You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by im...@apache.org on 2013/11/04 12:14:08 UTC

[1/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

Updated Branches:
  refs/heads/master f015d82ef -> b6793bdff


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/features/load-balancer/org.apache.stratos.lb.common.feature/pom.xml
----------------------------------------------------------------------
diff --git a/features/load-balancer/org.apache.stratos.lb.common.feature/pom.xml b/features/load-balancer/org.apache.stratos.lb.common.feature/pom.xml
deleted file mode 100644
index 0761415..0000000
--- a/features/load-balancer/org.apache.stratos.lb.common.feature/pom.xml
+++ /dev/null
@@ -1,86 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
-
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>loadbalancer-features</artifactId>
-        <version>4.0.0-SNAPSHOT</version>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.lb.common.feature</artifactId>
-    <packaging>pom</packaging>
-    <name>Apache Stratos - Load Balancer - Common Feature</name>
-    <url>http://apache.org</url>
-    <description>This feature contains the common bundle for loadbalancer features</description>
-
-    <dependencies>
-	<dependency>
-	    <groupId>org.apache.stratos</groupId>
-	    <artifactId>org.apache.stratos.lb.common</artifactId>
-	    <version>${project.version}</version>	
-	</dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.wso2.maven</groupId>
-                <artifactId>carbon-p2-plugin</artifactId>
-                <version>${carbon.p2.plugin.version}</version>
-                <executions>
-                    <execution>
-                        <id>4-p2-feature-generation</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>p2-feature-gen</goal>
-                        </goals>
-                        <configuration>
-                            <id>org.apache.stratos.lb.common</id>
-                            <propertiesFile>../../../etc/feature.properties</propertiesFile>
-                            <adviceFile>
-                                <properties>
-                                    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
-                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
-                                </properties>
-                            </adviceFile>
-                            <bundles>
-                                <!--bundleDef>org.wso2.carbon:org.wso2.carbon.load.balance.agent.stub</bundleDef>
-                                -->
-                                <bundleDef>org.apache.stratos:org.apache.stratos.lb.common:${project.version}</bundleDef>
-                                <bundleDef>org.slf4j:slf4j-api:1.6.4</bundleDef>
-                                <bundleDef>org.slf4j:slf4j-log4j12:1.6.4</bundleDef>
-                            </bundles>
-                            <importFeatures>
-                                <importFeatureDef>org.apache.synapse.wso2:${synapse.wso2.version}</importFeatureDef>
-                            </importFeatures>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/features/load-balancer/org.apache.stratos.lb.endpoint.server.feature/pom.xml
----------------------------------------------------------------------
diff --git a/features/load-balancer/org.apache.stratos.lb.endpoint.server.feature/pom.xml b/features/load-balancer/org.apache.stratos.lb.endpoint.server.feature/pom.xml
deleted file mode 100644
index eed667a..0000000
--- a/features/load-balancer/org.apache.stratos.lb.endpoint.server.feature/pom.xml
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-       Licensed to the Apache Software Foundation (ASF) under one
-       or more contributor license agreements.  See the NOTICE file
-       distributed with this work for additional information
-       regarding copyright ownership.  The ASF licenses this file
-       to you under the Apache License, Version 2.0 (the
-       "License"); you may not use this file except in compliance
-       with the License.  You may obtain a copy of the License at
-
-         http://www.apache.org/licenses/LICENSE-2.0
-
-       Unless required by applicable law or agreed to in writing,
-       software distributed under the License is distributed on an
-       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-       KIND, either express or implied.  See the License for the
-       specific language governing permissions and limitations
-       under the License.
-
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
-    <parent>
-        <groupId>org.apache.stratos</groupId>
-        <artifactId>loadbalancer-features</artifactId>
-        <version>4.0.0-SNAPSHOT</version>
-    </parent>
-
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>org.apache.stratos.lb.endpoint.server.feature</artifactId>
-    <packaging>pom</packaging>
-    <name>Apache Stratos - Load Balancer - Endpoint Management Feature</name>
-    <url>http://apache.org</url>
-    <description>This feature contains the required bundles for loadbalancer endpoint management functionality</description>
-
-    <dependencies>
-	<!--dependency>
-	    <groupId>org.wso2.carbon</groupId>
-	    <artifactId>org.wso2.carbon.lb.common</artifactId>
-	    <version>${project.version}</version>
-	</dependency-->
-	<dependency>
-	    <groupId>org.apache.stratos</groupId>
-	    <artifactId>org.apache.stratos.lb.endpoint</artifactId>
-	    <version>${project.version}</version>	
-	</dependency>
-    </dependencies>
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.wso2.maven</groupId>
-                <artifactId>carbon-p2-plugin</artifactId>
-                <version>${carbon.p2.plugin.version}</version>
-                <executions>
-                    <execution>
-                        <id>4-p2-feature-generation</id>
-                        <phase>package</phase>
-                        <goals>
-                            <goal>p2-feature-gen</goal>
-                        </goals>
-                        <configuration>
-                            <id>org.apache.stratos.lb.endpoint.server</id>
-                            <propertiesFile>../../../etc/feature.properties</propertiesFile>
-                            <adviceFile>
-                                <properties>
-                                    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
-                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
-                                </properties>
-                            </adviceFile>
-                            <bundles>
-                                <bundleDef>org.apache.stratos:org.apache.stratos.lb.endpoint:${project.version}</bundleDef>
-                            </bundles>
-                            <importFeatures>
-                                <importFeatureDef>org.wso2.carbon.core.server:${wso2carbon.version}</importFeatureDef>
-                                <importFeatureDef>org.apache.synapse.wso2:${synapse.wso2.version}</importFeatureDef>
-                            </importFeatures>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-    </build>
-<properties>
-	<carbon.patch.version.4.1.1>4.1.1</carbon.patch.version.4.1.1>
-</properties>
-
-</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/features/load-balancer/org.apache.stratos.load.balancer.common.feature/pom.xml
----------------------------------------------------------------------
diff --git a/features/load-balancer/org.apache.stratos.load.balancer.common.feature/pom.xml b/features/load-balancer/org.apache.stratos.load.balancer.common.feature/pom.xml
new file mode 100644
index 0000000..52d78c7
--- /dev/null
+++ b/features/load-balancer/org.apache.stratos.load.balancer.common.feature/pom.xml
@@ -0,0 +1,86 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>loadbalancer-features</artifactId>
+        <version>4.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.load.balancer.common.feature</artifactId>
+    <packaging>pom</packaging>
+    <name>Apache Stratos - Load Balancer - Common Feature</name>
+    <url>http://apache.org</url>
+    <description>This feature contains the common bundle for loadbalancer features</description>
+
+    <dependencies>
+	<dependency>
+	    <groupId>org.apache.stratos</groupId>
+	    <artifactId>org.apache.stratos.load.balancer.common</artifactId>
+	    <version>${project.version}</version>	
+	</dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.wso2.maven</groupId>
+                <artifactId>carbon-p2-plugin</artifactId>
+                <version>${carbon.p2.plugin.version}</version>
+                <executions>
+                    <execution>
+                        <id>4-p2-feature-generation</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>p2-feature-gen</goal>
+                        </goals>
+                        <configuration>
+                            <id>org.apache.stratos.load.balancer.common</id>
+                            <propertiesFile>../../../etc/feature.properties</propertiesFile>
+                            <adviceFile>
+                                <properties>
+                                    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
+                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
+                                </properties>
+                            </adviceFile>
+                            <bundles>
+                                <!--bundleDef>org.wso2.carbon:org.wso2.carbon.load.balance.agent.stub</bundleDef>
+                                -->
+                                <bundleDef>org.apache.stratos:org.apache.stratos.load.balancer.common:${project.version}</bundleDef>
+                                <bundleDef>org.slf4j:slf4j-api:1.6.4</bundleDef>
+                                <bundleDef>org.slf4j:slf4j-log4j12:1.6.4</bundleDef>
+                            </bundles>
+                            <importFeatures>
+                                <importFeatureDef>org.apache.synapse.wso2:${synapse.wso2.version}</importFeatureDef>
+                            </importFeatures>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/features/load-balancer/org.apache.stratos.load.balancer.feature/pom.xml
----------------------------------------------------------------------
diff --git a/features/load-balancer/org.apache.stratos.load.balancer.feature/pom.xml b/features/load-balancer/org.apache.stratos.load.balancer.feature/pom.xml
new file mode 100644
index 0000000..f8b6826
--- /dev/null
+++ b/features/load-balancer/org.apache.stratos.load.balancer.feature/pom.xml
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.apache.stratos</groupId>
+        <artifactId>loadbalancer-features</artifactId>
+        <version>4.0.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.apache.stratos.load.balancer.feature</artifactId>
+    <packaging>pom</packaging>
+    <name>Apache Stratos - Load Balancer - Management Feature</name>
+    <url>http://apache.org</url>
+    <description>This feature contains the required bundles for loadbalancer endpoint management functionality</description>
+
+    <dependencies>
+	<!--dependency>
+	    <groupId>org.wso2.carbon</groupId>
+	    <artifactId>org.wso2.carbon.lb.common</artifactId>
+	    <version>${project.version}</version>
+	</dependency-->
+	<dependency>
+	    <groupId>org.apache.stratos</groupId>
+	    <artifactId>org.apache.stratos.load.balancer</artifactId>
+	    <version>${project.version}</version>	
+	</dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.wso2.maven</groupId>
+                <artifactId>carbon-p2-plugin</artifactId>
+                <version>${carbon.p2.plugin.version}</version>
+                <executions>
+                    <execution>
+                        <id>4-p2-feature-generation</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>p2-feature-gen</goal>
+                        </goals>
+                        <configuration>
+                            <id>org.apache.stratos.load.balancer</id>
+                            <propertiesFile>../../../etc/feature.properties</propertiesFile>
+                            <adviceFile>
+                                <properties>
+                                    <propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
+                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
+                                </properties>
+                            </adviceFile>
+                            <bundles>
+                                <bundleDef>org.apache.stratos:org.apache.stratos.load.balancer:${project.version}</bundleDef>
+                            </bundles>
+                            <importFeatures>
+                                <importFeatureDef>org.wso2.carbon.core.server:${wso2carbon.version}</importFeatureDef>
+                                <importFeatureDef>org.apache.synapse.wso2:${synapse.wso2.version}</importFeatureDef>
+                            </importFeatures>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+<properties>
+	<carbon.patch.version.4.1.1>4.1.1</carbon.patch.version.4.1.1>
+</properties>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/features/load-balancer/pom.xml
----------------------------------------------------------------------
diff --git a/features/load-balancer/pom.xml b/features/load-balancer/pom.xml
index b43324c..920a91c 100644
--- a/features/load-balancer/pom.xml
+++ b/features/load-balancer/pom.xml
@@ -29,12 +29,12 @@
     <modelVersion>4.0.0</modelVersion>
     <artifactId>loadbalancer-features</artifactId>
     <packaging>pom</packaging>
-    <name>Apache Stratos - Load Balancer Module</name>
+    <name>Apache Stratos - Load Balancer - Feature Aggregator Module</name>
     <url>http://apache.org</url>
 
     <modules>
-	    <module>org.apache.stratos.lb.endpoint.server.feature</module>
-	    <module>org.apache.stratos.lb.common.feature</module>
+	    <module>org.apache.stratos.load.balancer.feature</module>
+	    <module>org.apache.stratos.load.balancer.common.feature</module>
     </modules>
 </project>
 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/products/cloud-controller/modules/p2-profile/pom.xml
----------------------------------------------------------------------
diff --git a/products/cloud-controller/modules/p2-profile/pom.xml b/products/cloud-controller/modules/p2-profile/pom.xml
index c54df43..27f7e8f 100644
--- a/products/cloud-controller/modules/p2-profile/pom.xml
+++ b/products/cloud-controller/modules/p2-profile/pom.xml
@@ -135,7 +135,7 @@
                                 </featureArtifactDef>
 
                                 <featureArtifactDef>
-                                    org.apache.stratos:org.apache.stratos.lb.common.feature:${project.version}
+                                    org.apache.stratos:org.apache.stratos.load.balancer.common.feature:${project.version}
                                 </featureArtifactDef>
 
                                 <featureArtifactDef>
@@ -244,7 +244,7 @@
                                     <version>${carbon.version}</version>
                                 </feature>
                                 <feature>
-                                    <id>org.apache.stratos.lb.common.feature.group</id>
+                                    <id>org.apache.stratos.load.balancer.common.feature.group</id>
                                     <version>${project.version}</version>
                                 </feature>
                                 <feature>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/products/load-balancer/modules/distribution/src/main/conf/log4j.properties
----------------------------------------------------------------------
diff --git a/products/load-balancer/modules/distribution/src/main/conf/log4j.properties b/products/load-balancer/modules/distribution/src/main/conf/log4j.properties
index 649bb4c..7e985aa 100644
--- a/products/load-balancer/modules/distribution/src/main/conf/log4j.properties
+++ b/products/load-balancer/modules/distribution/src/main/conf/log4j.properties
@@ -48,7 +48,7 @@ log4j.logger.com.atomikos=INFO,ATOMIKOS
 log4j.logger.org.quartz=WARN
 log4j.logger.org.wso2=INFO
 log4j.logger.org.wso2.carbon=INFO
-log4j.logger.org.apache.stratos.lb.endpoint=INFO
+log4j.logger.org.apache.stratos.load.balancer=INFO
 log4j.logger.org.apache.stratos.messaging=INFO
 
 log4j.logger.org.apache.catalina=WARN

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
----------------------------------------------------------------------
diff --git a/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml b/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
index b74c6d4..175a2bd 100644
--- a/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
+++ b/products/load-balancer/modules/distribution/src/main/conf/synapse-configs/default/sequences/main.xml
@@ -25,8 +25,8 @@
         <property name="SERVICE_PREFIX" expression="$axis2:SERVICE_PREFIX"/>
         <send>
 	          <endpoint name="tenantAwareLBEndpoint">
-                <class name ="org.apache.stratos.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint">
-                     <parameter name="algorithmClassName">org.apache.stratos.lb.endpoint.algorithm.RoundRobin</parameter>
+                <class name ="org.apache.stratos.load.balancer.endpoint.TenantAwareLoadBalanceEndpoint">
+                     <parameter name="algorithmClassName">org.apache.stratos.load.balancer.algorithm.RoundRobin</parameter>
                      <parameter name="failover">true</parameter>
                      <parameter name="sessionAffinity">true</parameter>
                      <parameter name="sessionTimeout">90000</parameter>
@@ -38,7 +38,7 @@
     </in>
     <out>
         <!-- Add response interceptor mediator -->
-        <class name="org.apache.stratos.lb.endpoint.mediators.ResponseInterceptor">
+        <class name="org.apache.stratos.load.balancer.mediators.ResponseInterceptor">
         </class>
 
         <!-- Updating location value in response header -->

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/products/load-balancer/modules/distribution/src/main/license/LICENSE
----------------------------------------------------------------------
diff --git a/products/load-balancer/modules/distribution/src/main/license/LICENSE b/products/load-balancer/modules/distribution/src/main/license/LICENSE
index 63ea050..91f1a4c 100644
--- a/products/load-balancer/modules/distribution/src/main/license/LICENSE
+++ b/products/load-balancer/modules/distribution/src/main/license/LICENSE
@@ -245,7 +245,7 @@ openstack-keystone_1.6.1.incubating.jar, openstack-nova_1.6.1.incubating.jar,
 org.apache.felix.gogo.command_0.8.0.v201108120515.jar,	org.apache.felix.gogo.runtime_0.8.0.v201108120515.jar
 org.apache.felix.gogo.shell_0.8.0.v201110170705.jar, org.apache.jasper.glassfish_2.2.2.v201205150955.jar,
 org.apache.stratos.lb.cartridge.autoscaler.service.stub_3.0.0.SNAPSHOT.jar, org.apache.stratos.lb.common_3.0.0.SNAPSHOT.jar
-org.apache.stratos.lb.endpoint_3.0.0.SNAPSHOT.jar
+org.apache.stratos.load.balancer_3.0.0.SNAPSHOT.jar
 org.jboss.netty_3.3.0.Final.jar, org.wso2.carbon.addressing_4.1.0.jar	
 org.wso2.carbon.apache.jasper.fragment_4.1.0.jar, org.wso2.carbon.application.deployer_4.1.0.jar
 org.wso2.carbon.authenticator.proxy_4.1.0.jar, org.wso2.carbon.authenticator.stub_4.1.0.jar

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/products/load-balancer/modules/p2-profile/pom.xml
----------------------------------------------------------------------
diff --git a/products/load-balancer/modules/p2-profile/pom.xml b/products/load-balancer/modules/p2-profile/pom.xml
index 5bad1db..b1daac4 100755
--- a/products/load-balancer/modules/p2-profile/pom.xml
+++ b/products/load-balancer/modules/p2-profile/pom.xml
@@ -141,7 +141,7 @@
                                 </featureArtifactDef>
 
                                 <featureArtifactDef>
-                                    org.apache.stratos:org.apache.stratos.lb.endpoint.server.feature:${project.version}
+                                    org.apache.stratos:org.apache.stratos.load.balancer.feature:${project.version}
                                 </featureArtifactDef>
 
                                 <featureArtifactDef>
@@ -281,7 +281,7 @@
                                     <version>${project.version}</version>
                                 </feature>
                                 <feature>
-                                    <id>org.apache.stratos.lb.endpoint.server.feature.group</id>
+                                    <id>org.apache.stratos.load.balancer.feature.group</id>
                                     <version>${project.version}</version>
                                 </feature>
                                 <feature>


[3/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

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

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/connect/TopicConnector.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/connect/TopicConnector.java b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/connect/TopicConnector.java
new file mode 100644
index 0000000..ed8aeef
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/connect/TopicConnector.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.common.mb.connect;
+
+import java.util.Properties;
+import java.io.File;
+
+import javax.jms.JMSException;
+import javax.jms.QueueSession;
+import javax.jms.Topic;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.TopicSession;
+import javax.naming.InitialContext;
+
+import org.apache.stratos.load.balancer.common.util.Util;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * This class is responsible for loading the jndi.properties file from the classpath
+ * and initialize the topic connection. Later if some other object needs a topic
+ * session, this object is capable of providing one. 
+ * @author nirmal
+ *
+ */
+public class TopicConnector {
+	
+	private TopicConnection topicConnection;
+	private String jndiPropFileDir = CarbonUtils.getCarbonConfigDirPath();
+	private String topicName;
+	private Topic topic;
+
+	public TopicConnector(String topic) {
+		jndiPropFileDir = System.getProperty("jndi.properties.dir");
+		topicName = topic;
+	}
+
+	public void init() throws Exception {
+		InitialContext ctx;
+		Properties environment = Util.getProperties(jndiPropFileDir+File.separator+"jndi.properties");
+		ctx = new InitialContext(environment);
+		// Lookup connection factory
+		TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx
+				.lookup("topicConnectionfactory");
+		topicConnection = connFactory.createTopicConnection();
+		setTopic((Topic) ctx.lookup(topicName));
+		topicConnection.start();
+
+	}
+
+	/**
+	 * Provides a new topic session.
+	 * @return topic session instance
+	 * @throws JMSException if unable to create a topic session
+	 */
+	public TopicSession newSession() throws Exception {
+		if(topicConnection == null) {
+			init();
+		}
+		return topicConnection.createTopicSession(false,
+				QueueSession.AUTO_ACKNOWLEDGE);
+	}
+	
+	public void close() throws JMSException {
+		if (topicConnection == null) {
+			return;
+		}
+		topicConnection.close();
+	}
+
+	public String getTopicName() {
+		return topicName;
+	}
+
+	public void setTopicName(String topicName) {
+		this.topicName = topicName;
+	}
+
+	public Topic getTopic() {
+		return topic;
+	}
+
+	public void setTopic(Topic topic) {
+		this.topic = topic;
+	}
+}

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/publish/TopicPublisher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/publish/TopicPublisher.java b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/publish/TopicPublisher.java
new file mode 100644
index 0000000..56625f0
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/publish/TopicPublisher.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.common.mb.publish;
+
+import javax.jms.*;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.load.balancer.common.mb.connect.TopicConnector;
+
+/**
+ * Any instance who needs to publish data to a topic, should communicate with this
+ * object.
+ * 
+ * @author nirmal
+ * 
+ */
+public class TopicPublisher {
+
+	private static final Log log = LogFactory.getLog(TopicPublisher.class);
+	private TopicSession topicSession;
+	private String topicName;
+	private TopicConnector connector;
+	private javax.jms.TopicPublisher topicPublisher = null;
+
+	/**
+	 * @param aTopicName
+	 *            topic name of this publisher instance.
+	 */
+	public TopicPublisher(String aTopicName) {
+		topicName = aTopicName;
+		connector = new TopicConnector(aTopicName);
+	}
+
+	/**
+	 * Publishes to a topic. If for some reason the connection to the topic got
+	 * lost, this will perform re-subscription periodically, until a connection
+	 * obtained.
+	 */
+	public void publish(String message) {
+
+		try {
+			doPublish(message);
+
+		} catch (Exception e) {
+			log.error("Error while publishing to the topic: " + topicName, e);
+		} 
+	}
+	
+	public void close() {
+		
+		// closes all sessions/connections
+		try {
+			if (topicPublisher != null) {
+				topicPublisher.close();
+			}
+			if (topicSession != null) {
+				topicSession.close();
+			}
+			if (connector != null) {
+				connector.close();
+			}
+		} catch (JMSException ignore) {
+		}
+	}
+
+	private void doPublish(String message) throws Exception, JMSException {
+		setPublisher();
+		
+		TextMessage textMessage = topicSession.createTextMessage(message);
+
+		topicPublisher.publish(textMessage);
+	}
+
+	private void setPublisher() throws Exception, JMSException {
+		if(topicSession != null && topicPublisher != null) {
+			return;
+		}
+		// initialize a TopicConnector
+		connector.init();
+		// get a session
+		topicSession = connector.newSession();
+		Topic topic = connector.getTopic();
+//		topic = topicSession.createTopic(topicName);
+		topicPublisher = topicSession.createPublisher(topic);
+	}
+	
+	public String getTopicName() {
+		return topicName;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/subscribe/TopicSubscriber.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/subscribe/TopicSubscriber.java b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/subscribe/TopicSubscriber.java
new file mode 100644
index 0000000..88c2cef
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/mb/subscribe/TopicSubscriber.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.common.mb.subscribe;
+
+import javax.jms.*;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.load.balancer.common.mb.connect.TopicConnector;
+import org.apache.stratos.load.balancer.common.mb.heartbeat.TopicHealthChecker;
+
+/**
+ * Any instance who needs to subscribe to a topic, should communicate with this
+ * object.
+ * 
+ * @author nirmal
+ * 
+ */
+public class TopicSubscriber implements Runnable {
+
+	private static final Log log = LogFactory.getLog(TopicSubscriber.class);
+	private MessageListener messageListener;
+	private TopicSession topicSession;
+	private String topicName;
+	TopicConnector connector;
+	javax.jms.TopicSubscriber topicSubscriber = null;
+
+	/**
+	 * @param aTopicName
+	 *            topic name of this subscriber instance.
+	 */
+	public TopicSubscriber(String aTopicName) {
+		topicName = aTopicName;
+		connector = new TopicConnector(aTopicName);
+	}
+
+	private void doSubscribe() throws Exception, JMSException {
+		// initialize a TopicConnector
+		connector.init();
+		// get a session
+		topicSession = connector.newSession();
+		Topic topic = connector.getTopic();
+		//since dynamic topic creation is not supported by most of the brokers
+//		topic = topicSession.createTopic(topicName);
+		topicSubscriber = topicSession.createSubscriber(topic);
+
+		topicSubscriber.setMessageListener(messageListener);
+	}
+
+	/**
+	 * @param aMessageListener
+	 *            this MessageListener will get triggered each time this
+	 *            subscription receives a message.
+	 */
+	public void setMessageListener(MessageListener aMessageListener) {
+
+		messageListener = aMessageListener;
+	}
+
+	/**
+	 * Subscribes to a topic. If for some reason the connection to the topic got
+	 * lost, this will perform re-subscription periodically, until a connection
+	 * obtained.
+	 */
+	@Override
+	public void run() {
+
+		while (true) {
+			try {
+				doSubscribe();
+
+			} catch (Exception e) {
+				log.error("Error while subscribing to the topic: " + topicName,
+						e);
+			} finally {
+				// start the health checker
+				Thread healthChecker = new Thread(new TopicHealthChecker(topicName));
+				healthChecker.start();
+				try {
+					// waits till the thread finishes.
+					healthChecker.join();
+				} catch (InterruptedException ignore) {
+				}
+				// health checker failed
+				// closes all sessions/connections
+				try {
+					if (topicSubscriber != null) {
+						topicSubscriber.close();
+					}
+					if (topicSession != null) {
+						topicSession.close();
+					}
+					if (connector != null) {
+						connector.close();
+					}
+				} catch (JMSException ignore) {
+				}
+			}
+		}
+	}
+
+}

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

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

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/util/Util.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/util/Util.java b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/util/Util.java
new file mode 100644
index 0000000..04b4c10
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/main/java/org/apache/stratos/load/balancer/common/util/Util.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.load.balancer.common.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Util {
+	private static final Log log = LogFactory.getLog(Util.class);
+
+	public static Properties getProperties(String filePath) {
+		Properties props = new Properties();
+		InputStream is = null;
+
+		// load properties from a properties file
+		try {
+			File f = new File(filePath);
+			is = new FileInputStream(f);
+			props.load(is);
+		} catch (Exception e) {
+			log.error("Failed to load properties from file: " + filePath, e);
+		} finally {
+			try {
+				is.close();
+			} catch (IOException ignore) {
+			}
+		}
+
+		return props;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.load.balancer.common/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..416d119
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/main/resources/META-INF/services.xml
@@ -0,0 +1,31 @@
+<?xml version='1.0'?>
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<serviceGroup>
+    <service name="LoadBalancerConfigurationService" scope="application">
+        <parameter name="ServiceClass">org.apache.stratos.load.balancer.common.service.impl.LoadBalancerConfigurationServiceImpl</parameter>
+        <messageReceivers>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
+        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
+    </messageReceivers>
+    </service>
+</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/test/java/org/apache/stratos/load/balancer/common/test/LoadBalancerConfigUtilTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/test/java/org/apache/stratos/load/balancer/common/test/LoadBalancerConfigUtilTest.java b/components/org.apache.stratos.load.balancer.common/src/test/java/org/apache/stratos/load/balancer/common/test/LoadBalancerConfigUtilTest.java
new file mode 100644
index 0000000..2eed44e
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/test/java/org/apache/stratos/load/balancer/common/test/LoadBalancerConfigUtilTest.java
@@ -0,0 +1,48 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.load.balancer.common.test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.stratos.load.balancer.common.conf.util.LoadBalancerConfigUtil;
+
+import junit.framework.TestCase;
+
+public class LoadBalancerConfigUtilTest extends TestCase {
+
+    private List<Integer> tenantList1 = Arrays.asList(1,2,3);
+    private List<Integer> tenantList2 = Arrays.asList(1,6,3,4);
+    private List<Integer> tenantList3 = Arrays.asList(43);
+    private List<Integer> tenantList4 = Arrays.asList(0);
+    
+    @Override
+    protected void setUp() throws Exception {
+
+    }
+    
+    public final void testGetTenantIds() {
+        
+        assertEquals(tenantList1, LoadBalancerConfigUtil.getTenantIds("1-3"));
+        assertEquals(tenantList2, LoadBalancerConfigUtil.getTenantIds("1,6,3,4"));
+        assertEquals(tenantList3, LoadBalancerConfigUtil.getTenantIds("43"));
+        assertEquals(tenantList4, LoadBalancerConfigUtil.getTenantIds("*"));
+    }
+
+}

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..7622e31
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer.conf
@@ -0,0 +1,84 @@
+#
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+    defaults {
+        min_app_instances 1;
+        max_app_instances       5;
+        max_requests_per_second   400;
+        alarming_upper_rate 0.65;
+        alarming_lower_rate 0.2;
+        scale_down_factor 0.25;
+        rounds_to_average       10;
+        instances_per_scale_up  1;
+        message_expiry_time     60000;
+    }
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            wso2.as1.domain {
+            	hosts as2.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      worker;
+                tenant_range    1-5;
+            }
+            wso2.as2.domain {
+                tenant_range    7;
+            }
+            wso2.as3.domain {
+                sub_domain nirmal;
+                tenant_range    10-20;
+            }
+            
+            wso2.as3.domain {
+                sub_domain nirmal2;
+                tenant_range    21-25;
+            }
+            
+            wso2.esb.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer1.conf b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer1.conf
new file mode 100644
index 0000000..9535f06
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer1.conf
@@ -0,0 +1,60 @@
+#
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#
+
+loadbalancer {
+    instances	1;
+    enable_autoscaler	true;
+    # interval between two task executions in milliseconds
+    autoscaler_task_interval	5000;
+    # after an instance booted up, task will wait till this much of time and let the server started up
+    server_startup_delay		15000; #default will be 60000ms
+}
+
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer2.conf b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer2.conf
new file mode 100644
index 0000000..6fd85f2
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/test/resources/loadbalancer2.conf
@@ -0,0 +1,50 @@
+#
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+services {
+
+    appserver {
+        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
+        sub_domain      worker1;
+        domains   {
+            
+            wso2.as.domain {
+            	sub_domain nirmal;
+                tenant_range    *;
+            }
+            wso2.as1.domain {
+            	sub_domain nirmal;
+                tenant_range    5-7;
+            }
+        }
+    }
+    
+    esb {
+        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
+        domains   {
+            wso2.esb.domain {
+                sub_domain      mgt;
+                tenant_range    *;
+            }
+        }
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer.common/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer.common/src/test/resources/testng.xml b/components/org.apache.stratos.load.balancer.common/src/test/resources/testng.xml
new file mode 100644
index 0000000..204f936
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer.common/src/test/resources/testng.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+-->
+
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="Default suite">
+  <test verbose="2" name="Default test">
+    <classes>
+      <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
+          <methods>
+            <include name="addZone" />
+              <include name="addHostMachine" />
+              <include name="deleteHostMachine" />
+          </methods>
+      </class-->
+    </classes>
+  </test>
+</suite>

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ClusterContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ClusterContext.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ClusterContext.java
new file mode 100644
index 0000000..f06495b
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ClusterContext.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer;
+
+import org.apache.stratos.load.balancer.algorithm.AlgorithmContext;
+
+import java.util.Properties;
+
+/**
+ * Defines cluster context properties.
+ */
+public class ClusterContext {
+    private String serviceName;
+    private String clusterId;
+    private AlgorithmContext algorithmContext;
+    private Properties properties;
+
+    public ClusterContext(String serviceName, String clusterId) {
+        this.serviceName = serviceName;
+        this.clusterId = clusterId;
+    }
+
+    public String getServiceName() {
+        return serviceName;
+    }
+
+    public String getClusterId() {
+        return clusterId;
+    }
+
+    public AlgorithmContext getAlgorithmContext() {
+        return algorithmContext;
+    }
+
+    public void setAlgorithmContext(AlgorithmContext algorithmContext) {
+        this.algorithmContext = algorithmContext;
+    }
+
+    public Properties getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Properties properties) {
+        this.properties = properties;
+    }
+}

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


[7/7] git commit: Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

Posted by im...@apache.org.
Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common


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

Branch: refs/heads/master
Commit: b6793bdff098ac16a95bdad983ddcb14f0887f27
Parents: f015d82
Author: Imesh Gunaratne <im...@apache.org>
Authored: Mon Nov 4 16:38:16 2013 +0530
Committer: Imesh Gunaratne <im...@apache.org>
Committed: Mon Nov 4 16:38:16 2013 +0530

----------------------------------------------------------------------
 .../org.apache.stratos.adc.topology.mgt/pom.xml |    7 +-
 .../adc/topology/mgt/util/ConfigHolder.java     |    5 -
 components/org.apache.stratos.lb.common/pom.xml |  122 --
 .../stratos/lb/common/cache/LRUCache.java       |  103 --
 .../lb/common/cache/URLMappingCache.java        |   47 -
 .../common/conf/LoadBalancerConfiguration.java  | 1202 ------------------
 .../LoadBalancerConfigurationDSComponent.java   |   47 -
 .../stratos/lb/common/conf/structure/Node.java  |  356 ------
 .../lb/common/conf/structure/NodeBuilder.java   |  140 --
 .../stratos/lb/common/conf/util/Constants.java  |   50 -
 .../lb/common/conf/util/HostContext.java        |  161 ---
 .../conf/util/LoadBalancerConfigUtil.java       |  305 -----
 .../common/conf/util/TenantDomainContext.java   |   80 --
 .../mgt/SubDomainAwareGroupManagementAgent.java |   58 -
 .../lb/common/mb/connect/TopicConnector.java    |  103 --
 .../common/mb/heartbeat/TopicHealthChecker.java |   81 --
 .../lb/common/mb/publish/TopicPublisher.java    |  109 --
 .../lb/common/mb/subscribe/TopicSubscriber.java |  119 --
 .../RequestTokenReplicationCommand.java         |   73 --
 .../LoadBalancerConfigurationService.java       |   79 --
 .../LoadBalancerConfigurationServiceImpl.java   |   48 -
 .../stratos/lb/common/util/DomainMapping.java   |   45 -
 .../org/apache/stratos/lb/common/util/Util.java |   54 -
 .../src/main/resources/META-INF/services.xml    |   31 -
 .../common/test/LoadBalancerConfigUtilTest.java |   48 -
 .../test/LoadBalancerConfigurationTest.java     |  169 ---
 .../stratos/lb/common/test/NodeBuilderTest.java |  123 --
 .../src/test/resources/loadbalancer.conf        |   84 --
 .../src/test/resources/loadbalancer1.conf       |   60 -
 .../src/test/resources/loadbalancer2.conf       |   50 -
 .../src/test/resources/testng.xml               |   36 -
 .../org.apache.stratos.lb.endpoint/pom.xml      |  135 --
 .../stratos/lb/endpoint/ClusterContext.java     |   63 -
 .../stratos/lb/endpoint/EndpointDeployer.java   |   79 --
 .../lb/endpoint/LoadBalancerContext.java        |  181 ---
 .../stratos/lb/endpoint/RequestDelegator.java   |  112 --
 .../stratos/lb/endpoint/ServiceContext.java     |   56 -
 ...TenantAwareLoadBalanceEndpointException.java |   39 -
 .../lb/endpoint/algorithm/AlgorithmContext.java |   51 -
 .../algorithm/LoadBalanceAlgorithm.java         |   65 -
 .../algorithm/LoadBalanceAlgorithmFactory.java  |   69 -
 .../lb/endpoint/algorithm/RoundRobin.java       |   97 --
 .../TenantAwareLoadBalanceEndpoint.java         |  517 --------
 .../LoadBalanceEndpointServiceComponent.java    |  333 -----
 .../endpoint/mediators/ResponseInterceptor.java |   58 -
 .../stat/LoadBalancingStatsCollector.java       |  110 --
 .../stat/observers/WSO2CEPStatsObserver.java    |  102 --
 .../stratos/lb/endpoint/util/Constants.java     |   27 -
 .../pom.xml                                     |  122 ++
 .../load/balancer/common/cache/LRUCache.java    |  103 ++
 .../balancer/common/cache/URLMappingCache.java  |   47 +
 .../common/conf/LoadBalancerConfiguration.java  | 1202 ++++++++++++++++++
 .../LoadBalancerConfigurationDSComponent.java   |   47 +
 .../balancer/common/conf/structure/Node.java    |  356 ++++++
 .../common/conf/structure/NodeBuilder.java      |  140 ++
 .../balancer/common/conf/util/Constants.java    |   50 +
 .../balancer/common/conf/util/HostContext.java  |  161 +++
 .../conf/util/LoadBalancerConfigUtil.java       |  305 +++++
 .../common/conf/util/TenantDomainContext.java   |   80 ++
 .../mgt/SubDomainAwareGroupManagementAgent.java |   58 +
 .../common/mb/connect/TopicConnector.java       |  103 ++
 .../common/mb/heartbeat/TopicHealthChecker.java |   81 ++
 .../common/mb/publish/TopicPublisher.java       |  109 ++
 .../common/mb/subscribe/TopicSubscriber.java    |  119 ++
 .../RequestTokenReplicationCommand.java         |   73 ++
 .../LoadBalancerConfigurationService.java       |   79 ++
 .../LoadBalancerConfigurationServiceImpl.java   |   48 +
 .../balancer/common/util/DomainMapping.java     |   45 +
 .../stratos/load/balancer/common/util/Util.java |   54 +
 .../src/main/resources/META-INF/services.xml    |   31 +
 .../common/test/LoadBalancerConfigUtilTest.java |   48 +
 .../test/LoadBalancerConfigurationTest.java     |  169 +++
 .../balancer/common/test/NodeBuilderTest.java   |  123 ++
 .../src/test/resources/loadbalancer.conf        |   84 ++
 .../src/test/resources/loadbalancer1.conf       |   60 +
 .../src/test/resources/loadbalancer2.conf       |   50 +
 .../src/test/resources/testng.xml               |   36 +
 .../org.apache.stratos.load.balancer/pom.xml    |  135 ++
 .../stratos/load/balancer/ClusterContext.java   |   63 +
 .../stratos/load/balancer/EndpointDeployer.java |   79 ++
 .../load/balancer/LoadBalancerContext.java      |  181 +++
 .../stratos/load/balancer/RequestDelegator.java |  112 ++
 .../stratos/load/balancer/ServiceContext.java   |   56 +
 ...TenantAwareLoadBalanceEndpointException.java |   39 +
 .../balancer/algorithm/AlgorithmContext.java    |   51 +
 .../algorithm/LoadBalanceAlgorithm.java         |   65 +
 .../algorithm/LoadBalanceAlgorithmFactory.java  |   69 +
 .../load/balancer/algorithm/RoundRobin.java     |   97 ++
 .../TenantAwareLoadBalanceEndpoint.java         |  517 ++++++++
 .../LoadBalanceEndpointServiceComponent.java    |  333 +++++
 .../balancer/mediators/ResponseInterceptor.java |   58 +
 .../stat/LoadBalancingStatsCollector.java       |  110 ++
 .../stat/observers/WSO2CEPStatsObserver.java    |  102 ++
 .../stratos/load/balancer/util/Constants.java   |   27 +
 components/pom.xml                              |    4 +-
 .../pom.xml                                     |   86 --
 .../pom.xml                                     |   91 --
 .../pom.xml                                     |   86 ++
 .../pom.xml                                     |   91 ++
 features/load-balancer/pom.xml                  |    6 +-
 .../cloud-controller/modules/p2-profile/pom.xml |    4 +-
 .../distribution/src/main/conf/log4j.properties |    2 +-
 .../synapse-configs/default/sequences/main.xml  |    6 +-
 .../distribution/src/main/license/LICENSE       |    2 +-
 .../load-balancer/modules/p2-profile/pom.xml    |    4 +-
 105 files changed, 6269 insertions(+), 6279 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.adc.topology.mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/pom.xml b/components/org.apache.stratos.adc.topology.mgt/pom.xml
index 85811a5..7a48fce 100644
--- a/components/org.apache.stratos.adc.topology.mgt/pom.xml
+++ b/components/org.apache.stratos.adc.topology.mgt/pom.xml
@@ -75,11 +75,6 @@
             <version>${wso2carbon.version}</version>
         </dependency>
         <dependency>
-            <groupId>org.apache.stratos</groupId>
-            <artifactId>org.apache.stratos.lb.common</artifactId>
-            <version>${project.version}</version>
-        </dependency>
-        <dependency>
             <groupId>org.wso2.carbon</groupId>
             <artifactId>org.wso2.carbon.ntask.core</artifactId>
 	    <version>${wso2carbon.version}</version>
@@ -127,7 +122,7 @@
 							org.apache.stratos.adc.topology.mgt.serviceobjects.*
                         </Export-Package>
                         <Import-Package>
-                            org.apache.stratos.lb.common.*; version=${project.version},
+                            org.apache.stratos.load.balancer.common.*; version=${project.version},
                             org.wso2.carbon.registry.core.service; version=1.0.1,
                             *;resolution:=optional
                         </Import-Package>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
index 2c088e8..e04308d 100644
--- a/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
+++ b/components/org.apache.stratos.adc.topology.mgt/src/main/java/org/apache/stratos/adc/topology/mgt/util/ConfigHolder.java
@@ -25,15 +25,10 @@ import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.stratos.adc.topology.mgt.exception.TopologyMgtException;
 import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration;
-import org.apache.stratos.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
-import org.apache.stratos.lb.common.service.LoadBalancerConfigurationService;
 import org.wso2.carbon.ntask.core.service.TaskService;
 import org.wso2.carbon.registry.core.session.UserRegistry;
 import org.wso2.carbon.user.core.service.RealmService;
 
-import java.util.List;
-import java.util.Map;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
 

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

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

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

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

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

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

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

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


[5/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/LoadBalancerContext.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/LoadBalancerContext.java
deleted file mode 100644
index 232d472..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/LoadBalancerContext.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.registry.core.session.UserRegistry;
-import org.wso2.carbon.user.core.service.RealmService;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Defines load balancer context information.
- */
-public class LoadBalancerContext {
-
-    private static volatile LoadBalancerContext instance;
-    private static final Log log = LogFactory.getLog(LoadBalancerContext.class);
-
-    private SynapseConfiguration synapseConfiguration;
-    private ConfigurationContext configCtxt;
-    private AxisConfiguration axisConfiguration;
-    private UserRegistry configRegistry;
-    private UserRegistry governanceRegistry;
-    private DependencyManagementService dependencyManager;
-    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices;
-
-    private Map<String, ServiceContext> serviceContextMap;
-    private Map<String, ClusterContext> clusterContextMap;
-
-    private LoadBalancerContext() {
-        synapseEnvironmentServices = new HashMap<Integer, SynapseEnvironmentService>();
-
-        serviceContextMap = new HashMap<String, ServiceContext>();
-        clusterContextMap = new HashMap<String, ClusterContext>();
-    }
-
-    public static synchronized LoadBalancerContext getInstance() {
-        if (instance == null) {
-            synchronized (LoadBalancerContext.class){
-                if (instance == null) {
-                    instance = new LoadBalancerContext ();
-                }
-            }
-        }
-        return instance;
-    }
-
-    public RealmService getRealmService() {
-        return realmService;
-    }
-
-    public void setRealmService(RealmService realmService) {
-        this.realmService = realmService;
-    }
-
-    private RealmService realmService;
-
-    public SynapseConfiguration getSynapseConfiguration() throws TenantAwareLoadBalanceEndpointException{
-        assertNull("SynapseConfiguration", synapseConfiguration);
-        return synapseConfiguration;
-    }
-
-    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
-        this.synapseConfiguration = synapseConfiguration;
-    }
-
-    public AxisConfiguration getAxisConfiguration() throws TenantAwareLoadBalanceEndpointException {
-        assertNull("AxisConfiguration", axisConfiguration);
-        return axisConfiguration;
-    }
-
-    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
-        this.axisConfiguration = axisConfiguration;
-    }
-
-    public UserRegistry getConfigRegistry() throws TenantAwareLoadBalanceEndpointException {
-        assertNull("Registry", configRegistry);
-        return configRegistry;
-    }
-
-    public void setConfigRegistry(UserRegistry configRegistry) {
-        this.configRegistry = configRegistry;
-    }
-
-    public DependencyManagementService getDependencyManager() {
-        return dependencyManager;
-    }
-
-    public void setDependencyManager(DependencyManagementService dependencyManager) {
-        this.dependencyManager = dependencyManager;
-    }
-
-    private void assertNull(String name, Object object) throws TenantAwareLoadBalanceEndpointException {
-        if (object == null) {
-            String message = name + " reference in the proxy admin config holder is null";
-            log.error(message);
-            throw new TenantAwareLoadBalanceEndpointException(message);
-        }
-    }
-
-    public UserRegistry getGovernanceRegistry() {
-        return governanceRegistry;
-    }
-
-    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
-        this.governanceRegistry = governanceRegistry;
-    }
-
-    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
-        return synapseEnvironmentServices.get(id);
-    }
-
-    public void addSynapseEnvironmentService(int id, SynapseEnvironmentService synapseEnvironmentService) {
-        synapseEnvironmentServices.put(id, synapseEnvironmentService);
-    }
-
-    public void removeSynapseEnvironmentService(int id) {
-        synapseEnvironmentServices.remove(id);
-    }
-
-    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
-        return synapseEnvironmentServices;
-    }
-
-    public ConfigurationContext getConfigCtxt() {
-        return configCtxt;
-    }
-
-    public void setConfigCtxt(ConfigurationContext configCtxt) {
-        this.configCtxt = configCtxt;
-    }
-
-    public Collection<ServiceContext> getServiceContexts() {
-        return serviceContextMap.values();
-    }
-
-    public ServiceContext getServiceContext(String serviceName) {
-        return serviceContextMap.get(serviceName);
-    }
-
-    public void addServiceContext(ServiceContext serviceContext) {
-        serviceContextMap.put(serviceContext.getServiceName(), serviceContext);
-    }
-
-    public Collection<ClusterContext> getClusterContexts() {
-        return clusterContextMap.values();
-    }
-
-    public ClusterContext getClusterContext(String clusterId) {
-        return clusterContextMap.get(clusterId);
-    }
-
-    public void addClusterContext(ClusterContext clusterContext) {
-        clusterContextMap.put(clusterContext.getClusterId(), clusterContext);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/RequestDelegator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/RequestDelegator.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/RequestDelegator.java
deleted file mode 100644
index 951d8f9..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/RequestDelegator.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-import org.apache.commons.lang.NotImplementedException;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.endpoint.algorithm.AlgorithmContext;
-import org.apache.stratos.lb.endpoint.algorithm.LoadBalanceAlgorithm;
-import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
-import org.apache.stratos.messaging.domain.topology.Cluster;
-import org.apache.stratos.messaging.domain.topology.Member;
-import org.apache.stratos.messaging.domain.topology.Service;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-/**
- * Implements core load balancing logic for identifying the next member
- * according to the incoming request information.
- */
-public class RequestDelegator {
-    private static final Log log = LogFactory.getLog(RequestDelegator.class);
-
-    private LoadBalanceAlgorithm algorithm;
-
-    public RequestDelegator(LoadBalanceAlgorithm algorithm) {
-        this.algorithm = algorithm;
-    }
-
-    public Member findNextMember(String targetHost) {
-
-        try {
-            if(targetHost == null)
-                return null;
-
-            TopologyManager.acquireReadLock();
-
-            Cluster cluster = findCluster(targetHost);
-            if(cluster != null) {
-                // Find algorithm context of the cluster
-                ClusterContext clusterContext = LoadBalancerContext.getInstance().getClusterContext(cluster.getClusterId());
-                if(clusterContext == null) {
-                    clusterContext = new ClusterContext(cluster.getServiceName(), cluster.getClusterId());
-                    LoadBalancerContext.getInstance().addClusterContext(clusterContext);
-                }
-
-                AlgorithmContext algorithmContext = clusterContext.getAlgorithmContext();
-                if(algorithmContext == null) {
-                    algorithmContext = new AlgorithmContext(cluster.getServiceName(), cluster.getClusterId());
-                    clusterContext.setAlgorithmContext(algorithmContext);
-                }
-                algorithm.setMembers(new ArrayList<Member>(cluster.getMembers()));
-                Member member = algorithm.getNextMember(algorithmContext);
-                if(log.isDebugEnabled()) {
-                    log.debug(String.format("Next member found: service: %s cluster id: %s member id: %s", member.getServiceName(), member.getClusterId(), member.getMemberId()));
-                }
-                return member;
-            }
-            return null;
-        }
-        finally {
-            TopologyManager.releaseReadLock();
-        }
-    }
-
-    public Member findNextMember(String serviceName, int tenantId, String targetHost) {
-        throw new NotImplementedException();
-    }
-
-    private Service findService(String serviceName) {
-        Collection<Service> services = TopologyManager.getTopology().getServices();
-        for (Service service : services) {
-            if(service.getServiceName().equals(serviceName))
-                return service;
-        }
-        return null;
-    }
-
-    private Cluster findCluster(String targetHost) {
-        Collection<Service> services = TopologyManager.getTopology().getServices();
-        for (Service service : services) {
-            for (Cluster cluster : service.getClusters()) {
-                if (targetHost.equals(cluster.getHostName())) {
-                    return cluster;
-                }
-            }
-        }
-        return null;
-    }
-
-    public boolean isTargetHostValid(String targetHost) {
-        return (findCluster(targetHost) != null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ServiceContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ServiceContext.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ServiceContext.java
deleted file mode 100644
index 7c4f8f8..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ServiceContext.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Defines service context properties.
- */
-public class ServiceContext {
-    private String serviceName;
-    private Map<String, ClusterContext> clusterContextMap;
-
-    public ServiceContext() {
-        clusterContextMap = new HashMap<String, ClusterContext>();
-    }
-
-    public String getServiceName() {
-        return serviceName;
-    }
-
-    public void setServiceName(String serviceName) {
-        this.serviceName = serviceName;
-    }
-
-    public Collection<ClusterContext> getClusterContexts() {
-        return clusterContextMap.values();
-    }
-
-    public ClusterContext getClusterContext(String clusterId) {
-        return clusterContextMap.get(clusterId);
-    }
-
-    public void addClusterContext(ClusterContext clusterContext) {
-        clusterContextMap.put(clusterContext.getClusterId(), clusterContext);
-    }
-}

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/AlgorithmContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/AlgorithmContext.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/AlgorithmContext.java
deleted file mode 100755
index 49430dc..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/AlgorithmContext.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.algorithm;
-
-/**
- * Algorithm context is used for identifying the cluster and its current member for executing load balancing algorithms.
- */
-public class AlgorithmContext {
-    private String serviceName;
-    private String clusterId;
-    private int currentMemberIndex;
-
-    public AlgorithmContext(String serviceName, String clusterId) {
-        this.serviceName = serviceName;
-        this.clusterId = clusterId;
-        this.currentMemberIndex = 0;
-    }
-
-    public String getServiceName() {
-        return serviceName;
-    }
-
-    public String getClusterId() {
-        return clusterId;
-    }
-
-    public int getCurrentMemberIndex() {
-        return currentMemberIndex;
-    }
-
-    public void setCurrentMemberIndex(int currentMemberIndex) {
-        this.currentMemberIndex = currentMemberIndex;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithm.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithm.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithm.java
deleted file mode 100755
index 1da2ba7..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithm.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.algorithm;
-
-import org.apache.stratos.messaging.domain.topology.Member;
-
-import java.util.List;
-
-/**
- * Defines the specification for implementing load balancing algorithms.
- */
-public interface LoadBalanceAlgorithm {
-    /**
-     * Return algorithm name.
-     *
-     * @return
-     */
-    public String getName();
-
-    /**
-     * Apply the algorithm and return the next member.
-     *
-     * @param algorithmContext
-     * @return
-     */
-    public Member getNextMember(AlgorithmContext algorithmContext);
-
-    /**
-     * Set member list of a given cluster.
-     *
-     * @param members
-     */
-    public void setMembers(List<Member> members);
-
-    /**
-     * Reset the algorithm and start from the beginning.
-     *
-     * @param algorithmContext
-     */
-    public void reset(AlgorithmContext algorithmContext);
-
-    /**
-     * Clone algorithm object.
-     *
-     * @return
-     */
-    public LoadBalanceAlgorithm clone();
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithmFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithmFactory.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithmFactory.java
deleted file mode 100644
index 4cc8c75..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/LoadBalanceAlgorithmFactory.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.algorithm;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.lang.reflect.InvocationTargetException;
-
-/**
- * Load balance algorithm factory to create the algorithm
- */
-public class LoadBalanceAlgorithmFactory {
-    private static final Log log = LogFactory.getLog(LoadBalanceAlgorithmFactory.class);
-
-
-    public static LoadBalanceAlgorithm createAlgorithm(String className) {
-        try {
-            Class algorithmClass = Class.forName(className);
-            try {
-                Object instance = algorithmClass.getConstructor().newInstance();
-                if (instance instanceof LoadBalanceAlgorithm) {
-                    return (LoadBalanceAlgorithm) instance;
-                } else {
-                    throw new RuntimeException(String.format("Class %s is not a valid load balance algorithm implementation"));
-                }
-            } catch (NoSuchMethodException e) {
-                if (log.isErrorEnabled()) {
-                    log.error(e);
-                }
-            } catch (InstantiationException e) {
-                if (log.isErrorEnabled()) {
-                    log.error(e);
-                }
-            } catch (IllegalAccessException e) {
-                if (log.isErrorEnabled()) {
-                    log.error(e);
-                }
-            } catch (InvocationTargetException e) {
-                if (log.isErrorEnabled()) {
-                    log.error(e);
-                }
-            }
-
-        } catch (ClassNotFoundException e) {
-            if (log.isErrorEnabled()) {
-                log.error(e);
-            }
-        }
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/RoundRobin.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/RoundRobin.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/RoundRobin.java
deleted file mode 100644
index f058ad6..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/algorithm/RoundRobin.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.algorithm;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.messaging.domain.topology.Member;
-
-import java.util.List;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * This is the implementation of the round robin load balancing algorithm. It simply iterates
- * through the endpoint list one by one for until an active endpoint is found.
- */
-public class RoundRobin implements LoadBalanceAlgorithm {
-    private static final Log log = LogFactory.getLog(RoundRobin.class);
-
-    private List<Member> members;
-    private final Lock lock = new ReentrantLock();
-
-    @Override
-    public String getName() {
-        return "Round Robin";
-    }
-
-    @Override
-    public Member getNextMember(AlgorithmContext algorithmContext) {
-        if (members.size() == 0) {
-            return null;
-        }
-        Member current = null;
-        lock.lock();
-        try {
-            int currentMemberIndex = algorithmContext.getCurrentMemberIndex();
-            if (currentMemberIndex >= members.size()) {
-                currentMemberIndex = 0;
-            }
-            int index = members.size();
-            do {                                                                   current = members.get(currentMemberIndex);
-                if (currentMemberIndex == members.size() - 1) {
-                    currentMemberIndex = 0;
-                } else {
-                    currentMemberIndex++;
-                }
-                index--;
-            } while ((!current.isActive()) && index > 0);
-            algorithmContext.setCurrentMemberIndex(currentMemberIndex);
-            if (log.isDebugEnabled()) {
-                log.debug(String.format("Service name: %s cluster id: %s members: %d", algorithmContext.getServiceName(), algorithmContext.getClusterId(), members.size()));
-                log.debug(String.format("Current member: %s", current.getMemberId()));
-            }
-
-        } finally {
-            lock.unlock();
-        }
-        return current;
-    }
-
-    @Override
-    public void setMembers(List<Member> members) {
-        this.members = members;
-    }
-
-    @Override
-    public void reset(AlgorithmContext algorithmContext) {
-        if (log.isDebugEnabled()) {
-            log.debug("Resetting the Round Robin load balancing algorithm ...");
-        }
-        synchronized (algorithmContext) {
-            algorithmContext.setCurrentMemberIndex(0);
-        }
-    }
-
-    @Override
-    public LoadBalanceAlgorithm clone() {
-        return new RoundRobin();
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
deleted file mode 100644
index 3cd3d1b..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.endpoint;
-
-import org.apache.axis2.addressing.EndpointReference;
-import org.apache.axis2.description.TransportInDescription;
-import org.apache.http.protocol.HTTP;
-import org.apache.stratos.lb.endpoint.RequestDelegator;
-import org.apache.stratos.lb.endpoint.algorithm.LoadBalanceAlgorithmFactory;
-import org.apache.stratos.lb.endpoint.stat.LoadBalancingStatsCollector;
-import org.apache.stratos.lb.endpoint.util.Constants;
-import org.apache.stratos.messaging.domain.topology.Member;
-import org.apache.stratos.messaging.domain.topology.Port;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.SynapseConstants;
-import org.apache.synapse.SynapseException;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.endpoints.AddressEndpoint;
-import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
-import org.apache.synapse.endpoints.Endpoint;
-import org.apache.synapse.endpoints.EndpointDefinition;
-import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
-import org.apache.synapse.endpoints.dispatch.SessionInformation;
-import org.apache.synapse.transport.nhttp.NhttpConstants;
-
-import java.io.Serializable;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.*;
-
-
-public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.LoadbalanceEndpoint implements Serializable {
-    private static final String PORT_MAPPING_PREFIX = "port.mapping.";
-
-    /* Request delegator identifies the next member */
-    private RequestDelegator requestDelegator;
-
-    /* Load balance algorithm class name */
-    private String algorithmClassName;
-
-    /* Flag to enable session affinity based load balancing */
-    private boolean sessionAffinity;
-
-    /* Dispatcher used for session affinity */
-    private HttpSessionDispatcher dispatcher;
-
-    /* Sessions time out interval */
-    private long sessionTimeout = -1;
-
-    @Override
-    public void init(SynapseEnvironment synapseEnvironment) {
-        super.init(synapseEnvironment);
-
-        requestDelegator = new RequestDelegator(LoadBalanceAlgorithmFactory.createAlgorithm(algorithmClassName));
-        synapseEnvironment.getSynapseConfiguration().setProperty(SynapseConstants.PROP_SAL_ENDPOINT_DEFAULT_SESSION_TIMEOUT, String.valueOf(sessionTimeout));
-        setDispatcher(new HttpSessionDispatcher());
-    }
-
-    @Override
-    public void send(MessageContext synCtx) {
-
-        SessionInformation sessionInformation = null;
-        org.apache.axis2.clustering.Member currentMember = null;
-        if (isSessionAffinityBasedLB()) {
-            // Check existing session information
-            sessionInformation = (SessionInformation) synCtx.getProperty(
-                    SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
-
-            currentMember = (org.apache.axis2.clustering.Member) synCtx.getProperty(
-                    SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);
-
-            if (sessionInformation == null && currentMember == null) {
-                sessionInformation = dispatcher.getSession(synCtx);
-                if (sessionInformation != null) {
-                    if (log.isDebugEnabled()) {
-                        log.debug(String.format("Existing session found: %s", sessionInformation.getId()));
-                    }
-
-                    currentMember = sessionInformation.getMember();
-                    synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
-                    // This is for reliably recovery any session information if while response is getting ,
-                    // session information has been removed by cleaner.
-                    // This will not be a cost as session information is not a heavy data structure
-                    synCtx.setProperty(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
-                }
-            }
-
-        }
-
-        TenantAwareLoadBalanceFaultHandler faultHandler = new TenantAwareLoadBalanceFaultHandler();
-        if (sessionInformation != null && currentMember != null) {
-            // Send request to the member with the existing session
-            sessionInformation.updateExpiryTime();
-            sendToApplicationMember(synCtx, currentMember, faultHandler, false);
-        } else {
-            // No existing session found
-            // Find next member
-            org.apache.axis2.clustering.Member axis2Member = findNextMember(synCtx);
-            if (axis2Member != null) {
-                // Send request to member
-                sendToApplicationMember(synCtx, axis2Member, faultHandler, true);
-            } else {
-                throwSynapseException(synCtx, 404, "Active application instances not found");
-            }
-        }
-    }
-
-    private void throwSynapseException(MessageContext synCtx, int errorCode, String errorMessage) {
-        synCtx.setProperty(SynapseConstants.ERROR_CODE, errorCode);
-        synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
-        throw new SynapseException(errorMessage);
-    }
-
-    /**
-     * Setup load balancer message context properties to be used by the out block of the main sequence.
-     * These values will be used to update the Location value in the response header.
-     *
-     * @param synCtx
-     */
-    private void setupLoadBalancerContextProperties(MessageContext synCtx) {
-        String lbHostName = extractTargetHost(synCtx);
-        org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-        TransportInDescription httpTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn("http");
-        TransportInDescription httpsTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn("https");
-        String lbHttpPort = (String) httpTransportIn.getParameter("port").getValue();
-        String lbHttpsPort = (String) httpsTransportIn.getParameter("port").getValue();
-
-        synCtx.setProperty(Constants.LB_HOST_NAME, lbHostName);
-        synCtx.setProperty(Constants.LB_HTTP_PORT, lbHttpPort);
-        synCtx.setProperty(Constants.LB_HTTPS_PORT, lbHttpsPort);
-    }
-
-
-    /**
-     * Adding the X-Forwarded-For/X-Originating-IP headers to the outgoing message.
-     *
-     * @param synCtx Current message context
-     */
-    protected void setupTransportHeaders(MessageContext synCtx) {
-        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
-        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
-        Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        if (headers != null && headers instanceof Map) {
-            Map headersMap = (Map) headers;
-            String xForwardFor = (String) headersMap.get(NhttpConstants.HEADER_X_FORWARDED_FOR);
-            String remoteHost = (String) axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
-
-            if (xForwardFor != null && !"".equals(xForwardFor)) {
-                StringBuilder xForwardedForString = new StringBuilder();
-                xForwardedForString.append(xForwardFor);
-                if (remoteHost != null && !"".equals(remoteHost)) {
-                    xForwardedForString.append(",").append(remoteHost);
-                }
-                headersMap.put(NhttpConstants.HEADER_X_FORWARDED_FOR, xForwardedForString.toString());
-            } else {
-                headersMap.put(NhttpConstants.HEADER_X_FORWARDED_FOR, remoteHost);
-            }
-
-            //Extracting information of X-Originating-IP
-            if (headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1) != null) {
-                headersMap.put(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1, headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1));
-            } else if (headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2) != null) {
-                headersMap.put(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2, headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2));
-            }
-
-        }
-    }
-
-    private org.apache.axis2.clustering.Member findNextMember(MessageContext synCtx) {
-        String targetHost = extractTargetHost(synCtx);
-        if(!requestDelegator.isTargetHostValid(targetHost)) {
-            throwSynapseException(synCtx, 404, String.format("Unknown host name %s", targetHost));
-        }
-        Member member = requestDelegator.findNextMember(targetHost);
-        if (member == null)
-            return null;
-
-        // Create Axi2 member object
-        String transport = extractTransport(synCtx);
-        Port transportPort = member.getPort(transport);
-        if (transportPort == null) {
-            if(log.isErrorEnabled()) {
-                log.error(String.format("Port not found for transport %s in member %s", transport, member.getMemberId()));
-            }
-            throwSynapseException(synCtx, 500, "Internal server error");
-        }
-
-        int memberPort = transportPort.getValue();
-        org.apache.axis2.clustering.Member axis2Member = new org.apache.axis2.clustering.Member(member.getMemberIp(), memberPort);
-        axis2Member.setDomain(member.getClusterId());
-        Port httpPort = member.getPort("http");
-        if (httpPort != null)
-            axis2Member.setHttpPort(httpPort.getValue());
-        Port httpsPort = member.getPort("https");
-        if (httpsPort != null)
-            axis2Member.setHttpsPort(httpsPort.getValue());
-        axis2Member.setActive(member.isActive());
-        return axis2Member;
-    }
-
-    private String extractTargetHost(MessageContext synCtx) {
-        org.apache.axis2.context.MessageContext msgCtx =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-
-        Map headerMap = (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        String hostName = null;
-        if (headerMap != null) {
-            Object hostObj = headerMap.get(HTTP.TARGET_HOST);
-            hostName = (String) hostObj;
-            if (hostName.contains(":")) {
-                hostName = hostName.substring(0, hostName.indexOf(":"));
-            }
-        }
-        return hostName;
-    }
-
-    private int extractPort(MessageContext synCtx, String transport) {
-        org.apache.axis2.context.MessageContext msgCtx =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-
-        Map headerMap = (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
-        int port = -1;
-        if (headerMap != null) {
-            String hostHeader = (String) headerMap.get(HTTP.TARGET_HOST);
-            int index = hostHeader.indexOf(':');
-            if (index != -1) {
-                port = Integer.parseInt(hostHeader.trim().substring(index + 1));
-            } else {
-                if ("http".equals(transport)) {
-                    port = 80;
-                } else if ("https".equals(transport)) {
-                    port = 443;
-                }
-            }
-        }
-        return port;
-    }
-
-    private String extractTransport(MessageContext synCtx) {
-        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-        return axis2MessageContext.getTransportIn().getName();
-    }
-
-    /**
-     * @param to     get an endpoint to send the information
-     * @param member The member to which an EP has to be created
-     * @param synCtx synapse context
-     * @return the created endpoint
-     */
-    private Endpoint getEndpoint(EndpointReference to, org.apache.axis2.clustering.Member member, MessageContext synCtx) {
-        AddressEndpoint endpoint = new AddressEndpoint();
-        endpoint.setEnableMBeanStats(false);
-        endpoint.setName("DLB:" + member.getHostName() +
-                ":" + member.getPort() + ":" + UUID.randomUUID());
-        EndpointDefinition definition = new EndpointDefinition();
-        definition.setSuspendMaximumDuration(10000);
-        definition.setReplicationDisabled(true);
-        definition.setAddress(to.getAddress());
-        endpoint.setDefinition(definition);
-        endpoint.init((SynapseEnvironment)
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext().
-                        getConfigurationContext().getAxisConfiguration().
-                        getParameterValue(SynapseConstants.SYNAPSE_ENV));
-        return endpoint;
-    }
-
-    private EndpointReference getEndpointReferenceAfterURLRewrite(org.apache.axis2.clustering.Member currentMember,
-                                                                  String transport,
-                                                                  String address,
-                                                                  int incomingPort) {
-
-        if (transport.startsWith("https")) {
-            transport = "https";
-        } else if (transport.startsWith("http")) {
-            transport = "http";
-        } else {
-            String msg = "Cannot load balance for non-HTTP/S transport " + transport;
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-        // URL Rewrite
-        if (transport.startsWith("http") || transport.startsWith("https")) {
-            if (address.startsWith("http://") || address.startsWith("https://")) {
-                try {
-                    String _address = address.indexOf("?") > 0 ? address.substring(address.indexOf("?"), address.length()) : "";
-                    address = new URL(address).getPath() + _address;
-                } catch (MalformedURLException e) {
-                    String msg = "URL " + address + " is malformed";
-                    log.error(msg, e);
-                    throw new SynapseException(msg, e);
-                }
-            }
-
-            int port;
-            Properties memberProperties = currentMember.getProperties();
-            String mappedPort = memberProperties.getProperty(PORT_MAPPING_PREFIX + incomingPort);
-            if (mappedPort != null) {
-                port = Integer.parseInt(mappedPort);
-            } else if (transport.startsWith("https")) {
-                port = currentMember.getHttpsPort();
-            } else {
-                port = currentMember.getHttpPort();
-            }
-
-            String remoteHost = memberProperties.getProperty("remoteHost");
-            String hostName = (remoteHost == null) ? currentMember.getHostName() : remoteHost;
-            return new EndpointReference(transport + "://" + hostName +
-                    ":" + port + address);
-        } else {
-            String msg = "Cannot load balance for non-HTTP/S transport " + transport;
-            log.error(msg);
-            throw new SynapseException(msg);
-        }
-    }
-
-    /*
-     * Preparing the endpoint sequence for a new session establishment request
-     */
-    private void prepareEndPointSequence(MessageContext synCtx, Endpoint endpoint) {
-
-        Object o = synCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST);
-        List<Endpoint> endpointList;
-        if (o instanceof List) {
-            endpointList = (List<Endpoint>) o;
-            endpointList.add(this);
-
-        } else {
-            // this is the first endpoint in the hierarchy. so create the queue and
-            // insert this as the first element.
-            endpointList = new ArrayList<Endpoint>();
-            endpointList.add(this);
-            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST, endpointList);
-        }
-
-        // if the next endpoint is not a session affinity one, endpoint sequence ends
-        // here. but we have to add the next endpoint to the list.
-        if (!(endpoint instanceof TenantAwareLoadBalanceEndpoint)) {
-            endpointList.add(endpoint);
-            // Clearing out if there any any session information with current message
-            if (dispatcher.isServerInitiatedSession()) {
-                dispatcher.removeSessionID(synCtx);
-            }
-        }
-    }
-
-    protected void sendToApplicationMember(MessageContext synCtx,
-                                           org.apache.axis2.clustering.Member currentMember,
-                                           DynamicLoadbalanceFaultHandler faultHandler,
-                                           boolean newSession) {
-        //Rewriting the URL
-        org.apache.axis2.context.MessageContext axis2MsgCtx =
-                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
-
-        //Removing the REST_URL_POSTFIX - this is a hack.
-        //In this load balance endpoint we create an endpoint per request by setting the complete url as the address.
-        //If a REST message comes Axis2FlexibleMEPClient append the REST_URL_POSTFIX to the address. Hence endpoint fails
-        //do send the request. e.g.  http://localhost:8080/example/index.html/example/index.html
-        axis2MsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
-
-        String transport = axis2MsgCtx.getTransportIn().getName();
-        String address = synCtx.getTo().getAddress();
-        int incomingPort = extractPort(synCtx, transport);
-        EndpointReference to = getEndpointReferenceAfterURLRewrite(currentMember, transport, address, incomingPort);
-        synCtx.setTo(to);
-
-        faultHandler.setTo(to);
-        faultHandler.setCurrentMember(currentMember);
-        synCtx.pushFaultHandler(faultHandler);
-        if (isFailover()) {
-            synCtx.getEnvelope().build();
-        }
-
-        Endpoint endpoint = getEndpoint(to, currentMember, synCtx);
-        faultHandler.setCurrentEp(endpoint);
-        if (isSessionAffinityBasedLB() && newSession) {
-            prepareEndPointSequence(synCtx, endpoint);
-            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
-            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER, dispatcher);
-            // we should also indicate that this is the first message in the session. so that
-            // onFault(...) method can resend only the failed attempts for the first message.
-            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_FIRST_MESSAGE_IN_SESSION,
-                    Boolean.TRUE);
-        }
-
-        Map<String, String> memberHosts;
-        if ((memberHosts = (Map<String, String>) currentMember.getProperties().get(HttpSessionDispatcher.HOSTS)) == null) {
-            currentMember.getProperties().put(HttpSessionDispatcher.HOSTS,
-                    memberHosts = new HashMap<String, String>());
-        }
-        memberHosts.put(extractTargetHost(synCtx), "true");
-        setupTransportHeaders(synCtx);
-        setupLoadBalancerContextProperties(synCtx);
-
-        // Update health stats
-        LoadBalancingStatsCollector.getInstance().incrementRequestInflightCount(currentMember.getDomain());
-        // Set the cluster id in the message context
-        synCtx.setProperty(Constants.CLUSTER_ID, currentMember.getDomain());
-
-        try {
-            if (log.isDebugEnabled()) {
-                log.debug(String.format("Sending request to endpoint: %s", to.getAddress()));
-            }
-            endpoint.send(synCtx);
-        } catch (Exception e) {
-            if (e.getMessage().toLowerCase().contains("io reactor shutdown")) {
-                log.fatal("System cannot continue normal operation. Restarting", e);
-                System.exit(121); // restart
-            } else {
-                throw new SynapseException(e);
-            }
-        }
-    }
-
-    public void setDispatcher(HttpSessionDispatcher dispatcher) {
-        this.dispatcher = dispatcher;
-    }
-
-    public HttpSessionDispatcher getDispatcher() {
-        return dispatcher;
-    }
-
-    public String getAlgorithmClassName() {
-        return algorithmClassName;
-    }
-
-    public void setAlgorithmClassName(String algorithmClassName) {
-        this.algorithmClassName = algorithmClassName;
-    }
-
-    public long getSessionTimeout() {
-        return sessionTimeout;
-    }
-
-    public void setSessionTimeout(long sessionTimeout) {
-        this.sessionTimeout = sessionTimeout;
-    }
-
-    public boolean isSessionAffinityBasedLB() {
-        return sessionAffinity;
-    }
-
-    public void setSessionAffinity(boolean sessionAffinity) {
-        this.sessionAffinity = sessionAffinity;
-    }
-
-    private class TenantAwareLoadBalanceFaultHandler extends DynamicLoadbalanceFaultHandler {
-        private org.apache.axis2.clustering.Member currentMember;
-        private Endpoint currentEp;
-        private EndpointReference to;
-
-        @Override
-        public void setCurrentMember(org.apache.axis2.clustering.Member currentMember) {
-            this.currentMember = currentMember;
-        }
-
-        @Override
-        public void setCurrentEp(Endpoint currentEp) {
-            this.currentEp = currentEp;
-        }
-
-        @Override
-        public void setTo(EndpointReference to) {
-            this.to = to;
-        }
-
-        @Override
-        public void onFault(MessageContext synCtx) {
-            //cleanup endpoint if exists
-            if (currentEp != null) {
-                currentEp.destroy();
-            }
-            if (currentMember == null) {
-                return;
-            }
-
-            Stack faultStack = synCtx.getFaultStack();
-            if (faultStack != null && !faultStack.isEmpty()) {
-                faultStack.pop();  // Remove the LoadbalanceFaultHandler
-            }
-
-            currentMember = findNextMember(synCtx);
-            if (currentMember == null) {
-                String msg = String.format("No application members available to serve the request %s", synCtx.getTo().getAddress());
-                log.error(msg);
-                throw new SynapseException(msg);
-            }
-            synCtx.setTo(to);
-            if (isSessionAffinityBasedLB()) {
-                //We are sending the this message on a new session,
-                // hence we need to remove previous session information
-                Set pros = synCtx.getPropertyKeySet();
-                if (pros != null) {
-                    pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
-                }
-            }
-            sendToApplicationMember(synCtx, currentMember, this, true);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
deleted file mode 100644
index 97a22a1..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint.internal;
-
-import org.apache.axis2.deployment.DeploymentEngine;
-import org.apache.axis2.engine.AxisConfiguration;
-import org.apache.stratos.lb.endpoint.LoadBalancerContext;
-import org.apache.stratos.lb.endpoint.TenantAwareLoadBalanceEndpointException;
-import org.apache.stratos.messaging.message.receiver.topology.TopologyEventMessageDelegator;
-import org.apache.stratos.messaging.message.receiver.topology.TopologyEventMessageReceiver;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.messaging.broker.subscribe.TopicSubscriber;
-import org.apache.stratos.messaging.util.Constants;
-import org.apache.synapse.config.SynapseConfiguration;
-import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.deployers.SynapseArtifactDeploymentStore;
-import org.apache.synapse.endpoints.Endpoint;
-import org.osgi.service.component.ComponentContext;
-import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
-import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
-import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
-import org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService;
-import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
-import org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService;
-import org.wso2.carbon.registry.core.exceptions.RegistryException;
-import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.utils.ConfigurationContextService;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-import org.wso2.carbon.user.core.service.RealmService;
-import org.apache.stratos.lb.endpoint.EndpointDeployer;
-
-import java.io.File;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @scr.component name="org.apache.stratos.lbr.endpoint" immediate="true"
- * @scr.reference name="configuration.context.service"
- * interface="org.wso2.carbon.utils.ConfigurationContextService"
- * cardinality="1..1" policy="dynamic"
- * bind="setConfigurationContextService"
- * unbind="unsetConfigurationContextService"
- * @scr.reference name="synapse.config.service" interface=
- * "org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
- * cardinality="1..1" policy="dynamic"
- * bind="setSynapseConfigurationService"
- * unbind="unsetSynapseConfigurationService"
- * @scr.reference name="synapse.env.service" interface=
- * "org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService"
- * cardinality="1..n" policy="dynamic"
- * bind="setSynapseEnvironmentService"
- * unbind="unsetSynapseEnvironmentService"
- * @scr.reference name="registry.service"
- * interface="org.wso2.carbon.registry.core.service.RegistryService"
- * cardinality="1..1" policy="dynamic" bind="setRegistryService"
- * unbind="unsetRegistryService"
- * @scr.reference name="dependency.mgt.service" interface=
- * "org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
- * cardinality="0..1" policy="dynamic"
- * bind="setDependencyManager" unbind="unsetDependencyManager"
- * @scr.reference name="synapse.registrations.service" interface=
- * "org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService"
- * cardinality="1..n" policy="dynamic"
- * bind="setSynapseRegistrationsService"
- * unbind="unsetSynapseRegistrationsService"
- * @scr.reference name="user.realmservice.default"
- * interface="org.wso2.carbon.user.core.service.RealmService"
- * cardinality="1..1" policy="dynamic" bind="setRealmService"
- * unbind="unsetRealmService"
- */
-@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
-public class LoadBalanceEndpointServiceComponent {
-    private static final Log log = LogFactory.getLog(LoadBalanceEndpointServiceComponent.class);
-
-    private boolean activated = false;
-
-    protected void activate(ComponentContext ctxt) {
-        try {
-            // Register endpoint deployer
-            SynapseEnvironmentService synEnvService = LoadBalancerContext.getInstance().getSynapseEnvironmentService(
-                    MultitenantConstants.SUPER_TENANT_ID);
-            registerDeployer(LoadBalancerContext.getInstance().getAxisConfiguration(),
-                    synEnvService.getSynapseEnvironment());
-
-            // Start topic subscriber thread
-            TopicSubscriber topicSubscriber = new TopicSubscriber(Constants.TOPOLOGY_TOPIC);
-            topicSubscriber.setMessageListener(new TopologyEventMessageReceiver());
-            Thread subscriberThread = new Thread(topicSubscriber);
-            subscriberThread.start();
-            if (log.isDebugEnabled()) {
-                log.debug("Topology event message receiver thread started");
-            }
-
-            // Start topology message receiver thread
-            Thread receiverThread = new Thread(new TopologyEventMessageDelegator());
-            receiverThread.start();
-            if (log.isDebugEnabled()) {
-                log.debug("Topology message processor thread started");
-            }
-
-            activated = true;
-            if (log.isDebugEnabled()) {
-                log.debug("LoadBalanceEndpointServiceComponent is activated ");
-            }
-        } catch (Throwable e) {
-            log.error("Failed to activate LoadBalanceEndpointServiceComponent", e);
-        }
-    }
-
-    protected void deactivate(ComponentContext context) {
-        try {
-            Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet = LoadBalancerContext
-                    .getInstance().getSynapseEnvironmentServices().entrySet();
-            for (Map.Entry<Integer, SynapseEnvironmentService> entry : entrySet) {
-                unregisterDeployer(entry.getValue().getConfigurationContext()
-                        .getAxisConfiguration(), entry.getValue()
-                        .getSynapseEnvironment());
-            }
-        } catch (Exception e) {
-            log.warn("Couldn't remove the EndpointDeployer");
-        }
-    }
-
-    /**
-     * Un-registers the Endpoint deployer.
-     *
-     * @param axisConfig         AxisConfiguration to which this deployer belongs
-     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
-     */
-    private void unregisterDeployer(AxisConfiguration axisConfig,
-                                    SynapseEnvironment synapseEnvironment)
-            throws TenantAwareLoadBalanceEndpointException {
-        if (axisConfig != null) {
-            DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
-                    .getConfigurator();
-            String synapseConfigPath = ServiceBusUtils
-                    .getSynapseConfigAbsPath(synapseEnvironment
-                            .getServerContextInformation());
-            String endpointDirPath = synapseConfigPath + File.separator
-                    + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
-            deploymentEngine.removeDeployer(endpointDirPath,
-                    ServiceBusConstants.ARTIFACT_EXTENSION);
-        }
-    }
-
-    /**
-     * Registers the Endpoint deployer.
-     *
-     * @param axisConfig         AxisConfiguration to which this deployer belongs
-     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
-     */
-    private void registerDeployer(AxisConfiguration axisConfig,
-                                  SynapseEnvironment synapseEnvironment)
-            throws TenantAwareLoadBalanceEndpointException {
-        SynapseConfiguration synCfg = synapseEnvironment
-                .getSynapseConfiguration();
-        DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
-                .getConfigurator();
-        SynapseArtifactDeploymentStore deploymentStore = synCfg
-                .getArtifactDeploymentStore();
-
-        String synapseConfigPath = ServiceBusUtils
-                .getSynapseConfigAbsPath(synapseEnvironment
-                        .getServerContextInformation());
-        String endpointDirPath = synapseConfigPath + File.separator
-                + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
-
-        for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
-            if (ep.getFileName() != null) {
-                deploymentStore.addRestoredArtifact(endpointDirPath
-                        + File.separator + ep.getFileName());
-            }
-        }
-        deploymentEngine.addDeployer(new EndpointDeployer(), endpointDirPath,
-                ServiceBusConstants.ARTIFACT_EXTENSION);
-    }
-
-    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        LoadBalancerContext.getInstance().setAxisConfiguration(cfgCtxService.getServerConfigContext().getAxisConfiguration());
-        LoadBalancerContext.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
-    }
-
-    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
-        LoadBalancerContext.getInstance().setAxisConfiguration(null);
-        LoadBalancerContext.getInstance().setConfigCtxt(null);
-    }
-
-    protected void setSynapseConfigurationService(SynapseConfigurationService synapseConfigurationService) {
-        LoadBalancerContext.getInstance().setSynapseConfiguration(synapseConfigurationService.getSynapseConfiguration());
-    }
-
-    protected void unsetSynapseConfigurationService(SynapseConfigurationService synapseConfigurationService) {
-        LoadBalancerContext.getInstance().setSynapseConfiguration(null);
-    }
-
-    /**
-     * Here we receive an event about the creation of a SynapseEnvironment. If
-     * this is SuperTenant we have to wait until all the other constraints are
-     * met and actual initialization is done in the activate method. Otherwise
-     * we have to do the activation here.
-     *
-     * @param synapseEnvironmentService SynapseEnvironmentService which contains information about the
-     *                                  new Synapse Instance
-     */
-    protected void setSynapseEnvironmentService(SynapseEnvironmentService synapseEnvironmentService) {
-        boolean alreadyCreated = LoadBalancerContext.getInstance()
-                .getSynapseEnvironmentServices()
-                .containsKey(synapseEnvironmentService.getTenantId());
-
-        LoadBalancerContext.getInstance().addSynapseEnvironmentService(
-                synapseEnvironmentService.getTenantId(),
-                synapseEnvironmentService);
-        if (activated) {
-            if (!alreadyCreated) {
-                try {
-                    registerDeployer(synapseEnvironmentService
-                            .getConfigurationContext().getAxisConfiguration(),
-                            synapseEnvironmentService.getSynapseEnvironment());
-                    if (log.isDebugEnabled()) {
-                        log.debug("Endpoint Admin bundle is activated ");
-                    }
-                } catch (Throwable e) {
-                    log.error("Failed to activate Endpoint Admin bundle ", e);
-                }
-            }
-        }
-    }
-
-    /**
-     * Here we receive an event about Destroying a SynapseEnvironment. This can
-     * be the super tenant destruction or a tenant destruction.
-     *
-     * @param synapseEnvironmentService synapseEnvironment
-     */
-    protected void unsetSynapseEnvironmentService(
-            SynapseEnvironmentService synapseEnvironmentService) {
-        LoadBalancerContext.getInstance().removeSynapseEnvironmentService(
-                synapseEnvironmentService.getTenantId());
-    }
-
-    protected void setRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService bound to the endpoint component");
-        }
-        try {
-            LoadBalancerContext.getInstance().setConfigRegistry(
-                    regService.getConfigSystemRegistry());
-            LoadBalancerContext.getInstance().setGovernanceRegistry(
-                    regService.getGovernanceSystemRegistry());
-        } catch (RegistryException e) {
-            log.error("Couldn't retrieve the registry from the registry service");
-        }
-    }
-
-    protected void unsetRegistryService(RegistryService regService) {
-        if (log.isDebugEnabled()) {
-            log.debug("RegistryService unbound from the endpoint component");
-        }
-        LoadBalancerContext.getInstance().setConfigRegistry(null);
-    }
-
-    protected void setDependencyManager(
-            DependencyManagementService dependencyMgr) {
-        if (log.isDebugEnabled()) {
-            log.debug("Dependency management service bound to the endpoint component");
-        }
-        LoadBalancerContext.getInstance().setDependencyManager(dependencyMgr);
-    }
-
-    protected void unsetDependencyManager(
-            DependencyManagementService dependencyMgr) {
-        if (log.isDebugEnabled()) {
-            log.debug("Dependency management service unbound from the endpoint component");
-        }
-        LoadBalancerContext.getInstance().setDependencyManager(null);
-    }
-
-    protected void setSynapseRegistrationsService(
-            SynapseRegistrationsService synapseRegistrationsService) {
-
-    }
-
-    protected void unsetSynapseRegistrationsService(
-            SynapseRegistrationsService synapseRegistrationsService) {
-        int tenantId = synapseRegistrationsService.getTenantId();
-        if (LoadBalancerContext.getInstance().getSynapseEnvironmentServices()
-                .containsKey(tenantId)) {
-            SynapseEnvironment env = LoadBalancerContext.getInstance()
-                    .getSynapseEnvironmentService(tenantId)
-                    .getSynapseEnvironment();
-
-            LoadBalancerContext.getInstance().removeSynapseEnvironmentService(
-                    synapseRegistrationsService.getTenantId());
-
-            AxisConfiguration axisConfig = synapseRegistrationsService
-                    .getConfigurationContext().getAxisConfiguration();
-            if (axisConfig != null) {
-                try {
-                    unregisterDeployer(axisConfig, env);
-                } catch (Exception e) {
-                    log.warn("Couldn't remove the EndpointDeployer");
-                }
-            }
-        }
-    }
-
-    protected void setRealmService(RealmService realmService) {
-        LoadBalancerContext.getInstance().setRealmService(realmService);
-    }
-
-    protected void unsetRealmService(RealmService realmService) {
-        LoadBalancerContext.getInstance().setRealmService(null);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/mediators/ResponseInterceptor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/mediators/ResponseInterceptor.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/mediators/ResponseInterceptor.java
deleted file mode 100644
index 33ef9ac..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/mediators/ResponseInterceptor.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.endpoint.mediators;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.stratos.lb.endpoint.stat.LoadBalancingStatsCollector;
-import org.apache.stratos.lb.endpoint.util.Constants;
-import org.apache.synapse.ManagedLifecycle;
-import org.apache.synapse.MessageContext;
-import org.apache.synapse.core.SynapseEnvironment;
-import org.apache.synapse.core.axis2.Axis2MessageContext;
-import org.apache.synapse.mediators.AbstractMediator;
-
-/**
- * This Synapse mediator counts the responses that are going across LB.
- * 
- */
-public class ResponseInterceptor extends AbstractMediator implements ManagedLifecycle {
-
-    public boolean mediate(MessageContext synCtx) {
-        if(log.isDebugEnabled()) {
-            log.debug("Mediation started " + ResponseInterceptor.class.getName());
-        }
-        String clusterId = (String) synCtx.getProperty(Constants.CLUSTER_ID);
-        LoadBalancingStatsCollector.getInstance().decrementRequestInflightCount(clusterId);
-        return true;
-    }
-
-    @Override
-    public void destroy() {
-        if(log.isDebugEnabled()) {
-            log.debug("ResponseInterceptor mediator destroyed");
-        }
-    }
-
-    @Override
-    public void init(SynapseEnvironment arg0) {
-        if(log.isDebugEnabled()) {
-            log.debug("ResponseInterceptor mediator initiated");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/LoadBalancingStatsCollector.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/LoadBalancingStatsCollector.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/LoadBalancingStatsCollector.java
deleted file mode 100644
index bc6183d..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/LoadBalancingStatsCollector.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.lb.endpoint.stat;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Observable;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.stratos.lb.endpoint.stat.observers.WSO2CEPStatsObserver;
-
-/**
- * This is the load balancing stats collector and any observer can get registered here 
- * and receive notifications periodically.
- * This is a Singleton object.
- * @author nirmal
- *
- */
-public class LoadBalancingStatsCollector extends Observable{
-
-	private static LoadBalancingStatsCollector collector;
-	private Map<String, Integer> clusterIdToRequestInflightCountMap;
-	private Thread notifier;
-	
-	private LoadBalancingStatsCollector() {
-		clusterIdToRequestInflightCountMap = new ConcurrentHashMap<String, Integer>();
-		if (notifier == null || (notifier != null && !notifier.isAlive())) {
-			notifier = new Thread(new ObserverNotifier());
-			notifier.start();
-		}
-    }
-	
-	public static LoadBalancingStatsCollector getInstance() {
-		if (collector == null) {
-			synchronized (LoadBalancingStatsCollector.class) {
-				if (collector == null) {
-					collector = new LoadBalancingStatsCollector();
-					// add observers
-					collector.addObserver(new WSO2CEPStatsObserver());
-				}
-			}
-		}
-		return collector;
-	}
-	
-	public void incrementRequestInflightCount(String clusterId) {
-		if(clusterId == null) {
-			return;
-		}
-		
-		int value = 1;
-		if(clusterIdToRequestInflightCountMap.get(clusterId) != null) {
-			value += clusterIdToRequestInflightCountMap.get(clusterId);
-		}
-		clusterIdToRequestInflightCountMap.put(clusterId, value);
-		setChanged();
-	}
-	
-	public void decrementRequestInflightCount(String clusterId) {
-		if(clusterId == null) {
-			return;
-		}
-		
-		int value = -1;
-		if(clusterIdToRequestInflightCountMap.get(clusterId) != null) {
-			value += clusterIdToRequestInflightCountMap.get(clusterId);
-		}
-		clusterIdToRequestInflightCountMap.put(clusterId, value);
-		setChanged();
-	}
-	
-	
-	/**
-	 * This thread will notify all the observers of this subject.
-	 * @author nirmal
-	 *
-	 */
-	private class ObserverNotifier implements Runnable {
-
-		@Override
-        public void run() {
-			while(true) {
-				try {
-	                Thread.sleep(15000);
-                } catch (InterruptedException ignore) {
-                }
-				LoadBalancingStatsCollector.getInstance().notifyObservers(new HashMap<String, Integer>(clusterIdToRequestInflightCountMap));
-			}
-	        
-        }
-		
-	}
-	
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/observers/WSO2CEPStatsObserver.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/observers/WSO2CEPStatsObserver.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/observers/WSO2CEPStatsObserver.java
deleted file mode 100644
index 60e960c..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/stat/observers/WSO2CEPStatsObserver.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.lb.endpoint.stat.observers;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.databridge.agent.thrift.Agent;
-import org.wso2.carbon.databridge.agent.thrift.AsyncDataPublisher;
-import org.wso2.carbon.databridge.agent.thrift.conf.AgentConfiguration;
-import org.wso2.carbon.databridge.agent.thrift.exception.AgentException;
-import org.wso2.carbon.databridge.commons.Event;
-import org.wso2.carbon.utils.CarbonUtils;
-
-public class WSO2CEPStatsObserver implements Observer{
-
-	private static final Log log = LogFactory.getLog(WSO2CEPStatsObserver.class);
-	private static final String CALL_CENTER_DATA_STREAM = "stratos.lb.stats";
-	private static final String VERSION = "1.0.0";
-	private AsyncDataPublisher asyncDataPublisher;
-	
-	public WSO2CEPStatsObserver() {
-		AgentConfiguration agentConfiguration = new AgentConfiguration();
-        // TODO get following from somewhere, without hard-coding.
-        System.setProperty("javax.net.ssl.trustStore", CarbonUtils.getCarbonHome()+File.separator+"repository"+
-                           File.separator+"resources"+File.separator+"security"+File.separator+"client-truststore.jks"	);
-        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
-        
-        Agent agent = new Agent(agentConfiguration);
-        //TODO read following from a config file?
-        String ip = System.getProperty("thrift.receiver.ip");
-        String port = System.getProperty("thrift.receiver.port");
-        //Using Asynchronous data publisher
-        asyncDataPublisher = new AsyncDataPublisher("tcp://"+ip+":"+port+"", "admin", "admin", agent);
-        String streamDefinition = "{" +
-                                  " 'name':'" + CALL_CENTER_DATA_STREAM + "'," +
-                                  " 'version':'" + VERSION + "'," +
-                                  " 'nickName': 'lb stats'," +
-                                  " 'description': 'lb stats'," +
-                                  " 'metaData':[]," +
-                                  " 'payloadData':[" +
-                                  " {'name':'cluster_id','type':'STRING'}," +
-                                  " {'name':'in_flight_requests','type':'INT'}" +
-                                  " ]" +
-                                  "}";
-        asyncDataPublisher.addStreamDefinition(streamDefinition, CALL_CENTER_DATA_STREAM, VERSION);
-    }
-	
-	public void update(Observable arg0, Object arg1) {
-		if(arg1 != null && arg1 instanceof Map<?, ?>) {
-			Map<String, Integer> stats = (Map<String, Integer>)arg1;
-			publishEvents(stats);
-		}
-	}
-	
-    private void publishEvents(Map<String, Integer> stats) {
-    	
-    	for (Map.Entry<String, Integer> entry : stats.entrySet()) {
-    		
-    		Object[] payload = new Object[]{entry.getKey(), entry.getValue()};
-    		Event event = eventObject(null, null, payload, new HashMap<String, String>());
-    		try {
-    			asyncDataPublisher.publish(CALL_CENTER_DATA_STREAM, VERSION, event);
-    		} catch (AgentException e) {
-    			log.error("Failed to publish events. ", e);
-    		}
-    		
-    	}
-    	stats = null;
-    }
-    
-    private static Event eventObject(Object[] correlationData, Object[] metaData,
-                                     Object[] payLoadData, HashMap<String, String> map) {
-        Event event = new Event();
-        event.setCorrelationData(correlationData);
-        event.setMetaData(metaData);
-        event.setPayloadData(payLoadData);
-        event.setArbitraryDataMap(map);
-        return event;
-    }
-}

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


[2/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

Posted by im...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/LoadBalancerContext.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/LoadBalancerContext.java
new file mode 100644
index 0000000..02f1a23
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/LoadBalancerContext.java
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.config.SynapseConfiguration;
+import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
+import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Defines load balancer context information.
+ */
+public class LoadBalancerContext {
+
+    private static volatile LoadBalancerContext instance;
+    private static final Log log = LogFactory.getLog(LoadBalancerContext.class);
+
+    private SynapseConfiguration synapseConfiguration;
+    private ConfigurationContext configCtxt;
+    private AxisConfiguration axisConfiguration;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+    private DependencyManagementService dependencyManager;
+    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices;
+
+    private Map<String, ServiceContext> serviceContextMap;
+    private Map<String, ClusterContext> clusterContextMap;
+
+    private LoadBalancerContext() {
+        synapseEnvironmentServices = new HashMap<Integer, SynapseEnvironmentService>();
+
+        serviceContextMap = new HashMap<String, ServiceContext>();
+        clusterContextMap = new HashMap<String, ClusterContext>();
+    }
+
+    public static synchronized LoadBalancerContext getInstance() {
+        if (instance == null) {
+            synchronized (LoadBalancerContext.class){
+                if (instance == null) {
+                    instance = new LoadBalancerContext ();
+                }
+            }
+        }
+        return instance;
+    }
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    private RealmService realmService;
+
+    public SynapseConfiguration getSynapseConfiguration() throws TenantAwareLoadBalanceEndpointException{
+        assertNull("SynapseConfiguration", synapseConfiguration);
+        return synapseConfiguration;
+    }
+
+    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
+        this.synapseConfiguration = synapseConfiguration;
+    }
+
+    public AxisConfiguration getAxisConfiguration() throws TenantAwareLoadBalanceEndpointException {
+        assertNull("AxisConfiguration", axisConfiguration);
+        return axisConfiguration;
+    }
+
+    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
+        this.axisConfiguration = axisConfiguration;
+    }
+
+    public UserRegistry getConfigRegistry() throws TenantAwareLoadBalanceEndpointException {
+        assertNull("Registry", configRegistry);
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+
+    public DependencyManagementService getDependencyManager() {
+        return dependencyManager;
+    }
+
+    public void setDependencyManager(DependencyManagementService dependencyManager) {
+        this.dependencyManager = dependencyManager;
+    }
+
+    private void assertNull(String name, Object object) throws TenantAwareLoadBalanceEndpointException {
+        if (object == null) {
+            String message = name + " reference in the proxy admin config holder is null";
+            log.error(message);
+            throw new TenantAwareLoadBalanceEndpointException(message);
+        }
+    }
+
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+    public SynapseEnvironmentService getSynapseEnvironmentService(int id) {
+        return synapseEnvironmentServices.get(id);
+    }
+
+    public void addSynapseEnvironmentService(int id, SynapseEnvironmentService synapseEnvironmentService) {
+        synapseEnvironmentServices.put(id, synapseEnvironmentService);
+    }
+
+    public void removeSynapseEnvironmentService(int id) {
+        synapseEnvironmentServices.remove(id);
+    }
+
+    public Map<Integer, SynapseEnvironmentService> getSynapseEnvironmentServices() {
+        return synapseEnvironmentServices;
+    }
+
+    public ConfigurationContext getConfigCtxt() {
+        return configCtxt;
+    }
+
+    public void setConfigCtxt(ConfigurationContext configCtxt) {
+        this.configCtxt = configCtxt;
+    }
+
+    public Collection<ServiceContext> getServiceContexts() {
+        return serviceContextMap.values();
+    }
+
+    public ServiceContext getServiceContext(String serviceName) {
+        return serviceContextMap.get(serviceName);
+    }
+
+    public void addServiceContext(ServiceContext serviceContext) {
+        serviceContextMap.put(serviceContext.getServiceName(), serviceContext);
+    }
+
+    public Collection<ClusterContext> getClusterContexts() {
+        return clusterContextMap.values();
+    }
+
+    public ClusterContext getClusterContext(String clusterId) {
+        return clusterContextMap.get(clusterId);
+    }
+
+    public void addClusterContext(ClusterContext clusterContext) {
+        clusterContextMap.put(clusterContext.getClusterId(), clusterContext);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/RequestDelegator.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/RequestDelegator.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/RequestDelegator.java
new file mode 100644
index 0000000..583541b
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/RequestDelegator.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer;
+
+import org.apache.commons.lang.NotImplementedException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.load.balancer.algorithm.AlgorithmContext;
+import org.apache.stratos.load.balancer.algorithm.LoadBalanceAlgorithm;
+import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
+import org.apache.stratos.messaging.domain.topology.Cluster;
+import org.apache.stratos.messaging.domain.topology.Member;
+import org.apache.stratos.messaging.domain.topology.Service;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Implements core load balancing logic for identifying the next member
+ * according to the incoming request information.
+ */
+public class RequestDelegator {
+    private static final Log log = LogFactory.getLog(RequestDelegator.class);
+
+    private LoadBalanceAlgorithm algorithm;
+
+    public RequestDelegator(LoadBalanceAlgorithm algorithm) {
+        this.algorithm = algorithm;
+    }
+
+    public Member findNextMember(String targetHost) {
+
+        try {
+            if(targetHost == null)
+                return null;
+
+            TopologyManager.acquireReadLock();
+
+            Cluster cluster = findCluster(targetHost);
+            if(cluster != null) {
+                // Find algorithm context of the cluster
+                ClusterContext clusterContext = LoadBalancerContext.getInstance().getClusterContext(cluster.getClusterId());
+                if(clusterContext == null) {
+                    clusterContext = new ClusterContext(cluster.getServiceName(), cluster.getClusterId());
+                    LoadBalancerContext.getInstance().addClusterContext(clusterContext);
+                }
+
+                AlgorithmContext algorithmContext = clusterContext.getAlgorithmContext();
+                if(algorithmContext == null) {
+                    algorithmContext = new AlgorithmContext(cluster.getServiceName(), cluster.getClusterId());
+                    clusterContext.setAlgorithmContext(algorithmContext);
+                }
+                algorithm.setMembers(new ArrayList<Member>(cluster.getMembers()));
+                Member member = algorithm.getNextMember(algorithmContext);
+                if(log.isDebugEnabled()) {
+                    log.debug(String.format("Next member found: service: %s cluster id: %s member id: %s", member.getServiceName(), member.getClusterId(), member.getMemberId()));
+                }
+                return member;
+            }
+            return null;
+        }
+        finally {
+            TopologyManager.releaseReadLock();
+        }
+    }
+
+    public Member findNextMember(String serviceName, int tenantId, String targetHost) {
+        throw new NotImplementedException();
+    }
+
+    private Service findService(String serviceName) {
+        Collection<Service> services = TopologyManager.getTopology().getServices();
+        for (Service service : services) {
+            if(service.getServiceName().equals(serviceName))
+                return service;
+        }
+        return null;
+    }
+
+    private Cluster findCluster(String targetHost) {
+        Collection<Service> services = TopologyManager.getTopology().getServices();
+        for (Service service : services) {
+            for (Cluster cluster : service.getClusters()) {
+                if (targetHost.equals(cluster.getHostName())) {
+                    return cluster;
+                }
+            }
+        }
+        return null;
+    }
+
+    public boolean isTargetHostValid(String targetHost) {
+        return (findCluster(targetHost) != null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ServiceContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ServiceContext.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ServiceContext.java
new file mode 100644
index 0000000..58d461a
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/ServiceContext.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Defines service context properties.
+ */
+public class ServiceContext {
+    private String serviceName;
+    private Map<String, ClusterContext> clusterContextMap;
+
+    public ServiceContext() {
+        clusterContextMap = new HashMap<String, ClusterContext>();
+    }
+
+    public String getServiceName() {
+        return serviceName;
+    }
+
+    public void setServiceName(String serviceName) {
+        this.serviceName = serviceName;
+    }
+
+    public Collection<ClusterContext> getClusterContexts() {
+        return clusterContextMap.values();
+    }
+
+    public ClusterContext getClusterContext(String clusterId) {
+        return clusterContextMap.get(clusterId);
+    }
+
+    public void addClusterContext(ClusterContext clusterContext) {
+        clusterContextMap.put(clusterContext.getClusterId(), clusterContext);
+    }
+}

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/AlgorithmContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/AlgorithmContext.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/AlgorithmContext.java
new file mode 100755
index 0000000..24bc70d
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/AlgorithmContext.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.algorithm;
+
+/**
+ * Algorithm context is used for identifying the cluster and its current member for executing load balancing algorithms.
+ */
+public class AlgorithmContext {
+    private String serviceName;
+    private String clusterId;
+    private int currentMemberIndex;
+
+    public AlgorithmContext(String serviceName, String clusterId) {
+        this.serviceName = serviceName;
+        this.clusterId = clusterId;
+        this.currentMemberIndex = 0;
+    }
+
+    public String getServiceName() {
+        return serviceName;
+    }
+
+    public String getClusterId() {
+        return clusterId;
+    }
+
+    public int getCurrentMemberIndex() {
+        return currentMemberIndex;
+    }
+
+    public void setCurrentMemberIndex(int currentMemberIndex) {
+        this.currentMemberIndex = currentMemberIndex;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithm.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithm.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithm.java
new file mode 100755
index 0000000..55412cf
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithm.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.algorithm;
+
+import org.apache.stratos.messaging.domain.topology.Member;
+
+import java.util.List;
+
+/**
+ * Defines the specification for implementing load balancing algorithms.
+ */
+public interface LoadBalanceAlgorithm {
+    /**
+     * Return algorithm name.
+     *
+     * @return
+     */
+    public String getName();
+
+    /**
+     * Apply the algorithm and return the next member.
+     *
+     * @param algorithmContext
+     * @return
+     */
+    public Member getNextMember(AlgorithmContext algorithmContext);
+
+    /**
+     * Set member list of a given cluster.
+     *
+     * @param members
+     */
+    public void setMembers(List<Member> members);
+
+    /**
+     * Reset the algorithm and start from the beginning.
+     *
+     * @param algorithmContext
+     */
+    public void reset(AlgorithmContext algorithmContext);
+
+    /**
+     * Clone algorithm object.
+     *
+     * @return
+     */
+    public LoadBalanceAlgorithm clone();
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithmFactory.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithmFactory.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithmFactory.java
new file mode 100644
index 0000000..699741e
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/LoadBalanceAlgorithmFactory.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.algorithm;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Load balance algorithm factory to create the algorithm
+ */
+public class LoadBalanceAlgorithmFactory {
+    private static final Log log = LogFactory.getLog(LoadBalanceAlgorithmFactory.class);
+
+
+    public static LoadBalanceAlgorithm createAlgorithm(String className) {
+        try {
+            Class algorithmClass = Class.forName(className);
+            try {
+                Object instance = algorithmClass.getConstructor().newInstance();
+                if (instance instanceof LoadBalanceAlgorithm) {
+                    return (LoadBalanceAlgorithm) instance;
+                } else {
+                    throw new RuntimeException(String.format("Class %s is not a valid load balance algorithm implementation"));
+                }
+            } catch (NoSuchMethodException e) {
+                if (log.isErrorEnabled()) {
+                    log.error(e);
+                }
+            } catch (InstantiationException e) {
+                if (log.isErrorEnabled()) {
+                    log.error(e);
+                }
+            } catch (IllegalAccessException e) {
+                if (log.isErrorEnabled()) {
+                    log.error(e);
+                }
+            } catch (InvocationTargetException e) {
+                if (log.isErrorEnabled()) {
+                    log.error(e);
+                }
+            }
+
+        } catch (ClassNotFoundException e) {
+            if (log.isErrorEnabled()) {
+                log.error(e);
+            }
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/RoundRobin.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/RoundRobin.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/RoundRobin.java
new file mode 100644
index 0000000..e3c2898
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/algorithm/RoundRobin.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.algorithm;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.domain.topology.Member;
+
+import java.util.List;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * This is the implementation of the round robin load balancing algorithm. It simply iterates
+ * through the endpoint list one by one for until an active endpoint is found.
+ */
+public class RoundRobin implements LoadBalanceAlgorithm {
+    private static final Log log = LogFactory.getLog(RoundRobin.class);
+
+    private List<Member> members;
+    private final Lock lock = new ReentrantLock();
+
+    @Override
+    public String getName() {
+        return "Round Robin";
+    }
+
+    @Override
+    public Member getNextMember(AlgorithmContext algorithmContext) {
+        if (members.size() == 0) {
+            return null;
+        }
+        Member current = null;
+        lock.lock();
+        try {
+            int currentMemberIndex = algorithmContext.getCurrentMemberIndex();
+            if (currentMemberIndex >= members.size()) {
+                currentMemberIndex = 0;
+            }
+            int index = members.size();
+            do {                                                                   current = members.get(currentMemberIndex);
+                if (currentMemberIndex == members.size() - 1) {
+                    currentMemberIndex = 0;
+                } else {
+                    currentMemberIndex++;
+                }
+                index--;
+            } while ((!current.isActive()) && index > 0);
+            algorithmContext.setCurrentMemberIndex(currentMemberIndex);
+            if (log.isDebugEnabled()) {
+                log.debug(String.format("Service name: %s cluster id: %s members: %d", algorithmContext.getServiceName(), algorithmContext.getClusterId(), members.size()));
+                log.debug(String.format("Current member: %s", current.getMemberId()));
+            }
+
+        } finally {
+            lock.unlock();
+        }
+        return current;
+    }
+
+    @Override
+    public void setMembers(List<Member> members) {
+        this.members = members;
+    }
+
+    @Override
+    public void reset(AlgorithmContext algorithmContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Resetting the Round Robin load balancing algorithm ...");
+        }
+        synchronized (algorithmContext) {
+            algorithmContext.setCurrentMemberIndex(0);
+        }
+    }
+
+    @Override
+    public LoadBalanceAlgorithm clone() {
+        return new RoundRobin();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/endpoint/TenantAwareLoadBalanceEndpoint.java
new file mode 100644
index 0000000..a132b30
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/endpoint/TenantAwareLoadBalanceEndpoint.java
@@ -0,0 +1,517 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.endpoint;
+
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.description.TransportInDescription;
+import org.apache.http.protocol.HTTP;
+import org.apache.stratos.load.balancer.RequestDelegator;
+import org.apache.stratos.load.balancer.algorithm.LoadBalanceAlgorithmFactory;
+import org.apache.stratos.load.balancer.stat.LoadBalancingStatsCollector;
+import org.apache.stratos.load.balancer.util.Constants;
+import org.apache.stratos.messaging.domain.topology.Member;
+import org.apache.stratos.messaging.domain.topology.Port;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.endpoints.AddressEndpoint;
+import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
+import org.apache.synapse.endpoints.Endpoint;
+import org.apache.synapse.endpoints.EndpointDefinition;
+import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
+import org.apache.synapse.endpoints.dispatch.SessionInformation;
+import org.apache.synapse.transport.nhttp.NhttpConstants;
+
+import java.io.Serializable;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.*;
+
+
+public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.LoadbalanceEndpoint implements Serializable {
+    private static final String PORT_MAPPING_PREFIX = "port.mapping.";
+
+    /* Request delegator identifies the next member */
+    private RequestDelegator requestDelegator;
+
+    /* Load balance algorithm class name */
+    private String algorithmClassName;
+
+    /* Flag to enable session affinity based load balancing */
+    private boolean sessionAffinity;
+
+    /* Dispatcher used for session affinity */
+    private HttpSessionDispatcher dispatcher;
+
+    /* Sessions time out interval */
+    private long sessionTimeout = -1;
+
+    @Override
+    public void init(SynapseEnvironment synapseEnvironment) {
+        super.init(synapseEnvironment);
+
+        requestDelegator = new RequestDelegator(LoadBalanceAlgorithmFactory.createAlgorithm(algorithmClassName));
+        synapseEnvironment.getSynapseConfiguration().setProperty(SynapseConstants.PROP_SAL_ENDPOINT_DEFAULT_SESSION_TIMEOUT, String.valueOf(sessionTimeout));
+        setDispatcher(new HttpSessionDispatcher());
+    }
+
+    @Override
+    public void send(MessageContext synCtx) {
+
+        SessionInformation sessionInformation = null;
+        org.apache.axis2.clustering.Member currentMember = null;
+        if (isSessionAffinityBasedLB()) {
+            // Check existing session information
+            sessionInformation = (SessionInformation) synCtx.getProperty(
+                    SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
+
+            currentMember = (org.apache.axis2.clustering.Member) synCtx.getProperty(
+                    SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER);
+
+            if (sessionInformation == null && currentMember == null) {
+                sessionInformation = dispatcher.getSession(synCtx);
+                if (sessionInformation != null) {
+                    if (log.isDebugEnabled()) {
+                        log.debug(String.format("Existing session found: %s", sessionInformation.getId()));
+                    }
+
+                    currentMember = sessionInformation.getMember();
+                    synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
+                    // This is for reliably recovery any session information if while response is getting ,
+                    // session information has been removed by cleaner.
+                    // This will not be a cost as session information is not a heavy data structure
+                    synCtx.setProperty(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
+                }
+            }
+
+        }
+
+        TenantAwareLoadBalanceFaultHandler faultHandler = new TenantAwareLoadBalanceFaultHandler();
+        if (sessionInformation != null && currentMember != null) {
+            // Send request to the member with the existing session
+            sessionInformation.updateExpiryTime();
+            sendToApplicationMember(synCtx, currentMember, faultHandler, false);
+        } else {
+            // No existing session found
+            // Find next member
+            org.apache.axis2.clustering.Member axis2Member = findNextMember(synCtx);
+            if (axis2Member != null) {
+                // Send request to member
+                sendToApplicationMember(synCtx, axis2Member, faultHandler, true);
+            } else {
+                throwSynapseException(synCtx, 404, "Active application instances not found");
+            }
+        }
+    }
+
+    private void throwSynapseException(MessageContext synCtx, int errorCode, String errorMessage) {
+        synCtx.setProperty(SynapseConstants.ERROR_CODE, errorCode);
+        synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMessage);
+        throw new SynapseException(errorMessage);
+    }
+
+    /**
+     * Setup load balancer message context properties to be used by the out block of the main sequence.
+     * These values will be used to update the Location value in the response header.
+     *
+     * @param synCtx
+     */
+    private void setupLoadBalancerContextProperties(MessageContext synCtx) {
+        String lbHostName = extractTargetHost(synCtx);
+        org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        TransportInDescription httpTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn("http");
+        TransportInDescription httpsTransportIn = axis2MsgCtx.getConfigurationContext().getAxisConfiguration().getTransportIn("https");
+        String lbHttpPort = (String) httpTransportIn.getParameter("port").getValue();
+        String lbHttpsPort = (String) httpsTransportIn.getParameter("port").getValue();
+
+        synCtx.setProperty(Constants.LB_HOST_NAME, lbHostName);
+        synCtx.setProperty(Constants.LB_HTTP_PORT, lbHttpPort);
+        synCtx.setProperty(Constants.LB_HTTPS_PORT, lbHttpsPort);
+    }
+
+
+    /**
+     * Adding the X-Forwarded-For/X-Originating-IP headers to the outgoing message.
+     *
+     * @param synCtx Current message context
+     */
+    protected void setupTransportHeaders(MessageContext synCtx) {
+        Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
+        org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
+        Object headers = axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        if (headers != null && headers instanceof Map) {
+            Map headersMap = (Map) headers;
+            String xForwardFor = (String) headersMap.get(NhttpConstants.HEADER_X_FORWARDED_FOR);
+            String remoteHost = (String) axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
+
+            if (xForwardFor != null && !"".equals(xForwardFor)) {
+                StringBuilder xForwardedForString = new StringBuilder();
+                xForwardedForString.append(xForwardFor);
+                if (remoteHost != null && !"".equals(remoteHost)) {
+                    xForwardedForString.append(",").append(remoteHost);
+                }
+                headersMap.put(NhttpConstants.HEADER_X_FORWARDED_FOR, xForwardedForString.toString());
+            } else {
+                headersMap.put(NhttpConstants.HEADER_X_FORWARDED_FOR, remoteHost);
+            }
+
+            //Extracting information of X-Originating-IP
+            if (headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1) != null) {
+                headersMap.put(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1, headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_1));
+            } else if (headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2) != null) {
+                headersMap.put(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2, headersMap.get(NhttpConstants.HEADER_X_ORIGINATING_IP_FORM_2));
+            }
+
+        }
+    }
+
+    private org.apache.axis2.clustering.Member findNextMember(MessageContext synCtx) {
+        String targetHost = extractTargetHost(synCtx);
+        if(!requestDelegator.isTargetHostValid(targetHost)) {
+            throwSynapseException(synCtx, 404, String.format("Unknown host name %s", targetHost));
+        }
+        Member member = requestDelegator.findNextMember(targetHost);
+        if (member == null)
+            return null;
+
+        // Create Axi2 member object
+        String transport = extractTransport(synCtx);
+        Port transportPort = member.getPort(transport);
+        if (transportPort == null) {
+            if(log.isErrorEnabled()) {
+                log.error(String.format("Port not found for transport %s in member %s", transport, member.getMemberId()));
+            }
+            throwSynapseException(synCtx, 500, "Internal server error");
+        }
+
+        int memberPort = transportPort.getValue();
+        org.apache.axis2.clustering.Member axis2Member = new org.apache.axis2.clustering.Member(member.getMemberIp(), memberPort);
+        axis2Member.setDomain(member.getClusterId());
+        Port httpPort = member.getPort("http");
+        if (httpPort != null)
+            axis2Member.setHttpPort(httpPort.getValue());
+        Port httpsPort = member.getPort("https");
+        if (httpsPort != null)
+            axis2Member.setHttpsPort(httpsPort.getValue());
+        axis2Member.setActive(member.isActive());
+        return axis2Member;
+    }
+
+    private String extractTargetHost(MessageContext synCtx) {
+        org.apache.axis2.context.MessageContext msgCtx =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+
+        Map headerMap = (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String hostName = null;
+        if (headerMap != null) {
+            Object hostObj = headerMap.get(HTTP.TARGET_HOST);
+            hostName = (String) hostObj;
+            if (hostName.contains(":")) {
+                hostName = hostName.substring(0, hostName.indexOf(":"));
+            }
+        }
+        return hostName;
+    }
+
+    private int extractPort(MessageContext synCtx, String transport) {
+        org.apache.axis2.context.MessageContext msgCtx =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+
+        Map headerMap = (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        int port = -1;
+        if (headerMap != null) {
+            String hostHeader = (String) headerMap.get(HTTP.TARGET_HOST);
+            int index = hostHeader.indexOf(':');
+            if (index != -1) {
+                port = Integer.parseInt(hostHeader.trim().substring(index + 1));
+            } else {
+                if ("http".equals(transport)) {
+                    port = 80;
+                } else if ("https".equals(transport)) {
+                    port = 443;
+                }
+            }
+        }
+        return port;
+    }
+
+    private String extractTransport(MessageContext synCtx) {
+        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        return axis2MessageContext.getTransportIn().getName();
+    }
+
+    /**
+     * @param to     get an endpoint to send the information
+     * @param member The member to which an EP has to be created
+     * @param synCtx synapse context
+     * @return the created endpoint
+     */
+    private Endpoint getEndpoint(EndpointReference to, org.apache.axis2.clustering.Member member, MessageContext synCtx) {
+        AddressEndpoint endpoint = new AddressEndpoint();
+        endpoint.setEnableMBeanStats(false);
+        endpoint.setName("DLB:" + member.getHostName() +
+                ":" + member.getPort() + ":" + UUID.randomUUID());
+        EndpointDefinition definition = new EndpointDefinition();
+        definition.setSuspendMaximumDuration(10000);
+        definition.setReplicationDisabled(true);
+        definition.setAddress(to.getAddress());
+        endpoint.setDefinition(definition);
+        endpoint.init((SynapseEnvironment)
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext().
+                        getConfigurationContext().getAxisConfiguration().
+                        getParameterValue(SynapseConstants.SYNAPSE_ENV));
+        return endpoint;
+    }
+
+    private EndpointReference getEndpointReferenceAfterURLRewrite(org.apache.axis2.clustering.Member currentMember,
+                                                                  String transport,
+                                                                  String address,
+                                                                  int incomingPort) {
+
+        if (transport.startsWith("https")) {
+            transport = "https";
+        } else if (transport.startsWith("http")) {
+            transport = "http";
+        } else {
+            String msg = "Cannot load balance for non-HTTP/S transport " + transport;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+        // URL Rewrite
+        if (transport.startsWith("http") || transport.startsWith("https")) {
+            if (address.startsWith("http://") || address.startsWith("https://")) {
+                try {
+                    String _address = address.indexOf("?") > 0 ? address.substring(address.indexOf("?"), address.length()) : "";
+                    address = new URL(address).getPath() + _address;
+                } catch (MalformedURLException e) {
+                    String msg = "URL " + address + " is malformed";
+                    log.error(msg, e);
+                    throw new SynapseException(msg, e);
+                }
+            }
+
+            int port;
+            Properties memberProperties = currentMember.getProperties();
+            String mappedPort = memberProperties.getProperty(PORT_MAPPING_PREFIX + incomingPort);
+            if (mappedPort != null) {
+                port = Integer.parseInt(mappedPort);
+            } else if (transport.startsWith("https")) {
+                port = currentMember.getHttpsPort();
+            } else {
+                port = currentMember.getHttpPort();
+            }
+
+            String remoteHost = memberProperties.getProperty("remoteHost");
+            String hostName = (remoteHost == null) ? currentMember.getHostName() : remoteHost;
+            return new EndpointReference(transport + "://" + hostName +
+                    ":" + port + address);
+        } else {
+            String msg = "Cannot load balance for non-HTTP/S transport " + transport;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+    }
+
+    /*
+     * Preparing the endpoint sequence for a new session establishment request
+     */
+    private void prepareEndPointSequence(MessageContext synCtx, Endpoint endpoint) {
+
+        Object o = synCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST);
+        List<Endpoint> endpointList;
+        if (o instanceof List) {
+            endpointList = (List<Endpoint>) o;
+            endpointList.add(this);
+
+        } else {
+            // this is the first endpoint in the hierarchy. so create the queue and
+            // insert this as the first element.
+            endpointList = new ArrayList<Endpoint>();
+            endpointList.add(this);
+            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_ENDPOINT_LIST, endpointList);
+        }
+
+        // if the next endpoint is not a session affinity one, endpoint sequence ends
+        // here. but we have to add the next endpoint to the list.
+        if (!(endpoint instanceof TenantAwareLoadBalanceEndpoint)) {
+            endpointList.add(endpoint);
+            // Clearing out if there any any session information with current message
+            if (dispatcher.isServerInitiatedSession()) {
+                dispatcher.removeSessionID(synCtx);
+            }
+        }
+    }
+
+    protected void sendToApplicationMember(MessageContext synCtx,
+                                           org.apache.axis2.clustering.Member currentMember,
+                                           DynamicLoadbalanceFaultHandler faultHandler,
+                                           boolean newSession) {
+        //Rewriting the URL
+        org.apache.axis2.context.MessageContext axis2MsgCtx =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+
+        //Removing the REST_URL_POSTFIX - this is a hack.
+        //In this load balance endpoint we create an endpoint per request by setting the complete url as the address.
+        //If a REST message comes Axis2FlexibleMEPClient append the REST_URL_POSTFIX to the address. Hence endpoint fails
+        //do send the request. e.g.  http://localhost:8080/example/index.html/example/index.html
+        axis2MsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
+
+        String transport = axis2MsgCtx.getTransportIn().getName();
+        String address = synCtx.getTo().getAddress();
+        int incomingPort = extractPort(synCtx, transport);
+        EndpointReference to = getEndpointReferenceAfterURLRewrite(currentMember, transport, address, incomingPort);
+        synCtx.setTo(to);
+
+        faultHandler.setTo(to);
+        faultHandler.setCurrentMember(currentMember);
+        synCtx.pushFaultHandler(faultHandler);
+        if (isFailover()) {
+            synCtx.getEnvelope().build();
+        }
+
+        Endpoint endpoint = getEndpoint(to, currentMember, synCtx);
+        faultHandler.setCurrentEp(endpoint);
+        if (isSessionAffinityBasedLB() && newSession) {
+            prepareEndPointSequence(synCtx, endpoint);
+            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_MEMBER, currentMember);
+            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER, dispatcher);
+            // we should also indicate that this is the first message in the session. so that
+            // onFault(...) method can resend only the failed attempts for the first message.
+            synCtx.setProperty(SynapseConstants.PROP_SAL_ENDPOINT_FIRST_MESSAGE_IN_SESSION,
+                    Boolean.TRUE);
+        }
+
+        Map<String, String> memberHosts;
+        if ((memberHosts = (Map<String, String>) currentMember.getProperties().get(HttpSessionDispatcher.HOSTS)) == null) {
+            currentMember.getProperties().put(HttpSessionDispatcher.HOSTS,
+                    memberHosts = new HashMap<String, String>());
+        }
+        memberHosts.put(extractTargetHost(synCtx), "true");
+        setupTransportHeaders(synCtx);
+        setupLoadBalancerContextProperties(synCtx);
+
+        // Update health stats
+        LoadBalancingStatsCollector.getInstance().incrementRequestInflightCount(currentMember.getDomain());
+        // Set the cluster id in the message context
+        synCtx.setProperty(Constants.CLUSTER_ID, currentMember.getDomain());
+
+        try {
+            if (log.isDebugEnabled()) {
+                log.debug(String.format("Sending request to endpoint: %s", to.getAddress()));
+            }
+            endpoint.send(synCtx);
+        } catch (Exception e) {
+            if (e.getMessage().toLowerCase().contains("io reactor shutdown")) {
+                log.fatal("System cannot continue normal operation. Restarting", e);
+                System.exit(121); // restart
+            } else {
+                throw new SynapseException(e);
+            }
+        }
+    }
+
+    public void setDispatcher(HttpSessionDispatcher dispatcher) {
+        this.dispatcher = dispatcher;
+    }
+
+    public HttpSessionDispatcher getDispatcher() {
+        return dispatcher;
+    }
+
+    public String getAlgorithmClassName() {
+        return algorithmClassName;
+    }
+
+    public void setAlgorithmClassName(String algorithmClassName) {
+        this.algorithmClassName = algorithmClassName;
+    }
+
+    public long getSessionTimeout() {
+        return sessionTimeout;
+    }
+
+    public void setSessionTimeout(long sessionTimeout) {
+        this.sessionTimeout = sessionTimeout;
+    }
+
+    public boolean isSessionAffinityBasedLB() {
+        return sessionAffinity;
+    }
+
+    public void setSessionAffinity(boolean sessionAffinity) {
+        this.sessionAffinity = sessionAffinity;
+    }
+
+    private class TenantAwareLoadBalanceFaultHandler extends DynamicLoadbalanceFaultHandler {
+        private org.apache.axis2.clustering.Member currentMember;
+        private Endpoint currentEp;
+        private EndpointReference to;
+
+        @Override
+        public void setCurrentMember(org.apache.axis2.clustering.Member currentMember) {
+            this.currentMember = currentMember;
+        }
+
+        @Override
+        public void setCurrentEp(Endpoint currentEp) {
+            this.currentEp = currentEp;
+        }
+
+        @Override
+        public void setTo(EndpointReference to) {
+            this.to = to;
+        }
+
+        @Override
+        public void onFault(MessageContext synCtx) {
+            //cleanup endpoint if exists
+            if (currentEp != null) {
+                currentEp.destroy();
+            }
+            if (currentMember == null) {
+                return;
+            }
+
+            Stack faultStack = synCtx.getFaultStack();
+            if (faultStack != null && !faultStack.isEmpty()) {
+                faultStack.pop();  // Remove the LoadbalanceFaultHandler
+            }
+
+            currentMember = findNextMember(synCtx);
+            if (currentMember == null) {
+                String msg = String.format("No application members available to serve the request %s", synCtx.getTo().getAddress());
+                log.error(msg);
+                throw new SynapseException(msg);
+            }
+            synCtx.setTo(to);
+            if (isSessionAffinityBasedLB()) {
+                //We are sending the this message on a new session,
+                // hence we need to remove previous session information
+                Set pros = synCtx.getPropertyKeySet();
+                if (pros != null) {
+                    pros.remove(SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
+                }
+            }
+            sendToApplicationMember(synCtx, currentMember, this, true);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalanceEndpointServiceComponent.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalanceEndpointServiceComponent.java
new file mode 100644
index 0000000..b317d78
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/internal/LoadBalanceEndpointServiceComponent.java
@@ -0,0 +1,333 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.stratos.load.balancer.internal;
+
+import org.apache.axis2.deployment.DeploymentEngine;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.stratos.load.balancer.LoadBalancerContext;
+import org.apache.stratos.load.balancer.TenantAwareLoadBalanceEndpointException;
+import org.apache.stratos.messaging.message.receiver.topology.TopologyEventMessageDelegator;
+import org.apache.stratos.messaging.message.receiver.topology.TopologyEventMessageReceiver;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.stratos.messaging.broker.subscribe.TopicSubscriber;
+import org.apache.stratos.messaging.util.Constants;
+import org.apache.synapse.config.SynapseConfiguration;
+import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.deployers.SynapseArtifactDeploymentStore;
+import org.apache.synapse.endpoints.Endpoint;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
+import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
+import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
+import org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService;
+import org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService;
+import org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.apache.stratos.load.balancer.EndpointDeployer;
+
+import java.io.File;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @scr.component name="org.apache.stratos.lbr.endpoint" immediate="true"
+ * @scr.reference name="configuration.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ * @scr.reference name="synapse.config.service" interface=
+ * "org.wso2.carbon.mediation.initializer.services.SynapseConfigurationService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setSynapseConfigurationService"
+ * unbind="unsetSynapseConfigurationService"
+ * @scr.reference name="synapse.env.service" interface=
+ * "org.wso2.carbon.mediation.initializer.services.SynapseEnvironmentService"
+ * cardinality="1..n" policy="dynamic"
+ * bind="setSynapseEnvironmentService"
+ * unbind="unsetSynapseEnvironmentService"
+ * @scr.reference name="registry.service"
+ * interface="org.wso2.carbon.registry.core.service.RegistryService"
+ * cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ * unbind="unsetRegistryService"
+ * @scr.reference name="dependency.mgt.service" interface=
+ * "org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService"
+ * cardinality="0..1" policy="dynamic"
+ * bind="setDependencyManager" unbind="unsetDependencyManager"
+ * @scr.reference name="synapse.registrations.service" interface=
+ * "org.wso2.carbon.mediation.initializer.services.SynapseRegistrationsService"
+ * cardinality="1..n" policy="dynamic"
+ * bind="setSynapseRegistrationsService"
+ * unbind="unsetSynapseRegistrationsService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ */
+@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
+public class LoadBalanceEndpointServiceComponent {
+    private static final Log log = LogFactory.getLog(LoadBalanceEndpointServiceComponent.class);
+
+    private boolean activated = false;
+
+    protected void activate(ComponentContext ctxt) {
+        try {
+            // Register endpoint deployer
+            SynapseEnvironmentService synEnvService = LoadBalancerContext.getInstance().getSynapseEnvironmentService(
+                    MultitenantConstants.SUPER_TENANT_ID);
+            registerDeployer(LoadBalancerContext.getInstance().getAxisConfiguration(),
+                    synEnvService.getSynapseEnvironment());
+
+            // Start topic subscriber thread
+            TopicSubscriber topicSubscriber = new TopicSubscriber(Constants.TOPOLOGY_TOPIC);
+            topicSubscriber.setMessageListener(new TopologyEventMessageReceiver());
+            Thread subscriberThread = new Thread(topicSubscriber);
+            subscriberThread.start();
+            if (log.isDebugEnabled()) {
+                log.debug("Topology event message receiver thread started");
+            }
+
+            // Start topology message receiver thread
+            Thread receiverThread = new Thread(new TopologyEventMessageDelegator());
+            receiverThread.start();
+            if (log.isDebugEnabled()) {
+                log.debug("Topology message processor thread started");
+            }
+
+            activated = true;
+            if (log.isDebugEnabled()) {
+                log.debug("LoadBalanceEndpointServiceComponent is activated ");
+            }
+        } catch (Throwable e) {
+            log.error("Failed to activate LoadBalanceEndpointServiceComponent", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        try {
+            Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet = LoadBalancerContext
+                    .getInstance().getSynapseEnvironmentServices().entrySet();
+            for (Map.Entry<Integer, SynapseEnvironmentService> entry : entrySet) {
+                unregisterDeployer(entry.getValue().getConfigurationContext()
+                        .getAxisConfiguration(), entry.getValue()
+                        .getSynapseEnvironment());
+            }
+        } catch (Exception e) {
+            log.warn("Couldn't remove the EndpointDeployer");
+        }
+    }
+
+    /**
+     * Un-registers the Endpoint deployer.
+     *
+     * @param axisConfig         AxisConfiguration to which this deployer belongs
+     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
+     */
+    private void unregisterDeployer(AxisConfiguration axisConfig,
+                                    SynapseEnvironment synapseEnvironment)
+            throws TenantAwareLoadBalanceEndpointException {
+        if (axisConfig != null) {
+            DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
+                    .getConfigurator();
+            String synapseConfigPath = ServiceBusUtils
+                    .getSynapseConfigAbsPath(synapseEnvironment
+                            .getServerContextInformation());
+            String endpointDirPath = synapseConfigPath + File.separator
+                    + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
+            deploymentEngine.removeDeployer(endpointDirPath,
+                    ServiceBusConstants.ARTIFACT_EXTENSION);
+        }
+    }
+
+    /**
+     * Registers the Endpoint deployer.
+     *
+     * @param axisConfig         AxisConfiguration to which this deployer belongs
+     * @param synapseEnvironment SynapseEnvironment to which this deployer belongs
+     */
+    private void registerDeployer(AxisConfiguration axisConfig,
+                                  SynapseEnvironment synapseEnvironment)
+            throws TenantAwareLoadBalanceEndpointException {
+        SynapseConfiguration synCfg = synapseEnvironment
+                .getSynapseConfiguration();
+        DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig
+                .getConfigurator();
+        SynapseArtifactDeploymentStore deploymentStore = synCfg
+                .getArtifactDeploymentStore();
+
+        String synapseConfigPath = ServiceBusUtils
+                .getSynapseConfigAbsPath(synapseEnvironment
+                        .getServerContextInformation());
+        String endpointDirPath = synapseConfigPath + File.separator
+                + MultiXMLConfigurationBuilder.ENDPOINTS_DIR;
+
+        for (Endpoint ep : synCfg.getDefinedEndpoints().values()) {
+            if (ep.getFileName() != null) {
+                deploymentStore.addRestoredArtifact(endpointDirPath
+                        + File.separator + ep.getFileName());
+            }
+        }
+        deploymentEngine.addDeployer(new EndpointDeployer(), endpointDirPath,
+                ServiceBusConstants.ARTIFACT_EXTENSION);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        LoadBalancerContext.getInstance().setAxisConfiguration(cfgCtxService.getServerConfigContext().getAxisConfiguration());
+        LoadBalancerContext.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        LoadBalancerContext.getInstance().setAxisConfiguration(null);
+        LoadBalancerContext.getInstance().setConfigCtxt(null);
+    }
+
+    protected void setSynapseConfigurationService(SynapseConfigurationService synapseConfigurationService) {
+        LoadBalancerContext.getInstance().setSynapseConfiguration(synapseConfigurationService.getSynapseConfiguration());
+    }
+
+    protected void unsetSynapseConfigurationService(SynapseConfigurationService synapseConfigurationService) {
+        LoadBalancerContext.getInstance().setSynapseConfiguration(null);
+    }
+
+    /**
+     * Here we receive an event about the creation of a SynapseEnvironment. If
+     * this is SuperTenant we have to wait until all the other constraints are
+     * met and actual initialization is done in the activate method. Otherwise
+     * we have to do the activation here.
+     *
+     * @param synapseEnvironmentService SynapseEnvironmentService which contains information about the
+     *                                  new Synapse Instance
+     */
+    protected void setSynapseEnvironmentService(SynapseEnvironmentService synapseEnvironmentService) {
+        boolean alreadyCreated = LoadBalancerContext.getInstance()
+                .getSynapseEnvironmentServices()
+                .containsKey(synapseEnvironmentService.getTenantId());
+
+        LoadBalancerContext.getInstance().addSynapseEnvironmentService(
+                synapseEnvironmentService.getTenantId(),
+                synapseEnvironmentService);
+        if (activated) {
+            if (!alreadyCreated) {
+                try {
+                    registerDeployer(synapseEnvironmentService
+                            .getConfigurationContext().getAxisConfiguration(),
+                            synapseEnvironmentService.getSynapseEnvironment());
+                    if (log.isDebugEnabled()) {
+                        log.debug("Endpoint Admin bundle is activated ");
+                    }
+                } catch (Throwable e) {
+                    log.error("Failed to activate Endpoint Admin bundle ", e);
+                }
+            }
+        }
+    }
+
+    /**
+     * Here we receive an event about Destroying a SynapseEnvironment. This can
+     * be the super tenant destruction or a tenant destruction.
+     *
+     * @param synapseEnvironmentService synapseEnvironment
+     */
+    protected void unsetSynapseEnvironmentService(
+            SynapseEnvironmentService synapseEnvironmentService) {
+        LoadBalancerContext.getInstance().removeSynapseEnvironmentService(
+                synapseEnvironmentService.getTenantId());
+    }
+
+    protected void setRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService bound to the endpoint component");
+        }
+        try {
+            LoadBalancerContext.getInstance().setConfigRegistry(
+                    regService.getConfigSystemRegistry());
+            LoadBalancerContext.getInstance().setGovernanceRegistry(
+                    regService.getGovernanceSystemRegistry());
+        } catch (RegistryException e) {
+            log.error("Couldn't retrieve the registry from the registry service");
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService unbound from the endpoint component");
+        }
+        LoadBalancerContext.getInstance().setConfigRegistry(null);
+    }
+
+    protected void setDependencyManager(
+            DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service bound to the endpoint component");
+        }
+        LoadBalancerContext.getInstance().setDependencyManager(dependencyMgr);
+    }
+
+    protected void unsetDependencyManager(
+            DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service unbound from the endpoint component");
+        }
+        LoadBalancerContext.getInstance().setDependencyManager(null);
+    }
+
+    protected void setSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+
+    }
+
+    protected void unsetSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+        int tenantId = synapseRegistrationsService.getTenantId();
+        if (LoadBalancerContext.getInstance().getSynapseEnvironmentServices()
+                .containsKey(tenantId)) {
+            SynapseEnvironment env = LoadBalancerContext.getInstance()
+                    .getSynapseEnvironmentService(tenantId)
+                    .getSynapseEnvironment();
+
+            LoadBalancerContext.getInstance().removeSynapseEnvironmentService(
+                    synapseRegistrationsService.getTenantId());
+
+            AxisConfiguration axisConfig = synapseRegistrationsService
+                    .getConfigurationContext().getAxisConfiguration();
+            if (axisConfig != null) {
+                try {
+                    unregisterDeployer(axisConfig, env);
+                } catch (Exception e) {
+                    log.warn("Couldn't remove the EndpointDeployer");
+                }
+            }
+        }
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        LoadBalancerContext.getInstance().setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        LoadBalancerContext.getInstance().setRealmService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/mediators/ResponseInterceptor.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/mediators/ResponseInterceptor.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/mediators/ResponseInterceptor.java
new file mode 100644
index 0000000..fc6d84c
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/mediators/ResponseInterceptor.java
@@ -0,0 +1,58 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+
+ *  http://www.apache.org/licenses/LICENSE-2.0
+
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package org.apache.stratos.load.balancer.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.stratos.load.balancer.stat.LoadBalancingStatsCollector;
+import org.apache.stratos.load.balancer.util.Constants;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.mediators.AbstractMediator;
+
+/**
+ * This Synapse mediator counts the responses that are going across LB.
+ * 
+ */
+public class ResponseInterceptor extends AbstractMediator implements ManagedLifecycle {
+
+    public boolean mediate(MessageContext synCtx) {
+        if(log.isDebugEnabled()) {
+            log.debug("Mediation started " + ResponseInterceptor.class.getName());
+        }
+        String clusterId = (String) synCtx.getProperty(Constants.CLUSTER_ID);
+        LoadBalancingStatsCollector.getInstance().decrementRequestInflightCount(clusterId);
+        return true;
+    }
+
+    @Override
+    public void destroy() {
+        if(log.isDebugEnabled()) {
+            log.debug("ResponseInterceptor mediator destroyed");
+        }
+    }
+
+    @Override
+    public void init(SynapseEnvironment arg0) {
+        if(log.isDebugEnabled()) {
+            log.debug("ResponseInterceptor mediator initiated");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/LoadBalancingStatsCollector.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/LoadBalancingStatsCollector.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/LoadBalancingStatsCollector.java
new file mode 100644
index 0000000..a0adc93
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/LoadBalancingStatsCollector.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.load.balancer.stat;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Observable;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.stratos.load.balancer.stat.observers.WSO2CEPStatsObserver;
+
+/**
+ * This is the load balancing stats collector and any observer can get registered here 
+ * and receive notifications periodically.
+ * This is a Singleton object.
+ * @author nirmal
+ *
+ */
+public class LoadBalancingStatsCollector extends Observable{
+
+	private static LoadBalancingStatsCollector collector;
+	private Map<String, Integer> clusterIdToRequestInflightCountMap;
+	private Thread notifier;
+	
+	private LoadBalancingStatsCollector() {
+		clusterIdToRequestInflightCountMap = new ConcurrentHashMap<String, Integer>();
+		if (notifier == null || (notifier != null && !notifier.isAlive())) {
+			notifier = new Thread(new ObserverNotifier());
+			notifier.start();
+		}
+    }
+	
+	public static LoadBalancingStatsCollector getInstance() {
+		if (collector == null) {
+			synchronized (LoadBalancingStatsCollector.class) {
+				if (collector == null) {
+					collector = new LoadBalancingStatsCollector();
+					// add observers
+					collector.addObserver(new WSO2CEPStatsObserver());
+				}
+			}
+		}
+		return collector;
+	}
+	
+	public void incrementRequestInflightCount(String clusterId) {
+		if(clusterId == null) {
+			return;
+		}
+		
+		int value = 1;
+		if(clusterIdToRequestInflightCountMap.get(clusterId) != null) {
+			value += clusterIdToRequestInflightCountMap.get(clusterId);
+		}
+		clusterIdToRequestInflightCountMap.put(clusterId, value);
+		setChanged();
+	}
+	
+	public void decrementRequestInflightCount(String clusterId) {
+		if(clusterId == null) {
+			return;
+		}
+		
+		int value = -1;
+		if(clusterIdToRequestInflightCountMap.get(clusterId) != null) {
+			value += clusterIdToRequestInflightCountMap.get(clusterId);
+		}
+		clusterIdToRequestInflightCountMap.put(clusterId, value);
+		setChanged();
+	}
+	
+	
+	/**
+	 * This thread will notify all the observers of this subject.
+	 * @author nirmal
+	 *
+	 */
+	private class ObserverNotifier implements Runnable {
+
+		@Override
+        public void run() {
+			while(true) {
+				try {
+	                Thread.sleep(15000);
+                } catch (InterruptedException ignore) {
+                }
+				LoadBalancingStatsCollector.getInstance().notifyObservers(new HashMap<String, Integer>(clusterIdToRequestInflightCountMap));
+			}
+	        
+        }
+		
+	}
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/observers/WSO2CEPStatsObserver.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/observers/WSO2CEPStatsObserver.java b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/observers/WSO2CEPStatsObserver.java
new file mode 100644
index 0000000..6093ee5
--- /dev/null
+++ b/components/org.apache.stratos.load.balancer/src/main/java/org/apache/stratos/load/balancer/stat/observers/WSO2CEPStatsObserver.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one 
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
+ * KIND, either express or implied.  See the License for the 
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.stratos.load.balancer.stat.observers;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Observable;
+import java.util.Observer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.databridge.agent.thrift.Agent;
+import org.wso2.carbon.databridge.agent.thrift.AsyncDataPublisher;
+import org.wso2.carbon.databridge.agent.thrift.conf.AgentConfiguration;
+import org.wso2.carbon.databridge.agent.thrift.exception.AgentException;
+import org.wso2.carbon.databridge.commons.Event;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class WSO2CEPStatsObserver implements Observer{
+
+	private static final Log log = LogFactory.getLog(WSO2CEPStatsObserver.class);
+	private static final String CALL_CENTER_DATA_STREAM = "stratos.lb.stats";
+	private static final String VERSION = "1.0.0";
+	private AsyncDataPublisher asyncDataPublisher;
+	
+	public WSO2CEPStatsObserver() {
+		AgentConfiguration agentConfiguration = new AgentConfiguration();
+        // TODO get following from somewhere, without hard-coding.
+        System.setProperty("javax.net.ssl.trustStore", CarbonUtils.getCarbonHome()+File.separator+"repository"+
+                           File.separator+"resources"+File.separator+"security"+File.separator+"client-truststore.jks"	);
+        System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+        
+        Agent agent = new Agent(agentConfiguration);
+        //TODO read following from a config file?
+        String ip = System.getProperty("thrift.receiver.ip");
+        String port = System.getProperty("thrift.receiver.port");
+        //Using Asynchronous data publisher
+        asyncDataPublisher = new AsyncDataPublisher("tcp://"+ip+":"+port+"", "admin", "admin", agent);
+        String streamDefinition = "{" +
+                                  " 'name':'" + CALL_CENTER_DATA_STREAM + "'," +
+                                  " 'version':'" + VERSION + "'," +
+                                  " 'nickName': 'lb stats'," +
+                                  " 'description': 'lb stats'," +
+                                  " 'metaData':[]," +
+                                  " 'payloadData':[" +
+                                  " {'name':'cluster_id','type':'STRING'}," +
+                                  " {'name':'in_flight_requests','type':'INT'}" +
+                                  " ]" +
+                                  "}";
+        asyncDataPublisher.addStreamDefinition(streamDefinition, CALL_CENTER_DATA_STREAM, VERSION);
+    }
+	
+	public void update(Observable arg0, Object arg1) {
+		if(arg1 != null && arg1 instanceof Map<?, ?>) {
+			Map<String, Integer> stats = (Map<String, Integer>)arg1;
+			publishEvents(stats);
+		}
+	}
+	
+    private void publishEvents(Map<String, Integer> stats) {
+    	
+    	for (Map.Entry<String, Integer> entry : stats.entrySet()) {
+    		
+    		Object[] payload = new Object[]{entry.getKey(), entry.getValue()};
+    		Event event = eventObject(null, null, payload, new HashMap<String, String>());
+    		try {
+    			asyncDataPublisher.publish(CALL_CENTER_DATA_STREAM, VERSION, event);
+    		} catch (AgentException e) {
+    			log.error("Failed to publish events. ", e);
+    		}
+    		
+    	}
+    	stats = null;
+    }
+    
+    private static Event eventObject(Object[] correlationData, Object[] metaData,
+                                     Object[] payLoadData, HashMap<String, String> map) {
+        Event event = new Event();
+        event.setCorrelationData(correlationData);
+        event.setMetaData(metaData);
+        event.setPayloadData(payLoadData);
+        event.setArbitraryDataMap(map);
+        return event;
+    }
+}

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/pom.xml
----------------------------------------------------------------------
diff --git a/components/pom.xml b/components/pom.xml
index 478663a..bd1ce2f 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -51,8 +51,8 @@
 		<!-- CLI -->
 		<module>org.apache.stratos.cli</module>
 		<!-- ELB -->
-        <module>org.apache.stratos.lb.common</module>
-        <module>org.apache.stratos.lb.endpoint</module>
+        <module>org.apache.stratos.load.balancer.common</module>
+        <module>org.apache.stratos.load.balancer</module>
 		<!-- Tenant Mgt -->
 		<module>org.apache.stratos.register.ui</module>
 		<module>org.apache.stratos.tenant.mgt.core</module>


[4/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

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

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

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

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

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

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

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

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

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


[6/7] Refactored org.apache.stratos.lb.endpoint to org.apache.stratos.load.balancer and org.apache.stratos.lb.common to org.apache.stratos.load.balancer.common

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

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

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/connect/TopicConnector.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/connect/TopicConnector.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/connect/TopicConnector.java
deleted file mode 100644
index 4839690..0000000
--- a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/connect/TopicConnector.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.common.mb.connect;
-
-import java.util.Properties;
-import java.io.File;
-
-import javax.jms.JMSException;
-import javax.jms.QueueSession;
-import javax.jms.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicConnectionFactory;
-import javax.jms.TopicSession;
-import javax.naming.InitialContext;
-
-import org.apache.stratos.lb.common.util.Util;
-import org.wso2.carbon.utils.CarbonUtils;
-
-/**
- * This class is responsible for loading the jndi.properties file from the classpath
- * and initialize the topic connection. Later if some other object needs a topic
- * session, this object is capable of providing one. 
- * @author nirmal
- *
- */
-public class TopicConnector {
-	
-	private TopicConnection topicConnection;
-	private String jndiPropFileDir = CarbonUtils.getCarbonConfigDirPath();
-	private String topicName;
-	private Topic topic;
-
-	public TopicConnector(String topic) {
-		jndiPropFileDir = System.getProperty("jndi.properties.dir");
-		topicName = topic;
-	}
-
-	public void init() throws Exception {
-		InitialContext ctx;
-		Properties environment = Util.getProperties(jndiPropFileDir+File.separator+"jndi.properties");
-		ctx = new InitialContext(environment);
-		// Lookup connection factory
-		TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx
-				.lookup("topicConnectionfactory");
-		topicConnection = connFactory.createTopicConnection();
-		setTopic((Topic) ctx.lookup(topicName));
-		topicConnection.start();
-
-	}
-
-	/**
-	 * Provides a new topic session.
-	 * @return topic session instance
-	 * @throws JMSException if unable to create a topic session
-	 */
-	public TopicSession newSession() throws Exception {
-		if(topicConnection == null) {
-			init();
-		}
-		return topicConnection.createTopicSession(false,
-				QueueSession.AUTO_ACKNOWLEDGE);
-	}
-	
-	public void close() throws JMSException {
-		if (topicConnection == null) {
-			return;
-		}
-		topicConnection.close();
-	}
-
-	public String getTopicName() {
-		return topicName;
-	}
-
-	public void setTopicName(String topicName) {
-		this.topicName = topicName;
-	}
-
-	public Topic getTopic() {
-		return topic;
-	}
-
-	public void setTopic(Topic topic) {
-		this.topic = topic;
-	}
-}

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/publish/TopicPublisher.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/publish/TopicPublisher.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/publish/TopicPublisher.java
deleted file mode 100644
index 8e04755..0000000
--- a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/publish/TopicPublisher.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.common.mb.publish;
-
-import javax.jms.*;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.mb.connect.TopicConnector;
-
-/**
- * Any instance who needs to publish data to a topic, should communicate with this
- * object.
- * 
- * @author nirmal
- * 
- */
-public class TopicPublisher {
-
-	private static final Log log = LogFactory.getLog(TopicPublisher.class);
-	private TopicSession topicSession;
-	private String topicName;
-	private TopicConnector connector;
-	private javax.jms.TopicPublisher topicPublisher = null;
-
-	/**
-	 * @param aTopicName
-	 *            topic name of this publisher instance.
-	 */
-	public TopicPublisher(String aTopicName) {
-		topicName = aTopicName;
-		connector = new TopicConnector(aTopicName);
-	}
-
-	/**
-	 * Publishes to a topic. If for some reason the connection to the topic got
-	 * lost, this will perform re-subscription periodically, until a connection
-	 * obtained.
-	 */
-	public void publish(String message) {
-
-		try {
-			doPublish(message);
-
-		} catch (Exception e) {
-			log.error("Error while publishing to the topic: " + topicName, e);
-		} 
-	}
-	
-	public void close() {
-		
-		// closes all sessions/connections
-		try {
-			if (topicPublisher != null) {
-				topicPublisher.close();
-			}
-			if (topicSession != null) {
-				topicSession.close();
-			}
-			if (connector != null) {
-				connector.close();
-			}
-		} catch (JMSException ignore) {
-		}
-	}
-
-	private void doPublish(String message) throws Exception, JMSException {
-		setPublisher();
-		
-		TextMessage textMessage = topicSession.createTextMessage(message);
-
-		topicPublisher.publish(textMessage);
-	}
-
-	private void setPublisher() throws Exception, JMSException {
-		if(topicSession != null && topicPublisher != null) {
-			return;
-		}
-		// initialize a TopicConnector
-		connector.init();
-		// get a session
-		topicSession = connector.newSession();
-		Topic topic = connector.getTopic();
-//		topic = topicSession.createTopic(topicName);
-		topicPublisher = topicSession.createPublisher(topic);
-	}
-	
-	public String getTopicName() {
-		return topicName;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/subscribe/TopicSubscriber.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/subscribe/TopicSubscriber.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/subscribe/TopicSubscriber.java
deleted file mode 100644
index e755e3c..0000000
--- a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/mb/subscribe/TopicSubscriber.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.common.mb.subscribe;
-
-import javax.jms.*;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.stratos.lb.common.mb.connect.TopicConnector;
-import org.apache.stratos.lb.common.mb.heartbeat.TopicHealthChecker;
-
-/**
- * Any instance who needs to subscribe to a topic, should communicate with this
- * object.
- * 
- * @author nirmal
- * 
- */
-public class TopicSubscriber implements Runnable {
-
-	private static final Log log = LogFactory.getLog(TopicSubscriber.class);
-	private MessageListener messageListener;
-	private TopicSession topicSession;
-	private String topicName;
-	TopicConnector connector;
-	javax.jms.TopicSubscriber topicSubscriber = null;
-
-	/**
-	 * @param aTopicName
-	 *            topic name of this subscriber instance.
-	 */
-	public TopicSubscriber(String aTopicName) {
-		topicName = aTopicName;
-		connector = new TopicConnector(aTopicName);
-	}
-
-	private void doSubscribe() throws Exception, JMSException {
-		// initialize a TopicConnector
-		connector.init();
-		// get a session
-		topicSession = connector.newSession();
-		Topic topic = connector.getTopic();
-		//since dynamic topic creation is not supported by most of the brokers
-//		topic = topicSession.createTopic(topicName);
-		topicSubscriber = topicSession.createSubscriber(topic);
-
-		topicSubscriber.setMessageListener(messageListener);
-	}
-
-	/**
-	 * @param aMessageListener
-	 *            this MessageListener will get triggered each time this
-	 *            subscription receives a message.
-	 */
-	public void setMessageListener(MessageListener aMessageListener) {
-
-		messageListener = aMessageListener;
-	}
-
-	/**
-	 * Subscribes to a topic. If for some reason the connection to the topic got
-	 * lost, this will perform re-subscription periodically, until a connection
-	 * obtained.
-	 */
-	@Override
-	public void run() {
-
-		while (true) {
-			try {
-				doSubscribe();
-
-			} catch (Exception e) {
-				log.error("Error while subscribing to the topic: " + topicName,
-						e);
-			} finally {
-				// start the health checker
-				Thread healthChecker = new Thread(new TopicHealthChecker(topicName));
-				healthChecker.start();
-				try {
-					// waits till the thread finishes.
-					healthChecker.join();
-				} catch (InterruptedException ignore) {
-				}
-				// health checker failed
-				// closes all sessions/connections
-				try {
-					if (topicSubscriber != null) {
-						topicSubscriber.close();
-					}
-					if (topicSession != null) {
-						topicSession.close();
-					}
-					if (connector != null) {
-						connector.close();
-					}
-				} catch (JMSException ignore) {
-				}
-			}
-		}
-	}
-
-}

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

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

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/Util.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/Util.java b/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/Util.java
deleted file mode 100644
index 5f7d24a..0000000
--- a/components/org.apache.stratos.lb.common/src/main/java/org/apache/stratos/lb/common/util/Util.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one 
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
- * KIND, either express or implied.  See the License for the 
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.stratos.lb.common.util;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Util {
-	private static final Log log = LogFactory.getLog(Util.class);
-
-	public static Properties getProperties(String filePath) {
-		Properties props = new Properties();
-		InputStream is = null;
-
-		// load properties from a properties file
-		try {
-			File f = new File(filePath);
-			is = new FileInputStream(f);
-			props.load(is);
-		} catch (Exception e) {
-			log.error("Failed to load properties from file: " + filePath, e);
-		} finally {
-			try {
-				is.close();
-			} catch (IOException ignore) {
-			}
-		}
-
-		return props;
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml b/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
deleted file mode 100644
index f458e62..0000000
--- a/components/org.apache.stratos.lb.common/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version='1.0'?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements.  See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership.  The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License.  You may obtain a copy of the License at
-
-   http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied.  See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-
-<serviceGroup>
-    <service name="LoadBalancerConfigurationService" scope="application">
-        <parameter name="ServiceClass">org.apache.stratos.lb.common.service.impl.LoadBalancerConfigurationServiceImpl</parameter>
-        <messageReceivers>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
-        <messageReceiver mep="http://www.w3.org/ns/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
-    </messageReceivers>
-    </service>
-</serviceGroup> 

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigUtilTest.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigUtilTest.java b/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigUtilTest.java
deleted file mode 100644
index a682bf5..0000000
--- a/components/org.apache.stratos.lb.common/src/test/java/org/apache/stratos/lb/common/test/LoadBalancerConfigUtilTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- *  Licensed to the Apache Software Foundation (ASF) under one
- *  or more contributor license agreements.  See the NOTICE file
- *  distributed with this work for additional information
- *  regarding copyright ownership.  The ASF licenses this file
- *  to you under the Apache License, Version 2.0 (the
- *  "License"); you may not use this file except in compliance
- *  with the License.  You may obtain a copy of the License at
-
- *  http://www.apache.org/licenses/LICENSE-2.0
-
- *  Unless required by applicable law or agreed to in writing,
- *  software distributed under the License is distributed on an
- *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- *  KIND, either express or implied.  See the License for the
- *  specific language governing permissions and limitations
- *  under the License.
- */
-package org.apache.stratos.lb.common.test;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.stratos.lb.common.conf.util.LoadBalancerConfigUtil;
-
-import junit.framework.TestCase;
-
-public class LoadBalancerConfigUtilTest extends TestCase {
-
-    private List<Integer> tenantList1 = Arrays.asList(1,2,3);
-    private List<Integer> tenantList2 = Arrays.asList(1,6,3,4);
-    private List<Integer> tenantList3 = Arrays.asList(43);
-    private List<Integer> tenantList4 = Arrays.asList(0);
-    
-    @Override
-    protected void setUp() throws Exception {
-
-    }
-    
-    public final void testGetTenantIds() {
-        
-        assertEquals(tenantList1, LoadBalancerConfigUtil.getTenantIds("1-3"));
-        assertEquals(tenantList2, LoadBalancerConfigUtil.getTenantIds("1,6,3,4"));
-        assertEquals(tenantList3, LoadBalancerConfigUtil.getTenantIds("43"));
-        assertEquals(tenantList4, LoadBalancerConfigUtil.getTenantIds("*"));
-    }
-
-}

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

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
deleted file mode 100644
index 7622e31..0000000
--- a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer.conf
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-loadbalancer {
-    instances	1;
-    enable_autoscaler	true;
-    # interval between two task executions in milliseconds
-    autoscaler_task_interval	5000;
-    # after an instance booted up, task will wait till this much of time and let the server started up
-    server_startup_delay		15000; #default will be 60000ms
-}
-
-services {
-    defaults {
-        min_app_instances 1;
-        max_app_instances       5;
-        max_requests_per_second   400;
-        alarming_upper_rate 0.65;
-        alarming_lower_rate 0.2;
-        scale_down_factor 0.25;
-        rounds_to_average       10;
-        instances_per_scale_up  1;
-        message_expiry_time     60000;
-    }
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            wso2.as1.domain {
-            	hosts as2.cloud-test.wso2.com;
-            	  min_app_instances   0;
-            	  sub_domain      worker;
-                tenant_range    1-5;
-            }
-            wso2.as2.domain {
-                tenant_range    7;
-            }
-            wso2.as3.domain {
-                sub_domain nirmal;
-                tenant_range    10-20;
-            }
-            
-            wso2.as3.domain {
-                sub_domain nirmal2;
-                tenant_range    21-25;
-            }
-            
-            wso2.esb.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com,mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
deleted file mode 100644
index 9535f06..0000000
--- a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer1.conf
+++ /dev/null
@@ -1,60 +0,0 @@
-#
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-#
-
-loadbalancer {
-    instances	1;
-    enable_autoscaler	true;
-    # interval between two task executions in milliseconds
-    autoscaler_task_interval	5000;
-    # after an instance booted up, task will wait till this much of time and let the server started up
-    server_startup_delay		15000; #default will be 60000ms
-}
-
-services {
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            
-            wso2.as.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-            wso2.as1.domain {
-            	sub_domain nirmal;
-                tenant_range    5-7;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf b/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
deleted file mode 100644
index 6fd85f2..0000000
--- a/components/org.apache.stratos.lb.common/src/test/resources/loadbalancer2.conf
+++ /dev/null
@@ -1,50 +0,0 @@
-#
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
-
-services {
-
-    appserver {
-        hosts                   appserver.cloud-test.wso2.com, as.cloud-test.wso2.com;
-        sub_domain      worker1;
-        domains   {
-            
-            wso2.as.domain {
-            	sub_domain nirmal;
-                tenant_range    *;
-            }
-            wso2.as1.domain {
-            	sub_domain nirmal;
-                tenant_range    5-7;
-            }
-        }
-    }
-    
-    esb {
-        hosts                   esb.cloud-test.wso2.com, mgt.as.cloud-test.wso2.com;
-        domains   {
-            wso2.esb.domain {
-                sub_domain      mgt;
-                tenant_range    *;
-            }
-        }
-    }
-
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.common/src/test/resources/testng.xml b/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
deleted file mode 100644
index 204f936..0000000
--- a/components/org.apache.stratos.lb.common/src/test/resources/testng.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements.  See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership.  The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License.  You may obtain a copy of the License at
-
-   http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied.  See the License for the
- specific language governing permissions and limitations
- under the License.
-
--->
-
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Default suite">
-  <test verbose="2" name="Default test">
-    <classes>
-      <!--class name="org.wso2.carbon.lb.common.test.AgentPersistenceManagerTest">
-          <methods>
-            <include name="addZone" />
-              <include name="addHostMachine" />
-              <include name="deleteHostMachine" />
-          </methods>
-      </class-->
-    </classes>
-  </test>
-</suite>

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

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/b6793bdf/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ClusterContext.java
----------------------------------------------------------------------
diff --git a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ClusterContext.java b/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ClusterContext.java
deleted file mode 100644
index 4721dff..0000000
--- a/components/org.apache.stratos.lb.endpoint/src/main/java/org/apache/stratos/lb/endpoint/ClusterContext.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.stratos.lb.endpoint;
-
-import org.apache.stratos.lb.endpoint.algorithm.AlgorithmContext;
-
-import java.util.Properties;
-
-/**
- * Defines cluster context properties.
- */
-public class ClusterContext {
-    private String serviceName;
-    private String clusterId;
-    private AlgorithmContext algorithmContext;
-    private Properties properties;
-
-    public ClusterContext(String serviceName, String clusterId) {
-        this.serviceName = serviceName;
-        this.clusterId = clusterId;
-    }
-
-    public String getServiceName() {
-        return serviceName;
-    }
-
-    public String getClusterId() {
-        return clusterId;
-    }
-
-    public AlgorithmContext getAlgorithmContext() {
-        return algorithmContext;
-    }
-
-    public void setAlgorithmContext(AlgorithmContext algorithmContext) {
-        this.algorithmContext = algorithmContext;
-    }
-
-    public Properties getProperties() {
-        return properties;
-    }
-
-    public void setProperties(Properties properties) {
-        this.properties = properties;
-    }
-}