You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by la...@apache.org on 2013/06/29 08:20:00 UTC

[01/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Updated Branches:
  refs/heads/master 384b3de96 -> dc8b360af


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
new file mode 100644
index 0000000..678cc63
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
@@ -0,0 +1,41 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.stratos.common.exception;
+
+/**
+ * This class is defined as the general Exception implementation for Stratos. This can be used
+ * within Stratos components when handling exceptions.
+ */
+public class StratosException extends Exception{
+
+    public StratosException() {
+    }
+
+    public StratosException(String message) {
+        super(message);
+    }
+
+    public StratosException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public StratosException(Throwable cause) {
+        super(cause);
+    }
+}


[15/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.xsd b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.xsd
new file mode 100644
index 0000000..9c851a5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.xsd
@@ -0,0 +1,2383 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?xml-stylesheet type="text/xsl" href="annotated-xsd.xsl"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<!-- XML Schema schema for XML Schemas: Part 1: Structures -->
+<!-- Note this schema is NOT the normative structures schema. -->
+<!-- The prose copy in the structures REC is the normative -->
+<!-- version (which shouldn't differ from this one except for -->
+<!-- this comment and entity expansions, but just in case -->
+<!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "XMLSchema.dtd" [
+        <!-- provide ID type information even for parsers which only read the
+      internal subset -->
+        <!ATTLIST xs:schema
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:complexType
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:complexContent
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:simpleContent
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:extension
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:element
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:group
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:all
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:choice
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:sequence
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:any
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:anyAttribute
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:attribute
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:attributeGroup
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:unique
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:key
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:keyref
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:selector
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:field
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:include
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:import
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:redefine
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:notation
+                id ID #IMPLIED
+                >
+        <!--
+           keep this schema XML1.0 DTD valid
+        -->
+        <!ENTITY % schemaAttrs 'xmlns:hfp CDATA #IMPLIED'>
+        <!ELEMENT hfp:hasFacet EMPTY>
+        <!ATTLIST hfp:hasFacet
+                name NMTOKEN #REQUIRED
+                >
+        <!ELEMENT hfp:hasProperty EMPTY>
+        <!ATTLIST hfp:hasProperty
+                name NMTOKEN #REQUIRED
+                value CDATA #REQUIRED
+                >
+        <!--
+              Make sure that processors that do not read the external
+              subset will know about the various IDs we declare
+        -->
+        <!ATTLIST xs:simpleType
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:maxExclusive
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:minExclusive
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:maxInclusive
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:minInclusive
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:totalDigits
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:fractionDigits
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:length
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:minLength
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:maxLength
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:enumeration
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:pattern
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:appinfo
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:documentation
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:list
+                id ID #IMPLIED
+                >
+        <!ATTLIST xs:union
+                id ID #IMPLIED
+                >
+        ]>
+<xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema" blockDefault="#all"
+           elementFormDefault="qualified" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
+           xml:lang="EN" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty">
+    <xs:annotation>
+        <xs:documentation>
+            Part 1 version: Id: XMLSchema.xsd,v 1.53 2003/02/24 17:40:07 ht Exp
+            Part 2 version: Id: datatypes.xsd,v 1.60 2003/04/05 11:02:30 ht Exp
+        </xs:documentation>
+    </xs:annotation>
+    <xs:annotation>
+        <xs:documentation
+                source="http://www.w3.org/XML/Group/2002/09/xmlschema-1/structures-with-errata.html">
+            The schema corresponding to this document is normative,
+            with respect to the syntactic constraints it expresses in the
+            XML Schema language. The documentation (within &lt;documentation> elements)
+            below, is not normative, but rather highlights important aspects of
+            the W3C Recommendation of which this is a part
+        </xs:documentation>
+    </xs:annotation>
+    <xs:annotation>
+        <xs:documentation>
+            The simpleType element and all of its members are defined
+            towards the end of this schema document
+        </xs:documentation>
+    </xs:annotation>
+    <xs:import namespace="http://www.w3.org/XML/1998/namespace"
+               schemaLocation="http://www.w3.org/2001/xml.xsd">
+        <xs:annotation>
+            <xs:documentation>
+                Get access to the xml: attribute groups for xml:lang
+                as declared on 'schema' and 'documentation' below
+            </xs:documentation>
+        </xs:annotation>
+    </xs:import>
+    <xs:complexType name="openAttrs">
+        <xs:annotation>
+            <xs:documentation>
+                This type is extended by almost all schema types
+                to allow attributes from other namespaces to be
+                added to user schemas.
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:restriction base="xs:anyType">
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="annotated">
+        <xs:annotation>
+            <xs:documentation>
+                This type is extended by all types which allow annotation
+                other than &lt;schema&gt; itself
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:extension base="xs:openAttrs">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                </xs:sequence>
+                <xs:attribute name="id" type="xs:ID"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:group name="schemaTop">
+        <xs:annotation>
+            <xs:documentation>
+                This group is for the
+                elements which occur freely at the top level of schemas.
+                All of their types are based on the "annotated" type by extension.
+            </xs:documentation>
+        </xs:annotation>
+        <xs:choice>
+            <xs:group ref="xs:redefinable"/>
+            <xs:element ref="xs:element"/>
+            <xs:element ref="xs:attribute"/>
+            <xs:element ref="xs:notation"/>
+        </xs:choice>
+    </xs:group>
+    <xs:group name="redefinable">
+        <xs:annotation>
+            <xs:documentation>
+                This group is for the
+                elements which can self-redefine (see &lt;redefine> below).
+            </xs:documentation>
+        </xs:annotation>
+        <xs:choice>
+            <xs:element ref="xs:simpleType"/>
+            <xs:element ref="xs:complexType"/>
+            <xs:element ref="xs:group"/>
+            <xs:element ref="xs:attributeGroup"/>
+        </xs:choice>
+    </xs:group>
+    <xs:simpleType name="formChoice">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:NMTOKEN">
+            <xs:enumeration value="qualified"/>
+            <xs:enumeration value="unqualified"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="reducedDerivationControl">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:derivationControl">
+            <xs:enumeration value="extension"/>
+            <xs:enumeration value="restriction"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="derivationSet">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+            <xs:documentation>
+                #all or (possibly empty) subset of {extension, restriction}
+            </xs:documentation>
+        </xs:annotation>
+        <xs:union>
+            <xs:simpleType>
+                <xs:restriction base="xs:token">
+                    <xs:enumeration value="#all"/>
+                </xs:restriction>
+            </xs:simpleType>
+            <xs:simpleType>
+                <xs:list itemType="xs:reducedDerivationControl"/>
+            </xs:simpleType>
+        </xs:union>
+    </xs:simpleType>
+    <xs:element name="schema" id="schema">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-schema"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:openAttrs">
+                    <xs:sequence>
+                        <xs:choice minOccurs="0" maxOccurs="unbounded">
+                            <xs:element ref="xs:include"/>
+                            <xs:element ref="xs:import"/>
+                            <xs:element ref="xs:redefine"/>
+                            <xs:element ref="xs:annotation"/>
+                        </xs:choice>
+                        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                            <xs:group ref="xs:schemaTop"/>
+                            <xs:element ref="xs:annotation" minOccurs="0" maxOccurs="unbounded"/>
+                        </xs:sequence>
+                    </xs:sequence>
+                    <xs:attribute name="targetNamespace" type="xs:anyURI"/>
+                    <xs:attribute name="version" type="xs:normalizedString"/>
+                    <xs:attribute name="finalDefault" type="xs:derivationSet" use="optional"
+                                  default=""/>
+                    <xs:attribute name="blockDefault" type="xs:blockSet" use="optional" default=""/>
+                    <xs:attribute name="attributeFormDefault" type="xs:formChoice" use="optional"
+                                  default="unqualified"/>
+                    <xs:attribute name="elementFormDefault" type="xs:formChoice" use="optional"
+                                  default="unqualified"/>
+                    <xs:attribute name="id" type="xs:ID"/>
+                    <xs:attribute ref="xml:lang"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+        <xs:key name="element">
+            <xs:selector xpath="xs:element"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="attribute">
+            <xs:selector xpath="xs:attribute"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="type">
+            <xs:selector xpath="xs:complexType|xs:simpleType"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="group">
+            <xs:selector xpath="xs:group"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="attributeGroup">
+            <xs:selector xpath="xs:attributeGroup"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="notation">
+            <xs:selector xpath="xs:notation"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+        <xs:key name="identityConstraint">
+            <xs:selector xpath=".//xs:key|.//xs:unique|.//xs:keyref"/>
+            <xs:field xpath="@name"/>
+        </xs:key>
+    </xs:element>
+    <xs:simpleType name="allNNI">
+        <xs:annotation>
+            <xs:documentation>
+                for maxOccurs
+            </xs:documentation>
+        </xs:annotation>
+        <xs:union memberTypes="xs:nonNegativeInteger">
+            <xs:simpleType>
+                <xs:restriction base="xs:NMTOKEN">
+                    <xs:enumeration value="unbounded"/>
+                </xs:restriction>
+            </xs:simpleType>
+        </xs:union>
+    </xs:simpleType>
+    <xs:attributeGroup name="occurs">
+        <xs:annotation>
+            <xs:documentation>
+                for all particles
+            </xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
+        <xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>
+    </xs:attributeGroup>
+    <xs:attributeGroup name="defRef">
+        <xs:annotation>
+            <xs:documentation>
+                for element, group and attributeGroup,
+                which both define and reference
+            </xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="name" type="xs:NCName"/>
+        <xs:attribute name="ref" type="xs:QName"/>
+    </xs:attributeGroup>
+    <xs:group name="typeDefParticle">
+        <xs:annotation>
+            <xs:documentation>
+                'complexType' uses this
+            </xs:documentation>
+        </xs:annotation>
+        <xs:choice>
+            <xs:element name="group" type="xs:groupRef"/>
+            <xs:element ref="xs:all"/>
+            <xs:element ref="xs:choice"/>
+            <xs:element ref="xs:sequence"/>
+        </xs:choice>
+    </xs:group>
+    <xs:group name="nestedParticle">
+        <xs:choice>
+            <xs:element name="element" type="xs:localElement"/>
+            <xs:element name="group" type="xs:groupRef"/>
+            <xs:element ref="xs:choice"/>
+            <xs:element ref="xs:sequence"/>
+            <xs:element ref="xs:any"/>
+        </xs:choice>
+    </xs:group>
+    <xs:group name="particle">
+        <xs:choice>
+            <xs:element name="element" type="xs:localElement"/>
+            <xs:element name="group" type="xs:groupRef"/>
+            <xs:element ref="xs:all"/>
+            <xs:element ref="xs:choice"/>
+            <xs:element ref="xs:sequence"/>
+            <xs:element ref="xs:any"/>
+        </xs:choice>
+    </xs:group>
+    <xs:complexType name="attribute">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:sequence>
+                    <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/>
+                </xs:sequence>
+                <xs:attributeGroup ref="xs:defRef"/>
+                <xs:attribute name="type" type="xs:QName"/>
+                <xs:attribute name="use" use="optional" default="optional">
+                    <xs:simpleType>
+                        <xs:restriction base="xs:NMTOKEN">
+                            <xs:enumeration value="prohibited"/>
+                            <xs:enumeration value="optional"/>
+                            <xs:enumeration value="required"/>
+                        </xs:restriction>
+                    </xs:simpleType>
+                </xs:attribute>
+                <xs:attribute name="default" type="xs:string"/>
+                <xs:attribute name="fixed" type="xs:string"/>
+                <xs:attribute name="form" type="xs:formChoice"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="topLevelAttribute">
+        <xs:complexContent>
+            <xs:restriction base="xs:attribute">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/>
+                </xs:sequence>
+                <xs:attribute name="ref" use="prohibited"/>
+                <xs:attribute name="form" use="prohibited"/>
+                <xs:attribute name="use" use="prohibited"/>
+                <xs:attribute name="name" use="required" type="xs:NCName"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:group name="attrDecls">
+        <xs:sequence>
+            <xs:choice minOccurs="0" maxOccurs="unbounded">
+                <xs:element name="attribute" type="xs:attribute"/>
+                <xs:element name="attributeGroup" type="xs:attributeGroupRef"/>
+            </xs:choice>
+            <xs:element ref="xs:anyAttribute" minOccurs="0"/>
+        </xs:sequence>
+    </xs:group>
+    <xs:element name="anyAttribute" type="xs:wildcard" id="anyAttribute">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-anyAttribute"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:group name="complexTypeModel">
+        <xs:choice>
+            <xs:element ref="xs:simpleContent"/>
+            <xs:element ref="xs:complexContent"/>
+            <xs:sequence>
+                <xs:annotation>
+                    <xs:documentation>
+                        This branch is short for
+                        &lt;complexContent>
+                        &lt;restriction base="xs:anyType">
+                        ...
+                        &lt;/restriction>
+                        &lt;/complexContent>
+                    </xs:documentation>
+                </xs:annotation>
+                <xs:group ref="xs:typeDefParticle" minOccurs="0"/>
+                <xs:group ref="xs:attrDecls"/>
+            </xs:sequence>
+        </xs:choice>
+    </xs:group>
+    <xs:complexType name="complexType" abstract="true">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:group ref="xs:complexTypeModel"/>
+                <xs:attribute name="name" type="xs:NCName">
+                    <xs:annotation>
+                        <xs:documentation>
+                            Will be restricted to required or forbidden
+                        </xs:documentation>
+                    </xs:annotation>
+                </xs:attribute>
+                <xs:attribute name="mixed" type="xs:boolean" use="optional" default="false">
+                    <xs:annotation>
+                        <xs:documentation>
+                            Not allowed if simpleContent child is chosen.
+                            May be overriden by setting on complexContent child.
+                        </xs:documentation>
+                    </xs:annotation>
+                </xs:attribute>
+                <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/>
+                <xs:attribute name="final" type="xs:derivationSet"/>
+                <xs:attribute name="block" type="xs:derivationSet"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="topLevelComplexType">
+        <xs:complexContent>
+            <xs:restriction base="xs:complexType">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:complexTypeModel"/>
+                </xs:sequence>
+                <xs:attribute name="name" type="xs:NCName" use="required"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="localComplexType">
+        <xs:complexContent>
+            <xs:restriction base="xs:complexType">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:complexTypeModel"/>
+                </xs:sequence>
+                <xs:attribute name="name" use="prohibited"/>
+                <xs:attribute name="abstract" use="prohibited"/>
+                <xs:attribute name="final" use="prohibited"/>
+                <xs:attribute name="block" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="restrictionType">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:sequence>
+                    <xs:choice minOccurs="0">
+                        <xs:group ref="xs:typeDefParticle"/>
+                        <xs:group ref="xs:simpleRestrictionModel"/>
+                    </xs:choice>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:attribute name="base" type="xs:QName" use="required"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="complexRestrictionType">
+        <xs:complexContent>
+            <xs:restriction base="xs:restrictionType">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="0">
+                        <xs:annotation>
+                            <xs:documentation>This choice is added simply to
+                                make this a valid restriction per the REC
+                            </xs:documentation>
+                        </xs:annotation>
+                        <xs:group ref="xs:typeDefParticle"/>
+                    </xs:choice>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="extensionType">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:sequence>
+                    <xs:group ref="xs:typeDefParticle" minOccurs="0"/>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:attribute name="base" type="xs:QName" use="required"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="complexContent" id="complexContent">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexContent"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:choice>
+                        <xs:element name="restriction" type="xs:complexRestrictionType"/>
+                        <xs:element name="extension" type="xs:extensionType"/>
+                    </xs:choice>
+                    <xs:attribute name="mixed" type="xs:boolean">
+                        <xs:annotation>
+                            <xs:documentation>
+                                Overrides any setting on complexType parent.
+                            </xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:complexType name="simpleRestrictionType">
+        <xs:complexContent>
+            <xs:restriction base="xs:restrictionType">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="0">
+                        <xs:annotation>
+                            <xs:documentation>This choice is added simply to
+                                make this a valid restriction per the REC
+                            </xs:documentation>
+                        </xs:annotation>
+                        <xs:group ref="xs:simpleRestrictionModel"/>
+                    </xs:choice>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="simpleExtensionType">
+        <xs:complexContent>
+            <xs:restriction base="xs:extensionType">
+                <xs:sequence>
+                    <xs:annotation>
+                        <xs:documentation>
+                            No typeDefParticle group reference
+                        </xs:documentation>
+                    </xs:annotation>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="simpleContent" id="simpleContent">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-simpleContent"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:choice>
+                        <xs:element name="restriction" type="xs:simpleRestrictionType"/>
+                        <xs:element name="extension" type="xs:simpleExtensionType"/>
+                    </xs:choice>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="complexType" type="xs:topLevelComplexType" id="complexType">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexType"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:simpleType name="blockSet">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+            <xs:documentation>
+                #all or (possibly empty) subset of {substitution, extension,
+                restriction}
+            </xs:documentation>
+        </xs:annotation>
+        <xs:union>
+            <xs:simpleType>
+                <xs:restriction base="xs:token">
+                    <xs:enumeration value="#all"/>
+                </xs:restriction>
+            </xs:simpleType>
+            <xs:simpleType>
+                <xs:list>
+                    <xs:simpleType>
+                        <xs:restriction base="xs:derivationControl">
+                            <xs:enumeration value="extension"/>
+                            <xs:enumeration value="restriction"/>
+                            <xs:enumeration value="substitution"/>
+                        </xs:restriction>
+                    </xs:simpleType>
+                </xs:list>
+            </xs:simpleType>
+        </xs:union>
+    </xs:simpleType>
+    <xs:complexType name="element" abstract="true">
+        <xs:annotation>
+            <xs:documentation>
+                The element element can be used either
+                at the top level to define an element-type binding globally,
+                or within a content model to either reference a globally-defined
+                element or type or declare an element-type binding locally.
+                The ref form is not allowed at the top level.
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:sequence>
+                    <xs:choice minOccurs="0">
+                        <xs:element name="simpleType" type="xs:localSimpleType"/>
+                        <xs:element name="complexType" type="xs:localComplexType"/>
+                    </xs:choice>
+                    <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attributeGroup ref="xs:defRef"/>
+                <xs:attribute name="type" type="xs:QName"/>
+                <xs:attribute name="substitutionGroup" type="xs:QName"/>
+                <xs:attributeGroup ref="xs:occurs"/>
+                <xs:attribute name="default" type="xs:string"/>
+                <xs:attribute name="fixed" type="xs:string"/>
+                <xs:attribute name="nillable" type="xs:boolean" use="optional" default="false"/>
+                <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/>
+                <xs:attribute name="final" type="xs:derivationSet"/>
+                <xs:attribute name="block" type="xs:blockSet"/>
+                <xs:attribute name="form" type="xs:formChoice"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="topLevelElement">
+        <xs:complexContent>
+            <xs:restriction base="xs:element">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="0">
+                        <xs:element name="simpleType" type="xs:localSimpleType"/>
+                        <xs:element name="complexType" type="xs:localComplexType"/>
+                    </xs:choice>
+                    <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="ref" use="prohibited"/>
+                <xs:attribute name="form" use="prohibited"/>
+                <xs:attribute name="minOccurs" use="prohibited"/>
+                <xs:attribute name="maxOccurs" use="prohibited"/>
+                <xs:attribute name="name" use="required" type="xs:NCName"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="localElement">
+        <xs:complexContent>
+            <xs:restriction base="xs:element">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="0">
+                        <xs:element name="simpleType" type="xs:localSimpleType"/>
+                        <xs:element name="complexType" type="xs:localComplexType"/>
+                    </xs:choice>
+                    <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="substitutionGroup" use="prohibited"/>
+                <xs:attribute name="final" use="prohibited"/>
+                <xs:attribute name="abstract" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="element" type="xs:topLevelElement" id="element">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-element"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:complexType name="group" abstract="true">
+        <xs:annotation>
+            <xs:documentation>
+                group type for explicit groups, named top-level groups and
+                group references
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:group ref="xs:particle" minOccurs="0" maxOccurs="unbounded"/>
+                <xs:attributeGroup ref="xs:defRef"/>
+                <xs:attributeGroup ref="xs:occurs"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="realGroup">
+        <xs:complexContent>
+            <xs:restriction base="xs:group">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="0" maxOccurs="1">
+                        <xs:element ref="xs:all"/>
+                        <xs:element ref="xs:choice"/>
+                        <xs:element ref="xs:sequence"/>
+                    </xs:choice>
+                </xs:sequence>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="namedGroup">
+        <xs:complexContent>
+            <xs:restriction base="xs:realGroup">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:choice minOccurs="1" maxOccurs="1">
+                        <xs:element name="all">
+                            <xs:complexType>
+                                <xs:complexContent>
+                                    <xs:restriction base="xs:all">
+                                        <xs:group ref="xs:allModel"/>
+                                        <xs:attribute name="minOccurs" use="prohibited"/>
+                                        <xs:attribute name="maxOccurs" use="prohibited"/>
+                                        <xs:anyAttribute namespace="##other" processContents="lax"/>
+                                    </xs:restriction>
+                                </xs:complexContent>
+                            </xs:complexType>
+                        </xs:element>
+                        <xs:element name="choice" type="xs:simpleExplicitGroup"/>
+                        <xs:element name="sequence" type="xs:simpleExplicitGroup"/>
+                    </xs:choice>
+                </xs:sequence>
+                <xs:attribute name="name" use="required" type="xs:NCName"/>
+                <xs:attribute name="ref" use="prohibited"/>
+                <xs:attribute name="minOccurs" use="prohibited"/>
+                <xs:attribute name="maxOccurs" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="groupRef">
+        <xs:complexContent>
+            <xs:restriction base="xs:realGroup">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                </xs:sequence>
+                <xs:attribute name="ref" use="required" type="xs:QName"/>
+                <xs:attribute name="name" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="explicitGroup">
+        <xs:annotation>
+            <xs:documentation>
+                group type for the three kinds of group
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:restriction base="xs:group">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="name" type="xs:NCName" use="prohibited"/>
+                <xs:attribute name="ref" type="xs:QName" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="simpleExplicitGroup">
+        <xs:complexContent>
+            <xs:restriction base="xs:explicitGroup">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="minOccurs" use="prohibited"/>
+                <xs:attribute name="maxOccurs" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:group name="allModel">
+        <xs:sequence>
+            <xs:element ref="xs:annotation" minOccurs="0"/>
+            <xs:choice minOccurs="0" maxOccurs="unbounded">
+                <xs:annotation>
+                    <xs:documentation>This choice with min/max is here to
+                        avoid a pblm with the Elt:All/Choice/Seq
+                        Particle derivation constraint
+                    </xs:documentation>
+                </xs:annotation>
+                <xs:element name="element">
+                    <xs:complexType>
+                        <xs:annotation>
+                            <xs:documentation>restricted max/min</xs:documentation>
+                        </xs:annotation>
+                        <xs:complexContent>
+                            <xs:restriction base="xs:localElement">
+                                <xs:sequence>
+                                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                                    <xs:choice minOccurs="0">
+                                        <xs:element name="simpleType" type="xs:localSimpleType"/>
+                                        <xs:element name="complexType" type="xs:localComplexType"/>
+                                    </xs:choice>
+                                    <xs:group ref="xs:identityConstraint" minOccurs="0"
+                                              maxOccurs="unbounded"/>
+                                </xs:sequence>
+                                <xs:attribute name="minOccurs" use="optional" default="1">
+                                    <xs:simpleType>
+                                        <xs:restriction base="xs:nonNegativeInteger">
+                                            <xs:enumeration value="0"/>
+                                            <xs:enumeration value="1"/>
+                                        </xs:restriction>
+                                    </xs:simpleType>
+                                </xs:attribute>
+                                <xs:attribute name="maxOccurs" use="optional" default="1">
+                                    <xs:simpleType>
+                                        <xs:restriction base="xs:allNNI">
+                                            <xs:enumeration value="0"/>
+                                            <xs:enumeration value="1"/>
+                                        </xs:restriction>
+                                    </xs:simpleType>
+                                </xs:attribute>
+                                <xs:anyAttribute namespace="##other" processContents="lax"/>
+                            </xs:restriction>
+                        </xs:complexContent>
+                    </xs:complexType>
+                </xs:element>
+            </xs:choice>
+        </xs:sequence>
+    </xs:group>
+    <xs:complexType name="all">
+        <xs:annotation>
+            <xs:documentation>
+                Only elements allowed inside
+            </xs:documentation>
+        </xs:annotation>
+        <xs:complexContent>
+            <xs:restriction base="xs:explicitGroup">
+                <xs:group ref="xs:allModel"/>
+                <xs:attribute name="minOccurs" use="optional" default="1">
+                    <xs:simpleType>
+                        <xs:restriction base="xs:nonNegativeInteger">
+                            <xs:enumeration value="0"/>
+                            <xs:enumeration value="1"/>
+                        </xs:restriction>
+                    </xs:simpleType>
+                </xs:attribute>
+                <xs:attribute name="maxOccurs" use="optional" default="1">
+                    <xs:simpleType>
+                        <xs:restriction base="xs:allNNI">
+                            <xs:enumeration value="1"/>
+                        </xs:restriction>
+                    </xs:simpleType>
+                </xs:attribute>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="all" id="all" type="xs:all">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-all"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="choice" type="xs:explicitGroup" id="choice">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-choice"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="sequence" type="xs:explicitGroup" id="sequence">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-sequence"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="group" type="xs:namedGroup" id="group">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-group"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:complexType name="wildcard">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:attribute name="namespace" type="xs:namespaceList" use="optional"
+                              default="##any"/>
+                <xs:attribute name="processContents" use="optional" default="strict">
+                    <xs:simpleType>
+                        <xs:restriction base="xs:NMTOKEN">
+                            <xs:enumeration value="skip"/>
+                            <xs:enumeration value="lax"/>
+                            <xs:enumeration value="strict"/>
+                        </xs:restriction>
+                    </xs:simpleType>
+                </xs:attribute>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="any" id="any">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-any"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:wildcard">
+                    <xs:attributeGroup ref="xs:occurs"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:annotation>
+        <xs:documentation>
+            simple type for the value of the 'namespace' attr of
+            'any' and 'anyAttribute'
+        </xs:documentation>
+    </xs:annotation>
+    <xs:annotation>
+        <xs:documentation>
+            Value is
+            ##any - - any non-conflicting WFXML/attribute at all
+
+            ##other - - any non-conflicting WFXML/attribute from
+            namespace other than targetNS
+
+            ##local - - any unqualified non-conflicting WFXML/attribute
+
+            one or - - any non-conflicting WFXML/attribute from
+            more URI the listed namespaces
+            references
+            (space separated)
+
+            ##targetNamespace or ##local may appear in the above list, to
+            refer to the targetNamespace of the enclosing
+            schema or an absent targetNamespace respectively
+        </xs:documentation>
+    </xs:annotation>
+    <xs:simpleType name="namespaceList">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+        </xs:annotation>
+        <xs:union>
+            <xs:simpleType>
+                <xs:restriction base="xs:token">
+                    <xs:enumeration value="##any"/>
+                    <xs:enumeration value="##other"/>
+                </xs:restriction>
+            </xs:simpleType>
+            <xs:simpleType>
+                <xs:list>
+                    <xs:simpleType>
+                        <xs:union memberTypes="xs:anyURI">
+                            <xs:simpleType>
+                                <xs:restriction base="xs:token">
+                                    <xs:enumeration value="##targetNamespace"/>
+                                    <xs:enumeration value="##local"/>
+                                </xs:restriction>
+                            </xs:simpleType>
+                        </xs:union>
+                    </xs:simpleType>
+                </xs:list>
+            </xs:simpleType>
+        </xs:union>
+    </xs:simpleType>
+    <xs:element name="attribute" type="xs:topLevelAttribute" id="attribute">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attribute"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:complexType name="attributeGroup" abstract="true">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:group ref="xs:attrDecls"/>
+                <xs:attributeGroup ref="xs:defRef"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="namedAttributeGroup">
+        <xs:complexContent>
+            <xs:restriction base="xs:attributeGroup">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                    <xs:group ref="xs:attrDecls"/>
+                </xs:sequence>
+                <xs:attribute name="name" use="required" type="xs:NCName"/>
+                <xs:attribute name="ref" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:complexType name="attributeGroupRef">
+        <xs:complexContent>
+            <xs:restriction base="xs:attributeGroup">
+                <xs:sequence>
+                    <xs:element ref="xs:annotation" minOccurs="0"/>
+                </xs:sequence>
+                <xs:attribute name="ref" use="required" type="xs:QName"/>
+                <xs:attribute name="name" use="prohibited"/>
+                <xs:anyAttribute namespace="##other" processContents="lax"/>
+            </xs:restriction>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:element name="attributeGroup" type="xs:namedAttributeGroup" id="attributeGroup">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attributeGroup"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="include" id="include">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-include"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="redefine" id="redefine">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-redefine"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:openAttrs">
+                    <xs:choice minOccurs="0" maxOccurs="unbounded">
+                        <xs:element ref="xs:annotation"/>
+                        <xs:group ref="xs:redefinable"/>
+                    </xs:choice>
+                    <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/>
+                    <xs:attribute name="id" type="xs:ID"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="import" id="import">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-import"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:attribute name="namespace" type="xs:anyURI"/>
+                    <xs:attribute name="schemaLocation" type="xs:anyURI"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="selector" id="selector">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-selector"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:attribute name="xpath" use="required">
+                        <xs:simpleType>
+                            <xs:annotation>
+                                <xs:documentation>A subset of XPath expressions for use
+                                    in selectors
+                                </xs:documentation>
+                                <xs:documentation>A utility type, not for public
+                                    use
+                                </xs:documentation>
+                            </xs:annotation>
+                            <xs:restriction base="xs:token">
+                                <xs:annotation>
+                                    <xs:documentation>The following pattern is intended to allow
+                                        XPath
+                                        expressions per the following EBNF:
+                                        Selector ::= Path ( '|' Path )*
+                                        Path ::= ('.//')? Step ( '/' Step )*
+                                        Step ::= '.' | NameTest
+                                        NameTest ::= QName | '*' | NCName ':' '*'
+                                        child:: is also allowed
+                                    </xs:documentation>
+                                </xs:annotation>
+                                <xs:pattern
+                                        value="(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)*">
+                                </xs:pattern>
+                            </xs:restriction>
+                        </xs:simpleType>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="field" id="field">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-field"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:attribute name="xpath" use="required">
+                        <xs:simpleType>
+                            <xs:annotation>
+                                <xs:documentation>A subset of XPath expressions for use
+                                    in fields
+                                </xs:documentation>
+                                <xs:documentation>A utility type, not for public
+                                    use
+                                </xs:documentation>
+                            </xs:annotation>
+                            <xs:restriction base="xs:token">
+                                <xs:annotation>
+                                    <xs:documentation>The following pattern is intended to allow
+                                        XPath
+                                        expressions per the same EBNF as for selector,
+                                        with the following change:
+                                        Path ::= ('.//')? ( Step '/' )* ( Step | '@' NameTest )
+                                    </xs:documentation>
+                                </xs:annotation>
+                                <xs:pattern
+                                        value="(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*)))))*">
+                                </xs:pattern>
+                            </xs:restriction>
+                        </xs:simpleType>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:complexType name="keybase">
+        <xs:complexContent>
+            <xs:extension base="xs:annotated">
+                <xs:sequence>
+                    <xs:element ref="xs:selector"/>
+                    <xs:element ref="xs:field" minOccurs="1" maxOccurs="unbounded"/>
+                </xs:sequence>
+                <xs:attribute name="name" type="xs:NCName" use="required"/>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <xs:group name="identityConstraint">
+        <xs:annotation>
+            <xs:documentation>The three kinds of identity constraints, all with
+                type of or derived from 'keybase'.
+            </xs:documentation>
+        </xs:annotation>
+        <xs:choice>
+            <xs:element ref="xs:unique"/>
+            <xs:element ref="xs:key"/>
+            <xs:element ref="xs:keyref"/>
+        </xs:choice>
+    </xs:group>
+    <xs:element name="unique" type="xs:keybase" id="unique">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-unique"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="key" type="xs:keybase" id="key">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-key"/>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="keyref" id="keyref">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-keyref"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:keybase">
+                    <xs:attribute name="refer" type="xs:QName" use="required"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="notation" id="notation">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-notation"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:annotated">
+                    <xs:attribute name="name" type="xs:NCName" use="required"/>
+                    <xs:attribute name="public" type="xs:public"/>
+                    <xs:attribute name="system" type="xs:anyURI"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:simpleType name="public">
+        <xs:annotation>
+            <xs:documentation>
+                A utility type, not for public use
+            </xs:documentation>
+            <xs:documentation>
+                A public identifier, per ISO 8879
+            </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:token"/>
+    </xs:simpleType>
+    <xs:element name="appinfo" id="appinfo">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-appinfo"/>
+        </xs:annotation>
+        <xs:complexType mixed="true">
+            <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                <xs:any processContents="lax"/>
+            </xs:sequence>
+            <xs:attribute name="source" type="xs:anyURI"/>
+            <xs:anyAttribute namespace="##other" processContents="lax"/>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="documentation" id="documentation">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-documentation"/>
+        </xs:annotation>
+        <xs:complexType mixed="true">
+            <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                <xs:any processContents="lax"/>
+            </xs:sequence>
+            <xs:attribute name="source" type="xs:anyURI"/>
+            <xs:attribute ref="xml:lang"/>
+            <xs:anyAttribute namespace="##other" processContents="lax"/>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="annotation" id="annotation">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-annotation"/>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="xs:openAttrs">
+                    <xs:choice minOccurs="0" maxOccurs="unbounded">
+                        <xs:element ref="xs:appinfo"/>
+                        <xs:element ref="xs:documentation"/>
+                    </xs:choice>
+                    <xs:attribute name="id" type="xs:ID"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:annotation>
+        <xs:documentation>
+            notations for use within XML Schema schemas
+        </xs:documentation>
+    </xs:annotation>
+    <xs:notation name="XMLSchemaStructures" public="structures"
+                 system="http://www.w3.org/2000/08/XMLSchema.xsd"/>
+    <xs:notation name="XML" public="REC-xml-19980210"
+                 system="http://www.w3.org/TR/1998/REC-xml-19980210"/>
+    <xs:complexType name="anyType" mixed="true">
+        <xs:annotation>
+            <xs:documentation>
+                Not the real urType, but as close an approximation as we can
+                get in the XML representation
+            </xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+            <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
+        </xs:sequence>
+        <xs:anyAttribute processContents="lax"/>
+    </xs:complexType>
+    <xs:annotation>
+        <xs:documentation>
+            First the built-in primitive datatypes. These definitions are for
+            information only, the real built-in definitions are magic.
+        </xs:documentation>
+        <xs:documentation>
+            For each built-in datatype in this schema (both primitive and
+            derived) can be uniquely addressed via a URI constructed
+            as follows:
+            1) the base URI is the URI of the XML Schema namespace
+            2) the fragment identifier is the name of the datatype
+
+            For example, to address the int datatype, the URI is:
+
+            http://www.w3.org/2001/XMLSchema#int
+
+            Additionally, each facet definition element can be uniquely
+            addressed via a URI constructed as follows:
+            1) the base URI is the URI of the XML Schema namespace
+            2) the fragment identifier is the name of the facet
+
+            For example, to address the maxInclusive facet, the URI is:
+
+            http://www.w3.org/2001/XMLSchema#maxInclusive
+
+            Additionally, each facet usage in a built-in datatype definition
+            can be uniquely addressed via a URI constructed as follows:
+            1) the base URI is the URI of the XML Schema namespace
+            2) the fragment identifier is the name of the datatype, followed
+            by a period (".") followed by the name of the facet
+
+            For example, to address the usage of the maxInclusive facet in
+            the definition of int, the URI is:
+
+            http://www.w3.org/2001/XMLSchema#int.maxInclusive
+
+        </xs:documentation>
+    </xs:annotation>
+    <xs:simpleType name="string" id="string">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#string"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="preserve" id="string.preserve"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="boolean" id="boolean">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="finite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#boolean"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="boolean.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="float" id="float">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="total"/>
+                <hfp:hasProperty name="bounded" value="true"/>
+                <hfp:hasProperty name="cardinality" value="finite"/>
+                <hfp:hasProperty name="numeric" value="true"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#float"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="float.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="double" id="double">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="total"/>
+                <hfp:hasProperty name="bounded" value="true"/>
+                <hfp:hasProperty name="cardinality" value="finite"/>
+                <hfp:hasProperty name="numeric" value="true"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#double"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="double.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="decimal" id="decimal">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="totalDigits"/>
+                <hfp:hasFacet name="fractionDigits"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="total"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="true"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#decimal"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="decimal.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="duration" id="duration">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#duration"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="duration.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="dateTime" id="dateTime">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#dateTime"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="dateTime.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="time" id="time">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#time"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="time.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="date" id="date">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#date"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="date.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="gYearMonth" id="gYearMonth">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYearMonth"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="gYearMonth.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="gYear" id="gYear">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gYear"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="gYear.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="gMonthDay" id="gMonthDay">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonthDay"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="gMonthDay.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="gDay" id="gDay">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gDay"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="gDay.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="gMonth" id="gMonth">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasFacet name="maxInclusive"/>
+                <hfp:hasFacet name="maxExclusive"/>
+                <hfp:hasFacet name="minInclusive"/>
+                <hfp:hasFacet name="minExclusive"/>
+                <hfp:hasProperty name="ordered" value="partial"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#gMonth"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="gMonth.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="hexBinary" id="hexBinary">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#binary"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="hexBinary.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="base64Binary" id="base64Binary">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#base64Binary"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="base64Binary.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="anyURI" id="anyURI">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#anyURI"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="anyURI.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="QName" id="QName">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#QName"/>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="QName.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="NOTATION" id="NOTATION">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="pattern"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NOTATION"/>
+            <xs:documentation>
+                NOTATION cannot be used directly in a schema; rather a type
+                must be derived from it by specifying at least one enumeration
+                facet whose value is the name of a NOTATION declared in the
+                schema.
+            </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:anySimpleType">
+            <xs:whiteSpace value="collapse" fixed="true" id="NOTATION.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:annotation>
+        <xs:documentation>
+            Now the derived primitive types
+        </xs:documentation>
+    </xs:annotation>
+    <xs:simpleType name="normalizedString" id="normalizedString">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#normalizedString"/>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+            <xs:whiteSpace value="replace" id="normalizedString.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="token" id="token">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#token"/>
+        </xs:annotation>
+        <xs:restriction base="xs:normalizedString">
+            <xs:whiteSpace value="collapse" id="token.whiteSpace"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="language" id="language">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#language"/>
+        </xs:annotation>
+        <xs:restriction base="xs:token">
+            <xs:pattern value="[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*" id="language.pattern">
+                <xs:annotation>
+                    <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-LanguageID">
+                        pattern specifies the content of section 2.12 of XML 1.0e2
+                        and RFC 3066 (Revised version of RFC 1766).
+                    </xs:documentation>
+                </xs:annotation>
+            </xs:pattern>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="IDREFS" id="IDREFS">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#IDREFS"/>
+        </xs:annotation>
+        <xs:restriction>
+            <xs:simpleType>
+                <xs:list itemType="xs:IDREF"/>
+            </xs:simpleType>
+            <xs:minLength value="1" id="IDREFS.minLength"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="ENTITIES" id="ENTITIES">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#ENTITIES"/>
+        </xs:annotation>
+        <xs:restriction>
+            <xs:simpleType>
+                <xs:list itemType="xs:ENTITY"/>
+            </xs:simpleType>
+            <xs:minLength value="1" id="ENTITIES.minLength"/>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="NMTOKEN" id="NMTOKEN">
+        <xs:annotation>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKEN"/>
+        </xs:annotation>
+        <xs:restriction base="xs:token">
+            <xs:pattern value="\c+" id="NMTOKEN.pattern">
+                <xs:annotation>
+                    <xs:documentation source="http://www.w3.org/TR/REC-xml#NT-Nmtoken">
+                        pattern matches production 7 from the XML spec
+                    </xs:documentation>
+                </xs:annotation>
+            </xs:pattern>
+        </xs:restriction>
+    </xs:simpleType>
+    <xs:simpleType name="NMTOKENS" id="NMTOKENS">
+        <xs:annotation>
+            <xs:appinfo>
+                <hfp:hasFacet name="length"/>
+                <hfp:hasFacet name="minLength"/>
+                <hfp:hasFacet name="maxLength"/>
+                <hfp:hasFacet name="enumeration"/>
+                <hfp:hasFacet name="whiteSpace"/>
+                <hfp:hasProperty name="ordered" value="false"/>
+                <hfp:hasProperty name="bounded" value="false"/>
+                <hfp:hasProperty name="cardinality" value="countably infinite"/>
+                <hfp:hasProperty name="numeric" value="false"/>
+            </xs:appinfo>
+            <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NMTOKENS"/>
+        </xs:annotation>
+        <xs:restriction>
+            <xs:simpleType>
+                <xs:list itemType="xs:NMTOKEN"/>
+           

<TRUNCATED>

[02/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CommonUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CommonUtil.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CommonUtil.java
new file mode 100644
index 0000000..3e3b794
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CommonUtil.java
@@ -0,0 +1,620 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.util;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.registry.core.ActionConstants;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.AccessControlConstants;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.AuthorizationManager;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.DateFormat;
+import java.text.DateFormatSymbols;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.regex.Pattern;
+
+/**
+ * Common Utility methods for Stratos.
+ * Now this class has been growing with several util methods - Should refactor accordingly.
+ */
+public class CommonUtil {
+    private static final Log log = LogFactory.getLog(CommonUtil.class);
+    private static StratosConfiguration stratosConfig;
+    private static String eula;
+
+
+    private static final String ILLEGAL_CHARACTERS_FOR_EMAIL =
+            ".*[\\(\\)\\<\\>\\,\\;\\:\\\\\\\"\\[\\]].*";
+    private static final String EMAIL_FILTER_STRING = "^[^@]+@[^@.]+\\.[^@]*\\w\\w$";
+    private static Pattern emailFilterPattern = Pattern.compile(EMAIL_FILTER_STRING);
+    private static Pattern illegalCharactersPatternForEmail = Pattern
+            .compile(ILLEGAL_CHARACTERS_FOR_EMAIL);
+
+    public static StratosConfiguration getStratosConfig() {
+        return stratosConfig;
+    }
+
+    public static void setStratosConfig(StratosConfiguration stratosConfig) {
+        CommonUtil.stratosConfig = stratosConfig;
+    }
+
+    public static String getEula() {
+        return eula;
+    }
+
+    public static void setEula(String eula) {
+        CommonUtil.eula = eula;
+    }
+
+    /**
+     * Checks whether the email validation is mandatory from the configuration file.
+     *
+     * @return true, if the email validation is mandatory to login. Default is false.
+     */
+    public static boolean isEmailValidationMandatory() {
+        boolean isEmailValidationMandatory = false; //false by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailValidationMandatory = stratosConfig.getEmailValidationRequired();
+        }
+        return isEmailValidationMandatory;
+    }
+
+    /**
+     * Checks whether the email sending is enabled from the configuration file.
+     *
+     * @return true, if the email sending is disabled. By default, this is disabled, and tenant
+     * activation is done without any email sending.
+     */
+    public static boolean isTenantManagementEmailsDisabled() {
+        boolean isEmailsDisabled = true; //true by default.
+        if (stratosConfig != null) {   //make sure the configuration exists.
+            isEmailsDisabled = stratosConfig.isEmailsDisabled();
+        }
+        return isEmailsDisabled;
+    }
+
+    public static String getSuperAdminEmail() {
+        return stratosConfig.getSuperAdminEmail();
+    }
+
+    public static String getAdminUserName() {
+        return stratosConfig.getAdminUserName();
+    }
+    
+    public static String getAdminPassword() {
+        return stratosConfig.getAdminPassword();
+    }
+
+    public static boolean isTenantActivationModerated() {
+        return stratosConfig.isTenantActivationModerated();
+    }
+
+    public static boolean isChargedOnRegistration() {
+        return stratosConfig.isChargeOnRegistration();
+    }
+
+    /**
+     * Checks whether it is for the public cloud setup or Mars.
+     *
+     * @return true, if it is not for the private cloud setups. Default is true.
+     */
+    public static boolean isPublicCloudSetup() {
+        boolean isPublicCloudSetup = true;  // true by default.
+        if (stratosConfig != null) { //make sure the configuration exists.
+            isPublicCloudSetup = stratosConfig.isPublicCloudSetup();
+        }
+        return isPublicCloudSetup;
+    }
+
+    /**
+     * Gets the notification email address of the admin upon the tenant creation.
+     *
+     * @return notification email address for the tenant creations.
+     */
+    public static String getNotificationEmailAddress() {
+        String notificationEmailAddress = "";
+        if (stratosConfig != null) {
+            notificationEmailAddress = stratosConfig.getNotificationEmail();
+            try {
+                validateEmail(notificationEmailAddress);
+            } catch (Exception e) {
+                if (log.isWarnEnabled()) {
+                    log.warn("Invalid Email Address provided for tenant creation notification. " +
+                             "Please check whether the parameter NotificationEmail" +
+                             " is set properly in " +
+                             StratosConstants.STRATOS_CONF_FILE, e);
+                }
+                return "";
+            }
+        }
+        return notificationEmailAddress;
+    }
+
+    public static String getMonthString(Calendar calendar) {
+        int currentMonth = calendar.get(Calendar.MONTH);
+
+        String[] monthArr = new DateFormatSymbols().getMonths();
+        String month = monthArr[currentMonth];
+        return calendar.get(Calendar.YEAR) + "-" + month;
+    }
+
+    public static String getMonthString(int relativeMonth) {
+        Calendar newCalendar = Calendar.getInstance();
+        newCalendar.add(Calendar.MONTH, relativeMonth);
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+    public static Date getDateFromMonthString(String yearMonth) throws ParseException {
+        DateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MMM");
+        return yearMonthFormat.parse(yearMonth);
+    }
+
+    public static String getCurrentMonthString() {
+        Calendar newCalendar = Calendar.getInstance();
+
+        return CommonUtil.getMonthString(newCalendar);
+    }
+
+
+    public static void setAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            String everyoneRole = CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME;
+
+            accessControlAdmin.authorizeRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not set authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    public static void denyAnonAuthorization(String path, UserRealm userRealm)
+            throws RegistryException {
+        if (userRealm == null) {
+            return;
+        }
+
+        try {
+            AuthorizationManager accessControlAdmin = userRealm.getAuthorizationManager();
+            RealmConfiguration realmConfig;
+            try {
+                realmConfig = userRealm.getRealmConfiguration();
+            } catch (UserStoreException e) {
+                String msg = "Failed to retrieve realm configuration.";
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+
+            String everyoneRole = realmConfig.getEveryOneRoleName();
+
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.GET);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.PUT);
+            accessControlAdmin.denyRole(everyoneRole, path, ActionConstants.DELETE);
+            accessControlAdmin.denyRole(everyoneRole, path, AccessControlConstants.AUTHORIZE);
+
+        } catch (UserStoreException e) {
+            String msg = "Could not clear authorizations for the " + path + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg);
+        }
+    }
+
+    /**
+     * builds the OMElement from the given inputStream
+     *
+     * @param inputStream, given input - inputStream
+     * @return OMElement
+     * @throws Exception, if building OMElement from the inputStream failed.
+     */
+    public static OMElement buildOMElement(InputStream inputStream) throws Exception {
+        XMLStreamReader parser;
+        try {
+            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+        } catch (XMLStreamException e) {
+            String msg = "Error in initializing the parser to build the OMElement.";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // create the builder
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+        // get the root element (in this case the envelope)
+
+        return builder.getDocumentElement();
+    }
+
+
+    /**
+     * validates the email
+     *
+     * @param email - email address
+     * @throws Exception, if validation failed
+     */
+    public static void validateEmail(String email) throws Exception {
+        if (email == null) {
+            String msg = "Provided email value is null.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        email = email.trim();
+        if ("".equals(email)) {
+            String msg = "Provided email value is empty.";
+            log.warn(msg);
+            throw new Exception(msg);
+        }
+        if (illegalCharactersPatternForEmail.matcher(email).matches()) {
+            String msg = "Wrong characters in the email.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        if (!emailFilterPattern.matcher(email).matches()) {
+            String msg = "Invalid email address is provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * @param name     validate the name.
+     * @param variable entry name.
+     * @throws Exception if empty
+     */
+    public static void validateName(String name, String variable) throws Exception {
+        if (name.trim().equals("")) {
+            String msg = variable + " is not provided.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+    /**
+     * validates domain from the successkey
+     *
+     * @param governanceSystemRegistry - The governance system registry
+     * @param domain                   - tenant domain
+     * @param successKey               - successkey
+     * @return true, if successfully validated
+     * @throws RegistryException, if validation failed
+     */
+    public static boolean validateDomainFromSuccessKey(UserRegistry governanceSystemRegistry,
+                                                       String domain, String successKey)
+            throws RegistryException {
+        String domainValidatorInfoPath =
+                StratosConstants.DOMAIN_VALIDATOR_INFO_PATH + RegistryConstants.PATH_SEPARATOR +
+                domain + RegistryConstants.PATH_SEPARATOR +
+                StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+            String actualSuccessKey = resource.getProperty("successKey");
+            if (actualSuccessKey != null && successKey != null &&
+                actualSuccessKey.trim().equals(successKey.trim())) {
+                // the domain is correct
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns the configurations from the stratos configuration file.
+     *
+     * @return stratos configurations
+     */
+    public static StratosConfiguration loadStratosConfiguration() {
+        // gets the configuration file name from the StratosConstants.
+        String StratosConfigFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_CONF_FILE;
+        return loadStratosConfiguration(StratosConfigFileName);
+    }
+
+    /**
+     * Loads the given Stratos Configuration file.
+     *
+     * @param configFilename Name of the configuration file
+     * @return the stratos configuration data.
+     */
+    private static StratosConfiguration loadStratosConfiguration(String configFilename) {
+        StratosConfiguration config = new StratosConfiguration();
+        File configFile = new File(configFilename);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    if ("DisableTenantManagementEmails".equals(element.getLocalName())) {
+                        String disableEmails = element.getText();
+                        // by default, make the email validation mandatory.
+                        boolean isEmailsDisabled = true;
+                        if (disableEmails.trim().equalsIgnoreCase("false")) {
+                            isEmailsDisabled = false;
+                        }
+                        config.setEmailsDisabled(isEmailsDisabled);
+                    }
+                    // Checks whether Email Validation is mandatory to log in and use the registered
+                    // tenants.
+                    else if ("EmailValidationMandatoryForLogin".equals(element.getLocalName())) {
+                        String emailValidation = element.getText();
+                        //by default, make the email validation not mandatory.
+                        boolean isEmailValidationRequired = false;
+                        if (emailValidation.trim().equalsIgnoreCase("true")) {
+                            isEmailValidationRequired = true;
+                        }
+                        config.setEmailValidationRequired(isEmailValidationRequired);
+                    } else if ("ChargeOnRegistration".equals(element.getLocalName())) {
+                        String chargeOnRegistration = element.getText();
+                        boolean isChargedOnRegistration = false;
+                        if (chargeOnRegistration.trim().equalsIgnoreCase("true")) {
+                            isChargedOnRegistration = true;
+                        }
+                        config.setChargeOnRegistration(isChargedOnRegistration);
+                    } else if ("NotificationEmail".equals(element.getLocalName())) {
+                        config.setNotificationEmail(element.getText());
+                    } else if ("SuperAdminEmail".equals(element.getLocalName())) {
+                        config.setSuperAdminEmail(element.getText());
+                    } else if ("TenantActivationModerated".equals(element.getLocalName())){
+                        String isTenantActivationModerated = element.getText();
+                        boolean tenantActivationModerated = false;
+                        if (isTenantActivationModerated.trim().equalsIgnoreCase("true")) {
+                            tenantActivationModerated = true;
+                        }
+                        config.setTenantActivationModerated(tenantActivationModerated);
+                    }
+                    //Checks whether it is public cloud deployment.
+                    else if ("StratosPublicCloudSetup".equals(element.getLocalName())) {
+                        String cloudSetup = element.getText();
+                        //by default, make the email validation mandatory.
+                        boolean isStratosPublicCloudSetup = true;
+                        if (cloudSetup.trim().equalsIgnoreCase("false")) {
+                            isStratosPublicCloudSetup = false;
+                        }
+                        config.setPublicCloudSetup(isStratosPublicCloudSetup);
+                        //Setting the paypal url
+                    } else if ("PaypalUrl".equals(element.getLocalName())) {
+                        String paypalUrl = element.getText();
+                        config.setPaypalUrl(paypalUrl);
+                    } else if ("SkipSummaryGenerator".equals(element.getLocalName())) {
+                        String summaryGenerator = element.getText();
+                        boolean skipSummaryGenerator = false;
+                        if (summaryGenerator.trim().equalsIgnoreCase("true")) {
+                            skipSummaryGenerator = true;
+                        }
+                        config.setSkipSummaryGenerator(skipSummaryGenerator);
+                    }
+                    else if ("PaypalAPIUsername".equals(element.getLocalName())) {
+                        config.setPaypalAPIUsername(element.getText());
+                    } else if ("PaypalAPIPassword".equals(element.getLocalName())) {
+                        config.setPaypalAPIPassword(element.getText());
+                    } else if ("PaypalAPISignature".equals(element.getLocalName())) {
+                        config.setPaypalAPISignature(element.getText());
+                    }else if ("PaypalEnvironment".equals(element.getLocalName())){
+                        config.setPaypalEnvironment(element.getText());
+                    }else if("FinanceNotificationEmail".equals(element.getLocalName())){
+                        config.setFinanceNotificationEmail(element.getText());    
+                    }else if("UsagePlanUrl".equals(element.getLocalName())){
+                        config.setUsagePlanURL(element.getText());
+                    }else if("PaidJIRAUrl".equals(element.getLocalName())) {
+                        config.setPaidJIRAUrl(element.getText());
+                    }else if("PaidJIRAProject".equals(element.getLocalName())) {
+                        config.setPaidJIRAProject(element.getText());
+                    }else if("ForumUrl".equals(element.getLocalName())) {
+                        config.setForumUrl(element.getText());
+                    }else if("PaidUserGroup".equals(element.getLocalName())) {
+                        config.setPaidUserGroup(element.getText());
+                    }else if("NonpaidUserGroup".equals(element.getLocalName())) {
+                        config.setNonpaidUserGroup(element.getText());
+                    } else if("SupportInfoUrl".equals(element.getLocalName())) {
+                        config.setSupportInfoUrl(element.getText());
+                    }else if("IncidentCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentCustomFieldId(element.getText());
+                    } else if("IncidentImpactCustomFieldId".equals(element.getLocalName())) {
+                        config.setIncidentImpactCustomFieldId(element.getText());
+                    } else if ("GoogleAnalyticsURL".equals(element.getLocalName())) {
+                        config.setGoogleAnalyticsURL(element.getText());
+                    } else if("StratosEventListener".equals(element.getLocalName())) {
+                        populateEventListenerProperties(config, element);
+                    } else if ("managerServiceUrl".equals(element.getLocalName())) {
+                        config.setManagerServiceUrl(element.getText());
+                    } else if ("adminUserName".equals(element.getLocalName())) {
+                        config.setAdminUserName(element.getText());
+                    } else if ("adminPassword".equals(element.getLocalName())) {
+                        config.setAdminPassword(element.getText());
+                    } else if("SSOLoadingMessage".equals(element.getLocalName())){
+                        config.setSsoLoadingMessage(element.getText());
+                    }
+                }
+                return config;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Configurations File: " + configFilename + ".";
+                log.error(msg, e);
+                return config; //returns the default configurations, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the Configuration File " + configFilename);
+                    }
+                }
+            }
+        }
+        log.error("Unable to locate the stratos configurations file. " +
+                  "Default Settings will be used.");
+        return config; // return the default configuratiosn, if the file not found.
+    }
+    
+    
+    private static void populateEventListenerProperties(StratosConfiguration config,
+                                                        OMElement element) throws RegistryException {
+        config.setStratosEventListenerName(element.getAttributeValue(new QName("class")));
+        Iterator<?> ite =
+                          element.getChildrenWithName(new QName("Property"));
+        while (ite.hasNext()) {
+            OMElement propElem = (OMElement) ite.next();
+            String propName = propElem.getAttributeValue(new QName("name"));
+            String propValue = propElem.getText();
+            config.setStratosEventListenerProperty(propName, propValue);
+        }
+    }
+
+    /**
+     * Loading the EULA.
+     * ultimately we shall be loading the eula from the web page itself.
+     * But loading from file should be there to customize the EULA based on the private deployments,
+     * etc.
+     *
+     * @return eula
+     */
+    public static String loadTermsOfUsage() {
+        // currently loads from the file; gets the eula file name from the StratosConstants.
+        String StratosEULAFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                StratosConstants.STRATOS_EULA;
+        return loadTermsOfUsage(StratosEULAFileName);
+    }
+
+    private static String loadTermsOfUsage(String eulaFile) {
+        String eula = StratosConstants.STRATOS_EULA_DEFAULT_TEXT;
+        File configFile = new File(eulaFile);
+        if (configFile.exists()) {
+            FileInputStream inputStream = null;
+            try {
+                inputStream = new FileInputStream(configFile);
+                XMLStreamReader parser =
+                        XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+                StAXOMBuilder builder = new StAXOMBuilder(parser);
+                OMElement documentElement = builder.getDocumentElement();
+                Iterator it = documentElement.getChildElements();
+                while (it.hasNext()) {
+                    OMElement element = (OMElement) it.next();
+
+                    //Checks whether Email Validation is mandatory for tenant registration complete.
+                    if ("EULA".equalsIgnoreCase(element.getLocalName())) {
+                        eula = element.getText();
+                    }
+                }
+                return eula;
+            } catch (Exception e) {
+                String msg = "Error in loading Stratos Terms and Conditions File.";
+                log.error(msg, e);
+                return eula; //returns the default text, if the file could not be loaded.
+            } finally {
+                if (inputStream != null) {
+                    try {
+                        inputStream.close();
+                    } catch (IOException e) {
+                        log.error("Could not close the EULA File " + eulaFile);
+                    }
+                }
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Unable to locate the stratos EULA file. Default value will be used.");
+        }
+        return eula; // return the default, if the file not found.
+    }
+
+
+    /**
+     * method to check whether a domain name is available to register given a domain name
+     * @param tenantDomain, domain name
+     * @return true, if the domain is available to register
+     * @throws Exception, if checking the existence of the tenant is failed.
+     */
+    public static boolean isDomainNameAvailable(String tenantDomain) throws Exception {
+
+        TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
+          // The registry reserved words are checked first.
+          if (tenantDomain.equals("atom") || tenantDomain.equals("registry")
+                  || tenantDomain.equals("resource")) {
+              String msg = "You can not use a registry reserved word:" + tenantDomain +
+                           ":as a tenant domain. Please choose a different one.";
+              log.error(msg);
+              throw new Exception(msg);
+          }
+
+          int tenantId;
+          try {
+              tenantId = tenantManager.getTenantId(tenantDomain);
+          } catch (UserStoreException e) {
+              String msg = "Error in getting the tenant id for the given domain  " +
+                           tenantDomain + ".";
+              log.error(msg);
+              throw new Exception(msg, e);
+          }
+
+          // check a tenant with same domain exist.
+          if ((tenantId != MultitenantConstants.INVALID_TENANT_ID && tenantId != MultitenantConstants.SUPER_TENANT_ID) ||
+                  tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+              String msg =
+                           "A tenant with same domain already exist. " +
+                                   "Please use a different domain name. tenant domain: " +
+                                   tenantDomain + ".";
+              log.info(msg);
+              return false;
+          }
+          return true;
+      }
+}
+
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/MeteringAccessValidationUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/MeteringAccessValidationUtils.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/MeteringAccessValidationUtils.java
new file mode 100644
index 0000000..7f9e8c3
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/MeteringAccessValidationUtils.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.util;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+public class MeteringAccessValidationUtils {
+
+	public static final String ERROR_MSG_PROPERTY_KEY_POST_FIX = "error_msg";
+	public static final String IS_BLOCKED_PROPERTY_KEY_POST_FIX = "is_blocked";
+
+	public static String generateIsBlockedPropertyKey(String action) {
+		return action + "_" + IS_BLOCKED_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static String generateErrorMsgPropertyKey(String action) {
+		return action + "_" + ERROR_MSG_PROPERTY_KEY_POST_FIX;
+	}
+
+	public static Set<String> getAvailableActions(Properties properties) {
+		Set propertyKeys = properties.keySet();
+		Set<String> actions = new HashSet<String>();
+		for (Object propertyKeyObj : propertyKeys) {
+			String propertyKey = (String) propertyKeyObj;
+			if (propertyKey.endsWith(IS_BLOCKED_PROPERTY_KEY_POST_FIX)) {
+			    // -1 for the length of the '_'
+				String action =
+				        propertyKey.substring(0, propertyKey.length() -
+				                IS_BLOCKED_PROPERTY_KEY_POST_FIX.length() - 1);
+				actions.add(action);
+			}
+		}
+		return actions;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/StratosConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/StratosConfiguration.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/StratosConfiguration.java
new file mode 100644
index 0000000..611158f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/StratosConfiguration.java
@@ -0,0 +1,319 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.stratos.common.util;
+
+import java.lang.String;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Class for the stratos specific parameters configuration
+ */
+public class StratosConfiguration {
+
+    // By default email sending is disabled. Changed according to the configuration file.
+    private boolean emailsDisabled = true;
+
+    private boolean emailValidationRequired = false;
+    private boolean isPublicCloudSetup = true;
+    private boolean isTenantActivationModerated = false;
+    private boolean chargeOnRegistration = false;
+    private String SuperAdminEmail = "";
+    private String paypalUrl = "";
+    private String paypalAPIUsername = "";
+    private String paypalAPIPassword = "";
+    private String paypalAPISignature = "";
+    private String paypalEnvironment="";
+    private String usagePlanURL = "";
+    private String paidJIRAUrl = "";
+    private String paidJIRAProject = "";
+    private String forumUrl = "";
+    private String paidUserGroup = "";
+    private String nonpaidUserGroup = "";
+    private String supportInfoUrl = "";
+    private String incidentCustomFieldId = ""; // todo this is a custom field id of JIRA, this need to be dynamically get in jira reporting component
+    private String incidentImpactCustomFieldId = "";
+    private String stratosEventListenerName ="";
+    private Map<String, String> stratosEventProperties = new HashMap<String, String>();
+    private String googleAnalyticsURL;
+    private String managerServiceUrl = "";
+    private String adminUserName = "";
+    private String adminPassword = "";
+    private String ssoLoadingMessage="";
+
+    /**
+     * @return Stratos Manager service url
+     */
+    public String getManagerServiceUrl() {
+        return managerServiceUrl;
+    }
+
+    public void setManagerServiceUrl(String managerServiceUrl) {
+        this.managerServiceUrl = managerServiceUrl;
+    }
+
+    /**
+     * @return Super admin User name
+     */
+    public String getAdminUserName() {
+        return adminUserName;
+    }
+
+    public void setAdminUserName(String adminUserName) {
+        this.adminUserName = adminUserName;
+    }
+
+    /**
+     * @return super admin password
+     */
+    public String getAdminPassword() {
+        return adminPassword;
+    }
+
+    public void setAdminPassword(String adminPassword) {
+        this.adminPassword = adminPassword;
+    }
+
+    //This parameter used to skip usage summary generator
+     private boolean skipSummaryGenerator = false;
+
+    public boolean isSkipSummaryGenerator() {
+        return skipSummaryGenerator;
+    }
+
+    public void setSkipSummaryGenerator(boolean skipSummaryGenerator) {
+        this.skipSummaryGenerator = skipSummaryGenerator;
+    }
+    //This is the url that we pointed users when they need to aware about usage plans
+
+    public String getUsagePlanURL() {
+        return usagePlanURL;
+    }
+
+    public void setUsagePlanURL(String usagePlanURL) {
+        this.usagePlanURL = usagePlanURL;
+    }
+
+    //Email address for general notifications
+    private String notificationEmail = "";
+    //Email address for finance related notifications
+    private String financeNotificationEmail = "";
+
+    public boolean isTenantActivationModerated() {
+        return isTenantActivationModerated;
+    }
+
+    public void setTenantActivationModerated(boolean tenantActivationModerated) {
+        isTenantActivationModerated = tenantActivationModerated;
+    }
+
+    public String getSuperAdminEmail() {
+        return SuperAdminEmail;
+    }
+
+    public void setSuperAdminEmail(String superAdminEmail) {
+        SuperAdminEmail = superAdminEmail;
+    }
+
+    public boolean getEmailValidationRequired() {
+        return emailValidationRequired;
+    }
+
+    public String getPaypalUrl() {
+        return paypalUrl;
+    }
+
+    public void setPaypalUrl(String paypalUrl) {
+        this.paypalUrl = paypalUrl;
+    }
+
+    public void setEmailValidationRequired(boolean emailValidationRequired) {
+        this.emailValidationRequired = emailValidationRequired;
+    }
+
+    public boolean isPublicCloudSetup() {
+        return isPublicCloudSetup;
+    }
+
+    public void setPublicCloudSetup(boolean publicCloudSetup) {
+        isPublicCloudSetup = publicCloudSetup;
+    }
+
+    public String getNotificationEmail() {
+        return notificationEmail;
+    }
+
+    public void setNotificationEmail(String notificationEmail) {
+        this.notificationEmail = notificationEmail;
+    }
+
+    public String getPaypalAPIUsername() {
+        return paypalAPIUsername;
+    }
+
+    public void setPaypalAPIUsername(String paypalAPIUsername) {
+        this.paypalAPIUsername = paypalAPIUsername;
+    }
+
+    public String getPaypalAPIPassword() {
+        return paypalAPIPassword;
+    }
+
+    public void setPaypalAPIPassword(String paypalAPIPassword) {
+        this.paypalAPIPassword = paypalAPIPassword;
+    }
+
+    public String getPaypalAPISignature() {
+        return paypalAPISignature;
+    }
+
+    public void setPaypalAPISignature(String paypalAPISignature) {
+        this.paypalAPISignature = paypalAPISignature;
+    }
+
+    public String getFinanceNotificationEmail() {
+        return financeNotificationEmail;
+    }
+
+    public void setFinanceNotificationEmail(String financeNotificationEmail) {
+        this.financeNotificationEmail = financeNotificationEmail;
+    }
+
+    public String getPaidJIRAUrl() {
+        return paidJIRAUrl;
+    }
+
+    public void setPaidJIRAUrl(String paidJIRAUrl) {
+        this.paidJIRAUrl = paidJIRAUrl;
+    }
+
+    public String getPaidJIRAProject() {
+        return paidJIRAProject;
+    }
+
+    public void setPaidJIRAProject(String paidJIRAProject) {
+        this.paidJIRAProject = paidJIRAProject;
+    }
+
+    public String getForumUrl() {
+        return forumUrl;
+    }
+
+    public void setForumUrl(String forumUrl) {
+        this.forumUrl = forumUrl;
+    }
+
+    public String getPaidUserGroup() {
+        return paidUserGroup;
+    }
+
+    public void setPaidUserGroup(String paidUserGroup) {
+        this.paidUserGroup = paidUserGroup;
+    }
+
+    public String getNonpaidUserGroup() {
+        return nonpaidUserGroup;
+    }
+
+    public void setNonpaidUserGroup(String nonpaidUserGroup) {
+        this.nonpaidUserGroup = nonpaidUserGroup;
+    }
+
+    public String getSupportInfoUrl() {
+        return supportInfoUrl;
+    }
+
+    public void setSupportInfoUrl(String supportInfoUrl) {
+        this.supportInfoUrl = supportInfoUrl;
+    }
+
+    public String getIncidentCustomFieldId() {
+        return incidentCustomFieldId;
+    }
+
+    public void setIncidentCustomFieldId(String incidentCustomFieldId) {
+        this.incidentCustomFieldId = incidentCustomFieldId;
+    }
+
+    public String getIncidentImpactCustomFieldId() {
+        return incidentImpactCustomFieldId;
+    }
+
+    public void setIncidentImpactCustomFieldId(String incidentImpactCustomFieldId) {
+        this.incidentImpactCustomFieldId = incidentImpactCustomFieldId;
+    }
+    
+    public String getStratosEventListenerName() {
+        return stratosEventListenerName;
+    }
+
+    public void setStratosEventListenerName(String stratosEventListenerName) {
+        this.stratosEventListenerName = stratosEventListenerName;
+    }
+
+    public String getStratosEventListenerPropertyValue(String key) {
+        return stratosEventProperties.get(key);
+    }
+
+    public void setStratosEventListenerProperty(String key, String value) {
+        stratosEventProperties.put(key, value);
+    }
+
+    public String getPaypalEnvironment() {
+        return paypalEnvironment;
+    }
+
+    public void setPaypalEnvironment(String paypalEnvironment) {
+        this.paypalEnvironment = paypalEnvironment;
+    }
+
+    public String getGoogleAnalyticsURL() {
+        return googleAnalyticsURL;
+    }
+
+    public void setGoogleAnalyticsURL(String googleAnalyticsURL) {
+        this.googleAnalyticsURL = googleAnalyticsURL;
+    }
+
+    public boolean isEmailsDisabled() {
+        return emailsDisabled;
+    }
+
+    public void setEmailsDisabled(boolean emailsDisabled) {
+        this.emailsDisabled = emailsDisabled;
+    }
+
+    public boolean isChargeOnRegistration() {
+        return chargeOnRegistration;
+    }
+
+    public void setChargeOnRegistration(boolean chargeOnRegistration) {
+        this.chargeOnRegistration = chargeOnRegistration;
+    }
+
+    public String getSsoLoadingMessage() {
+        return ssoLoadingMessage;
+    }
+
+    public void setSsoLoadingMessage(String ssoLoadingMessage) {
+        this.ssoLoadingMessage = ssoLoadingMessage;
+    }
+    
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..89198d2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+
+    <service name="PackageInfoService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.stratos.common.services.PackageInfoService
+        </parameter>
+        <parameter name="adminService" locked="ture">false</parameter>
+    </service>
+
+    <parameter name="hiddenService" locked="ture">true</parameter>
+    
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/cloud-services-desc.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/cloud-services-desc.xml b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/cloud-services-desc.xml
new file mode 100644
index 0000000..15fb4b9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/resources/cloud-services-desc.xml
@@ -0,0 +1,109 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<cloudServices xmlns="http://wso2.com/carbon/cloud/mgt/services">
+    <cloudService name="WSO2 Stratos Manager">
+    </cloudService>
+    <cloudService name="WSO2 Enterprise Service Bus" default="true">
+      <label>Enterprise Service Bus</label>
+      <link>https://esb.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/esb.gif
+      </icon>
+      <description>Enterprise Service Bus in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Application Server" default="true">
+        <label>Application Server</label>
+        <link>https://appserver.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/appserver.gif
+        </icon>
+        <description>Application Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Data Services Server" default="true">
+      <label>Data Services Server</label>
+      <link>https://dss.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/ds.gif
+      </icon>
+      <description>Data Services Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Governance" default="true">
+        <label>Governance</label>
+        <link>https://governance.stratoslive.wso2.com</link>
+        <description>Governance in the cloud.</description>
+        <icon>
+            https://localhost:9443/cloud-services-icons/governance.gif
+        </icon>
+    </cloudService>
+    <cloudService name="WSO2 Identity" default="true">
+        <label>Identity</label>
+        <link>https://identity.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/identity.gif
+        </icon>
+        <description>Identity in the cloud.</description>
+    </cloudService>
+	<cloudService name="WSO2 Business Activity Monitor" default="true">
+        <label>Business Activity Monitor</label>
+        <link>https://bam.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/bam.gif
+        </icon>
+        <description>Business Activity Monitor in the cloud.</description>
+	</cloudService>
+    <cloudService name="WSO2 Business Process Server" default="true">
+      <label>Business Process Server</label>
+      <link>https://bps.stratoslive.wso2.com</link>
+      <icon>
+        https://localhost:9443/cloud-services-icons/bps.gif
+      </icon>
+      <description>Business Process Server in the cloud.</description>
+    </cloudService>
+	<cloudService name="WSO2 Business Rule Server" default="true">
+        <label>Business Rule Server</label>
+        <link>https://brs.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/brs.gif
+        </icon>
+        <description>Business Rule Server in the cloud.</description>
+	</cloudService>
+	<cloudService name="WSO2 Mashup Server" default="true">
+        <label>Mashup Server</label>
+        <link>https://mashup.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/mashup.gif
+        </icon>
+        <description>Mashup Server in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Gadgets" default="true">
+        <label>Gadgets</label>
+        <link>https://gadget.stratoslive.wso2.com</link>
+        <icon>
+            https://localhost:9443/cloud-services-icons/gadget.gif
+        </icon>
+        <description>Gadgets in the cloud.</description>
+    </cloudService>
+    <cloudService name="WSO2 Cloud Services Gateway" default="true">
+        <label>Cloud Gateway</label>
+	<link>https://csg.stratoslive.wso2.com</link>
+	<icon>
+            https://localhost:9443/cloud-services-icons/csg.gif
+	</icon>
+	<description>WSO2 Cloud Services Gateway in the cloud.</description>
+    </cloudService>
+</cloudServices>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/test/java/org/wso2/carbon/common/test/CommonTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/test/java/org/wso2/carbon/common/test/CommonTest.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/test/java/org/wso2/carbon/common/test/CommonTest.java
new file mode 100644
index 0000000..aca6d41
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/test/java/org/wso2/carbon/common/test/CommonTest.java
@@ -0,0 +1,48 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.common.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+
+public class CommonTest extends TestCase {
+    public void testEmailValidation() throws Exception {
+        try {
+            CommonUtil.validateEmail("damn@right.com");
+            assertTrue(true);
+        } catch (Exception e) {
+            assertTrue(false);
+        }
+
+        try {
+            CommonUtil.validateEmail("damn@right].com");
+            assertTrue(false);
+        } catch (Exception e) {
+            assertTrue(true);
+            assertEquals("Wrong characters in the email.", e.getMessage());
+        }
+
+        try {
+            CommonUtil.validateEmail("damn@right@wrong.com");
+            assertTrue(false);
+        } catch (Exception e) {
+            assertTrue(true);
+            assertEquals("Invalid email address is provided.", e.getMessage());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/pom.xml b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/pom.xml
new file mode 100644
index 0000000..cff9c0a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/pom.xml
@@ -0,0 +1,87 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.stratos.common</artifactId>
+    <version>2.1.1</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Common</name>
+
+    <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.wso2.carbon.stratos.common.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.user.core.*,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+            <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+           <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.mgt</artifactId>
+            <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+             <groupId>junit</groupId>
+             <artifactId>junit</artifactId>
+             <scope>test</scope>
+         </dependency>        
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
new file mode 100644
index 0000000..e2bff75
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
@@ -0,0 +1,24 @@
+package org.wso2.carbon.stratos.common;
+
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.Tenant;
+
+/**
+ * The OSGI service interface that enables tenant related billing actions.
+ */
+public interface TenantBillingService {
+    
+    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException;
+    
+    public String getActiveUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException;
+    
+    public void activateUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException;
+
+    public void deleteBillingData(int tenantId) throws StratosException;
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
new file mode 100755
index 0000000..8470a39
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
@@ -0,0 +1,137 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.stratos.common.beans;
+
+import java.util.Calendar;
+
+/**
+ * Bean class for Tenant Information
+ */
+public class TenantInfoBean {
+
+    private String admin; //admin's user name
+    private String firstname;
+    private String lastname;
+    private String adminPassword;
+    private String tenantDomain;
+    private int tenantId;
+    private String email;
+    private boolean active;
+    private String successKey;
+    Calendar createdDate;
+    private String originatedService;
+    private String usagePlan;
+
+    public String getFirstname() {
+        return firstname;
+    }
+
+    public void setFirstname(String firstname) {
+        this.firstname = firstname;
+    }
+
+    public String getLastname() {
+        return lastname;
+    }
+
+    public void setLastname(String lastname) {
+        this.lastname = lastname;
+    }
+
+    public String getEmail() {
+
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public String getTenantDomain() {
+        return tenantDomain;
+    }
+
+    public void setTenantDomain(String tenantDomain) {
+        this.tenantDomain = tenantDomain;
+    }
+
+    public String getAdmin() {
+        return admin;
+    }
+
+    public void setAdmin(String admin) {
+        this.admin = admin;
+    }
+
+    public String getAdminPassword() {
+        return adminPassword;
+    }
+
+    public void setAdminPassword(String adminPassword) {
+        this.adminPassword = adminPassword;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+    public String getSuccessKey() {
+        return successKey;
+    }
+
+    public void setSuccessKey(String successKey) {
+        this.successKey = successKey;
+    }
+
+    public Calendar getCreatedDate() {
+        return createdDate;
+    }
+
+    public void setCreatedDate(Calendar createdDate) {
+        this.createdDate = createdDate;
+    }
+
+    public String getOriginatedService() {
+        return originatedService;
+    }
+
+    public void setOriginatedService(String originatedService) {
+        this.originatedService = originatedService;
+    }
+
+    public String getUsagePlan() {
+        return usagePlan;
+    }
+
+    public void setUsagePlan(String usagePlan) {
+        this.usagePlan = usagePlan;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
new file mode 100644
index 0000000..a776bf2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class CloudServiceConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+
+    private static final String NAME_ATTR_NAME = "name";
+    private static final String DEFAULT_ATTR_NAME = "default";
+    private static final String LABEL_ELEMENT_NAME = "label";
+    private static final String LINK_ELEMENT_NAME = "link";
+    private static final String ICON_ELEMENT_NAME = "icon";
+    private static final String DESCRIPTION_ELEMENT_NAME = "description";
+    private static final String PERMISSIONS_ELEMENT_NAME = "permissions";
+    private static final String PERMISSION_ELEMENT_NAME = "permission";
+    private static final String PRODUCT_PAGE_URL_ELEMENT_NAME = "productPageURL";
+
+    private String name;
+    private String label;
+    private String link;
+    private String icon;
+    private String description;
+    private List<PermissionConfig> permissionConfigs;
+    boolean defaultActive;
+    private String productPageURL;
+
+    public CloudServiceConfig(OMElement configEle) {
+        permissionConfigs = new ArrayList<PermissionConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator cloudServiceChildIt = configEle.getChildElements();
+        name = configEle.getAttributeValue(new QName(null, NAME_ATTR_NAME));
+        defaultActive = "true".equals(configEle.
+                getAttributeValue(new QName(null, DEFAULT_ATTR_NAME)));
+        while (cloudServiceChildIt.hasNext()) {
+            Object cloudServiceChildObj = cloudServiceChildIt.next();
+            if (!(cloudServiceChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement cloudServiceChildEle = (OMElement) cloudServiceChildObj;
+            if (new QName(CONFIG_NS, LABEL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                label = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, ICON_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                icon = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, LINK_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                link = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PRODUCT_PAGE_URL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                productPageURL = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, DESCRIPTION_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                description = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PERMISSIONS_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                Iterator permissionChildIt = cloudServiceChildEle.getChildElements();
+                while (permissionChildIt.hasNext()) {
+                    Object permissionChildObj = permissionChildIt.next();
+                    if (!(permissionChildObj instanceof OMElement)) {
+                        continue;
+                    }
+                    OMElement permissionChildEle = (OMElement) permissionChildObj;
+
+                    if (new QName(CONFIG_NS, PERMISSION_ELEMENT_NAME, "").
+                            equals(permissionChildEle.getQName())) {
+                        PermissionConfig permissionConfig =
+                                new PermissionConfig(permissionChildEle);
+                        permissionConfigs.add(permissionConfig);
+                    }
+                }
+            }
+
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getLabel() {
+        return label;
+    }
+
+    public void setLabel(String label) {
+        this.label = label;
+    }
+
+    public String getLink() {
+        return link;
+    }
+
+    public void setLink(String link) {
+        this.link = link;
+    }
+
+    public String getIcon() {
+        return icon;
+    }
+
+    public void setIcon(String icon) {
+        this.icon = icon;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<PermissionConfig> getPermissionConfigs() {
+        return permissionConfigs;
+    }
+
+    public void setPermissionConfigs(List<PermissionConfig> permissionConfigs) {
+        this.permissionConfigs = permissionConfigs;
+    }
+
+    public boolean isDefaultActive() {
+        return defaultActive;
+    }
+
+    public void setDefaultActive(boolean defaultActive) {
+        this.defaultActive = defaultActive;
+    }
+
+    public String getProductPageURL() {
+        return productPageURL;
+    }
+
+    public void setProductPageURL(String productPageURL) {
+        this.productPageURL = productPageURL;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
new file mode 100644
index 0000000..b01a385
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
@@ -0,0 +1,48 @@
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+public class CloudServiceConfigParser {
+
+    private static Log log = LogFactory.getLog(CloudServiceConfigParser.class);
+
+    private static class SynchronizingClass {
+    }
+
+    private static final SynchronizingClass loadlock = new SynchronizingClass();
+
+    private static CloudServicesDescConfig cloudServicesDescConfig = null;
+
+    private static final String CONFIG_FILENAME = "cloud-services-desc.xml";
+
+    public static CloudServicesDescConfig loadCloudServicesConfiguration() throws Exception {
+        if (cloudServicesDescConfig != null) {
+            return cloudServicesDescConfig;
+        }
+
+        synchronized (loadlock) {
+            if (cloudServicesDescConfig == null) {
+                try {
+                    String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                            StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILENAME;
+                    OMElement configElement = CommonUtil.buildOMElement(new FileInputStream(configFileName));
+                    cloudServicesDescConfig = new CloudServicesDescConfig(configElement);
+                } catch (Exception e) {
+                    String msg = "Error in building the cloud service configuration.";
+                    log.error(msg, e);
+                    throw new Exception(msg, e);
+                }
+            }
+        }
+        return cloudServicesDescConfig;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
new file mode 100644
index 0000000..27d3f9e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.namespace.QName;
+import java.util.*;
+
+public class CloudServicesDescConfig {
+    private static final Log log = LogFactory.getLog(CloudServicesDescConfig.class);
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String CLOUD_SERVICE_ELEMENT_NAME = "cloudService";
+
+    Map<String, CloudServiceConfig> cloudServiceConfigs;
+
+    public CloudServicesDescConfig(OMElement configEle) {
+        // as the cloud service configs are kept in an order, we use an ordered map.
+        cloudServiceConfigs = new LinkedHashMap<String, CloudServiceConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, CLOUD_SERVICE_ELEMENT_NAME, "").
+                    equals(configChildEle.getQName())) {
+                CloudServiceConfig cloudServiceConfig = new CloudServiceConfig(configChildEle);
+                String name = cloudServiceConfig.getName();
+                cloudServiceConfigs.put(name, cloudServiceConfig);
+            }
+        }
+    }
+
+    public Map<String, CloudServiceConfig> getCloudServiceConfigs() {
+        return cloudServiceConfigs;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
new file mode 100644
index 0000000..5171019
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.Iterator;
+
+public class PermissionConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String PATH = "path";
+    private static final String NAME = "name";
+    String name;
+    String path;
+
+    public PermissionConfig(OMElement configEle) {
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, NAME, "").
+                    equals(configChildEle.getQName())) {
+                name = configChildEle.getText();
+            } else if (new QName(CONFIG_NS, PATH, "").
+                    equals(configChildEle.getQName())) {
+                path = configChildEle.getText();
+            }
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
new file mode 100644
index 0000000..bbc3dd9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
@@ -0,0 +1,143 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.common.constants;
+
+import java.io.File;
+
+public class StratosConstants {
+
+    public static final String CLOUD_SERVICE_IS_ACTIVE_PROP_KEY = "active";
+
+    public static final String CLOUD_SERVICE_INFO_STORE_PATH =
+            "/repository/components/org.wso2.stratos/cloud-manager/cloud-services";
+
+    public static final String TENANT_USER_VALIDATION_STORE_PATH =
+            "/repository/components/org.wso2.carbon.validations";
+    public static final String ADMIN_EMAIL_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.email-confirmation-flag";
+    public static final String TENANT_DOMAIN_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.domain-confirmation-flag";
+
+    public static final String DOMAIN_VALIDATOR_INFO_PATH =
+            "/repository/components/org.wso2.carbon.domain-validator-info";
+
+    public static final String TENANT_CREATION_THEME_PAGE_TOKEN =
+            "/repository/components/org.wso2.carbon.theme-page-token";
+
+    public static final String TENANT_PACKAGE_INFO_PATH =
+            "/repository/components/org.wso2.carbon.package-info";
+
+    public static final String ALL_THEMES_PATH =
+            "/repository/components/org.wso2.carbon.all-themes";
+
+    public static final String THROTTLING_RULES_PATH =
+            "/repository/components/org.wso2.carbon.throttling-rules";
+
+    public static final String ORIGINATED_SERVICE_PATH =
+            "/repository/components/org.wso2.carbon.originated-service";
+
+    public static final String PATH_SEPARATOR = "/";
+
+    public static final String CLOUD_SERVICE_ICONS_STORE_PATH =
+            "/repository/components/org.wso2.carbon.cloud-manager/" +
+                    "cloud-services-icons";
+
+    public static final String VALIDATION_KEY_RESOURCE_NAME = "validation-key";
+    public static final String INCOMING_PATH_DIR = "incoming";
+    public static final String OUTGOING_PATH_DIR = "outgoing";
+    public static final String MULTITENANCY_SCHEDULED_TASK_ID = "multitenancyScheduledTask";
+    public static final String MULTITENANCY_VIEWING_TASK_ID = "multitenancyViewingTask";
+
+    public static final String INVALID_TENANT = "invalidTenant";
+    public static final String INACTIVE_TENANT = "inactiveTenant";
+    public static final String ACTIVE_TENANT = "activeTenant";
+    public static final String IS_EMAIL_VALIDATED = "isEmailValidated";
+    public static final String IS_CREDENTIALS_ALREADY_RESET = "isCredentialsReset";
+    public static final String TENANT_ADMIN = "tenantAdminUsername";
+
+    public static final String CLOUD_MANAGER_SERVICE = "WSO2 Stratos Manager";
+    public static final String CLOUD_IDENTITY_SERVICE = "WSO2 Stratos Identity";
+    public static final String CLOUD_GOVERNANCE_SERVICE = "WSO2 Stratos Governance";
+    public static final String CLOUD_ESB_SERVICE = "WSO2 Stratos Enterprise Service Bus";
+
+    // keystore mgt related Constants
+    public static final String TENANT_KS = "/repository/security/key-stores/";
+    public static final String TENANT_PUB_KEY = "/repository/security/pub-key";
+    public static final String PROP_TENANT_KS_TYPE = "key-store-type";
+    public static final String PROP_TENANT_KS_PASSWD = "key-store-password";
+    public static final String PROP_TENANT_KS_PRIV_KEY_PASSWD = "priv-key-password";
+    public static final String PROP_TENANT_KS_ALIAS = "alias";
+
+    // constants related to redirection
+
+    public static final String UNVERIFIED_ACCOUNT_DOMAIN_SUFFIX = "-unverified";
+    public static final String TENANT_SPECIFIC_URL_RESOLVED = "tenant-sepcific-url-resolved";
+    public static final String SUFFIXED_UNVERIFIED_SESSION_FLAG = "temp-suffixed-unverified";
+
+    // metering constants
+    public static final String THROTTLING_ALL_ACTION = "all_actions";
+    public static final String THROTTLING_IN_DATA_ACTION = "in_data_action"; //this covers registry capacity + registry bandwidth
+    public static final String THROTTLING_OUT_DATA_ACTION = "out_data_action"; //this covers registry bandwidth
+    public static final String THROTTLING_ADD_USER_ACTION = "add_user_action";
+    public static final String THROTTLING_SERVICE_IN_BANDWIDTH_ACTION = "service_in_bandwith_action";
+    public static final String THROTTLING_SERVICE_OUT_BANDWIDTH_ACTION = "service_out_bandwith_action";
+    public static final String THROTTLING_WEBAPP_IN_BANDWIDTH_ACTION = "webapp_in_bandwith_action";
+    public static final String THROTTLING_WEBAPP_OUT_BANDWIDTH_ACTION = "webapp_out_bandwith_action";
+    public static final String THROTTLING_SERVICE_REQUEST_ACTION = "service_request_action";
+    public static final String THROTTLING_SERVICE_RESPONSE_ACTION = "service_response_action";
+
+    // the session attribute to keep track whether the registry action validated
+    // and the usage persisted
+    public static final String REGISTRY_ACTION_VALIDATED_SESSION_ATTR = "registryActionValidated";
+    public static final String REGISTRY_USAGE_PERSISTED_SESSION_ATTR = "usagePersited";
+
+    // Metering servlet attributes
+    public static final String SERVICE_NAME_SERVLET_ATTR = "meteringServiceName";
+    public static final String TENANT_ID_SERVLET_ATTR = "tenantId";
+    public static final String ADMIN_SERVICE_SERVLET_ATTR = "adminService";
+
+    // * as a Service impl related constants
+    public static final String ORIGINATED_SERVICE = "originatedService";
+
+    // Configuration file name
+    public static final String STRATOS_CONF_FILE = "stratos.xml";
+    //public static final String STRATOS_CONF_LOC = "repository/conf/";
+    //public static final String STRATOS_CONF_FILE_WITH_PATH = STRATOS_CONF_LOC + STRATOS_CONF_FILE;
+
+    // EULA location
+    public static final String STRATOS_EULA = "eula.xml";
+
+    // EULA default text.
+    public static final String STRATOS_EULA_DEFAULT_TEXT =
+            "Please refer to: " + StratosConstants.STRATOS_TERMS_OF_USAGE +
+                    " for terms and usage and " + StratosConstants.STRATOS_PRIVACY_POLICY +
+                    " for privacy policy of WSO2 Stratos.";
+
+    // Web location of Terms of Usage and privacy policy
+    public static final String STRATOS_TERMS_OF_USAGE =
+            "http://wso2.com/cloud/services/terms-of-use/";
+    public static final String STRATOS_PRIVACY_POLICY =
+            "http://wso2.com/cloud/services/privacy-policy/";
+    public static final String MULTITENANCY_FREE_PLAN = "Demo";
+    public static final String MULTITENANCY_SMALL_PLAN = "SMB";
+    public static final String MULTITENANCY_MEDIUM_PLAN = "Professional";
+    public static final String MULTITENANCY_LARGE_PLAN = "Enterprise";
+    public static final String EMAIL_CONFIG= "email";
+    public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
new file mode 100644
index 0000000..e2c521b
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.1/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.constants;
+
+public class UsageConstants {
+    final public static String ANY_DURATION = "anyDuration";
+
+    public static final String SYSTEM_METERING_PATH =
+            "/repository/components/org.wso2.carbon.system-metering";
+
+    public static final String CUSTOM_METERING_PATH =
+        "/repository/components/org.wso2.carbon.system-metering";
+
+    // the measurements
+    final public static String CAPACITY_USAGE = "capacity-usage";
+    
+    final public static String SERVICE_REQUEST_COUNT = "serviceRequestCount";
+    final public static String SERVICE_RESPONSE_COUNT = "serviceResponseCount";
+    final public static String SERVICE_FAULT_COUNT = "serviceFaultCount";
+    
+    public static final String BANDWIDTH_KEY_PATTERN = "%Bandwidth%";
+    public static final String REGISTRY_BANDWIDTH = "RegistryBandwidth";
+    public static final String SERVICE_BANDWIDTH = "ServiceBandwidth";
+    public static final String WEBAPP_BANDWIDTH = "WebappBandwidth";
+    public static final String IN_LABLE = "-In";
+    public static final String OUT_LABLE = "-Out";
+    public static final String REGISTRY_CONTENT_BANDWIDTH = "ContentBandwidth";
+    
+    final public static String REGISTRY_INCOMING_BW = REGISTRY_BANDWIDTH + IN_LABLE;
+    final public static String REGISTRY_OUTGOING_BW = REGISTRY_BANDWIDTH + OUT_LABLE;
+    final public static String REGISTRY_TOTAL_BW = "registry-total-bw-usage";
+    final public static String NUMBER_OF_USERS = "number-of-users";
+
+    final public static String SERVICE_INCOMING_BW = SERVICE_BANDWIDTH + IN_LABLE;
+    final public static String SERVICE_OUTGOING_BW = SERVICE_BANDWIDTH + OUT_LABLE;
+    final public static String SERVICE_TOTAL_BW = "serviceRequestTotalBw";
+    
+    final public static String WEBAPP_INCOMING_BW = WEBAPP_BANDWIDTH + IN_LABLE;
+    final public static String WEBAPP_OUTGOING_BW = WEBAPP_BANDWIDTH + OUT_LABLE;
+
+    final public static String API_CALL_COUNT = "apiCallCount";
+}


[33/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
new file mode 100644
index 0000000..cbd1d80
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.Date;
+
+/**
+ * Customer class - This holds the information of tenants
+ * i.e. customer=tenant
+ */
+public class Customer {
+    private int id;
+    private String name;
+    private String context;
+    private String fullName;
+    private String email;
+    private Date startedDate;
+    private String address;
+    private Invoice activeInvoice;
+    private long totalBandwidth;
+    private long totalStorage;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getFullName() {
+        return fullName;
+    }
+
+    public void setFullName(String fullName) {
+        this.fullName = fullName;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getContext() {
+        return context;
+    }
+
+    public void setContext(String context) {
+        this.context = context;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public Date getStartedDate() {
+        return new Date(startedDate.getTime());
+    }
+
+    public void setStartedDate(Date startedDate) {
+        this.startedDate = new Date(startedDate.getTime());
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    /**
+     * This will be used by rules to retrieve the active invoice
+     *
+     * @return
+     */
+    public final Invoice getActiveInvoice() {
+        return activeInvoice;
+    }
+
+    public final void setActiveInvoice(Invoice invoice) {
+        this.activeInvoice = invoice;
+    }
+
+    public long getTotalBandwidth() {
+        return totalBandwidth;
+    }
+
+    public void setTotalBandwidth(long totalBandwidth) {
+        this.totalBandwidth = totalBandwidth;
+    }
+
+    public long getTotalStorage() {
+        return totalStorage;
+    }
+
+    public void setTotalStorage(long totalStorage) {
+        this.totalStorage = totalStorage;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Customer customer = (Customer) o;
+
+        if (id != customer.id) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return id;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
new file mode 100644
index 0000000..862b1fd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
@@ -0,0 +1,88 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.dataobjects;
+
+
+import java.util.Date;
+
+public class Discount {
+    
+    private int id;
+    private int tenantId;
+    private float percentage;
+    private float amount;
+    private Date startDate;
+    private Date endDate;
+    private boolean isPercentageType;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public float getPercentage() {
+        return percentage;
+    }
+
+    public void setPercentage(float percentage) {
+        this.percentage = percentage;
+    }
+
+    public float getAmount() {
+        return amount;
+    }
+
+    public void setAmount(float amount) {
+        this.amount = amount;
+    }
+
+    public Date getStartDate() {
+        return startDate;
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = startDate;
+    }
+
+    public Date getEndDate() {
+        return endDate;
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = endDate;
+    }
+
+    public boolean isPercentageType() {
+        return isPercentageType;
+    }
+
+    public void setPercentageType(boolean percentageType) {
+        isPercentageType = percentageType;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
new file mode 100644
index 0000000..697ae77
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Invoice class - holds the invoice information
+ */
+public class Invoice {
+    int id;
+    Date date;
+    Date startDate;
+    Date endDate;
+    Cash boughtForward;
+    Cash carriedForward;
+    Cash totalCost;
+    Cash totalPayment;
+    Customer customer;
+    List<Subscription> subscriptions = new ArrayList<Subscription>();
+    List<Payment> payments = new ArrayList<Payment>();
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getDate() {
+        return new Date(date.getTime());
+    }
+
+    public void setDate(Date date) {
+        this.date = new Date(date.getTime());
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public Cash getBoughtForward() {
+        return boughtForward;
+    }
+
+    public void setBoughtForward(Cash boughtForward) {
+        this.boughtForward = boughtForward;
+    }
+
+    public Cash getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(Cash carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public Cash getTotalCost() {
+        return totalCost;
+    }
+
+    public void setTotalCost(Cash totalCost) {
+        this.totalCost = totalCost;
+    }
+
+    public Cash getTotalPayment() {
+        return totalPayment;
+    }
+
+    public void setTotalPayment(Cash totalPayment) {
+        this.totalPayment = totalPayment;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public List<Payment> getPayments() {
+        return payments;
+    }
+
+    public void setPayments(List<Payment> payments) {
+        this.payments = payments;
+    }
+
+    public void addPayment(Payment payment) {
+        this.payments.add(payment);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
new file mode 100644
index 0000000..66b156b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.List;
+
+public class Item {
+    private int id;
+    private String name;
+    private Cash cost;
+    private Cash creditLimit; //this is the credit limit defined by the billing rules
+    private int bandwidthLimit;
+    private Cash bandwidthOveruseCharge;
+    private int resourceVolumeLimit;
+    private Cash resourceVolumeOveruseCharge;
+    private String description;
+    private Item parent;
+    private List<? extends Item> children;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Cash getCost() {
+        return cost;
+    }
+
+    public void setCost(Cash cost) {
+        this.cost = cost;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public Item getParent() {
+        return parent;
+    }
+
+    public void setParent(Item parent) {
+        this.parent = parent;
+    }
+
+    public List<? extends Item> getChildren() {
+        return children;
+    }
+
+    public void setChildren(List<? extends Item> children) {
+        this.children = children;
+    }
+
+    public Cash getCreditLimit() {
+        return creditLimit;
+    }
+
+    public void setCreditLimit(Cash creditLimit) {
+        this.creditLimit = creditLimit;
+    }
+
+    public int getBandwidthLimit() {
+        return bandwidthLimit;
+    }
+
+    public void setBandwidthLimit(int bandwidthLimit) {
+        this.bandwidthLimit = bandwidthLimit;
+    }
+
+    public Cash getBandwidthOveruseCharge() {
+        return bandwidthOveruseCharge;
+    }
+
+    public void setBandwidthOveruseCharge(Cash bandwidthOveruseCharge) {
+        this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+    }
+
+    public int getResourceVolumeLimit() {
+        return resourceVolumeLimit;
+    }
+
+    public void setResourceVolumeLimit(int resourceVolumeLimit) {
+        this.resourceVolumeLimit = resourceVolumeLimit;
+    }
+
+    public Cash getResourceVolumeOveruseCharge() {
+        return resourceVolumeOveruseCharge;
+    }
+
+    public void setResourceVolumeOveruseCharge(Cash resourceVolumeOveruseCharge) {
+        this.resourceVolumeOveruseCharge = resourceVolumeOveruseCharge;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Item item = (Item) o;
+
+        if (name != null ? !name.equals(item.name) : item.name != null) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return name != null ? name.hashCode() : 0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
new file mode 100644
index 0000000..e99f5d7
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+public class Payment {
+    int id;
+    Date date;
+    Cash amount;
+    String description;
+    List<Subscription> subscriptions;
+    Invoice invoice;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getDate() {
+        if(date!=null){
+            return new Date(date.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setDate(Date date) {
+        if(date!=null){
+            this.date = new Date(date.getTime());
+        }else{
+            this.date = null;
+        }
+    }
+
+    public Cash getAmount() {
+        return amount;
+    }
+
+    public void setAmount(Cash amount) {
+        this.amount = amount;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public void addSubscription(Subscription subscription) {
+        if (this.subscriptions == null) {
+            this.subscriptions = new ArrayList<Subscription>();
+        }
+        subscriptions.add(subscription);
+    }
+
+    public Invoice getInvoice() {
+        return invoice;
+    }
+
+    public void setInvoice(Invoice invoice) {
+        this.invoice = invoice;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
new file mode 100644
index 0000000..0b9fbf3
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Subscription class - information on subscriptions which the users
+ * are subscribed to.
+ */
+public class Subscription {
+    int id;
+    Date activeSince;
+    Date activeUntil;
+    Item item;
+    Customer customer;
+    boolean active;
+    int invoiceSubscriptionId = -1; // requires only if associated with an invoice
+    List<Payment> payments;
+    String subscriptionPlan;        //i.e. multitenance-small, multitencay-medium .....
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getActiveSince() {
+        if(activeSince!=null){
+            return  new Date(activeSince.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setActiveSince(Date activeSince) {
+        if(activeSince!=null){
+            this.activeSince = new Date(activeSince.getTime());
+        }else{
+            this.activeSince = null;
+        }
+
+    }
+
+    public Date getActiveUntil() {
+        if(activeUntil!=null){
+            return  new Date(activeUntil.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setActiveUntil(Date activeUntil) {
+        if(activeUntil!=null){
+            this.activeUntil = new Date(activeUntil.getTime());
+        }else{
+            this.activeUntil = null;
+        }
+
+    }
+
+    public Item getItem() {
+        return item;
+    }
+
+    public void setItem(Item item) {
+        this.item = item;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+    public int getInvoiceSubscriptionId() {
+        return invoiceSubscriptionId;
+    }
+
+    public void setInvoiceSubscriptionId(int invoiceSubscriptionId) {
+        this.invoiceSubscriptionId = invoiceSubscriptionId;
+    }
+
+    public List<Payment> getPayments() {
+        return payments;
+    }
+
+    public void setPayments(List<Payment> payments) {
+        this.payments = payments;
+    }
+
+    public String getSubscriptionPlan() {
+        return subscriptionPlan;
+    }
+
+    public void setSubscriptionPlan(String subscriptionPlan) {
+        this.subscriptionPlan = subscriptionPlan;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
new file mode 100644
index 0000000..cadc052
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Stores the generated invoice in the billing database.
+ */
+public class DefaultFinalizingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(DefaultFinalizingHandler.class);
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        // saving the bill
+        saveInvoice(handlerContext);
+    }
+
+    private void saveInvoice(BillingEngineContext handlerContext) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+        
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            Invoice invoice = customer.getActiveInvoice();
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        // from the invoice set we are calculating the purchase orders
+        for (Invoice invoice : invoiceMap.values()) {
+            // save the invoice first
+            dataAccessObject.addInvoice(invoice);
+            subscriptions = invoice.getSubscriptions();
+            for (Subscription subscription : subscriptions) {
+                // associate the subscription with the invoice.
+                int invoiceSubscriptionId =
+                        dataAccessObject.addInvoiceSubscription(invoice, subscription);
+                // now iterate all the items and save it in invoice subscription item space
+                if (subscription.getItem() != null) {
+                    addInvoiceSubscriptionItem(subscription.getItem(), invoiceSubscriptionId);
+                }
+            }
+        }
+        log.info( invoiceMap.size() + " Invoices saved to the database");
+    }
+
+    private void addInvoiceSubscriptionItem(Item item, 
+                                            int invoiceSubscriptionId) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        dataAccessObject.addInvoiceSubscriptionItem(item, invoiceSubscriptionId);
+        // and iterate through all the item children
+        if (item.getChildren() != null) {
+            for (Item subItem : item.getChildren()) {
+                addInvoiceSubscriptionItem(subItem, invoiceSubscriptionId);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
new file mode 100644
index 0000000..0dc39e1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This class finds all relevant subscription entries for
+ * the period considered in billing (i.e. billing cycle)
+ */
+public class DefaultSubscriptionFeedingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(DefaultSubscriptionFeedingHandler.class);
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    /**
+     *
+     * @param handlerContext - BillingEngineContext which keeps the data
+     * used in the bill generation process
+     * @throws BillingException
+     */
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        feedSubscriptions(handlerContext);
+    }
+
+    /**
+     * Finds the subscription of all the tenants applicable for the period being
+     * considered in bill generation
+     * @param handlerContext
+     * @throws BillingException
+     */
+    private void feedSubscriptions(BillingEngineContext handlerContext) throws BillingException {
+        // get the subscriptions right here..
+        Customer customer = handlerContext.getCustomer();
+        List<Subscription> subscriptions = getFilteredActiveSubscriptions(null, customer);
+        // prepare the handler context
+        handlerContext.setSubscriptions(subscriptions);
+        String infoMsg = "Subscription feeding phase completed. ";
+        if (subscriptions!=null){
+            infoMsg += subscriptions.size() + " subscriptions fed. ";
+        }else{
+            infoMsg += "0 subscriptions fed. ";
+        }
+        log.info(infoMsg);
+    }
+
+    /**
+     *
+     * @param filter - currently we pass the string "multitencay" because we
+     * need all the subscriptions. But, if you want subscriptions of a specific usage plan
+     * then you can pass it here. 
+     * @param customer - if generating an interim invoice, this is applicable.
+     * otherwise this will be null
+     * @return a list of subscriptions
+     * @throws BillingException
+     */
+    private List<Subscription> getFilteredActiveSubscriptions(String filter,
+                                                Customer customer) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        List<Subscription> subscriptions = null;
+        try {
+            dataAccessObject.beginTransaction();
+            if (customer == null) {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptions(filter);
+            } else {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptionsForCustomer(filter,
+                                                                                           customer);
+            }
+
+            // iterate through all the subscriptions and assign correct customer and item
+            for (Subscription subscription : subscriptions) {
+                Customer dummyCustomer = subscription.getCustomer();
+                Customer correctCustomer = getCustomer(dummyCustomer.getId());
+                subscription.setCustomer(correctCustomer);
+
+                Item dummyItem = subscription.getItem();
+                Item correctItem = getItem(dummyItem.getId());
+                subscription.setItem(correctItem);
+            }
+            dataAccessObject.commitTransaction();
+        }catch(Exception e){
+            String msg = "Error occurred while feeding subscription entries: " +
+                            e.getMessage();
+            log.error(msg);
+            dataAccessObject.rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    /**
+     * Gets the billable item for a subscription
+     * @param itemId in the subscription entry
+     * @return the item retrieved from the db
+     * @throws BillingException
+     */
+    private Item getItem(int itemId) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        Item item = null;
+        try {
+            dataAccessObject.beginTransaction();
+            item = dataAccessObject.getItem(itemId);
+            dataAccessObject.commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while retrieving item for item id: " + itemId +
+                            ": " + e.getMessage();
+            dataAccessObject.rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return item;
+    }
+
+    private Customer getCustomer(int customerId) throws BillingException {
+        Customer customer = new Customer();
+        CustomerUtils.fillCustomerData(customerId, customer);
+        return customer;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
new file mode 100644
index 0000000..0990d74
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Payment;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.email.sender.api.BulkEmailSender;
+import org.wso2.carbon.email.sender.api.EmailDataHolder;
+import org.wso2.carbon.email.sender.api.EmailSender;
+import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Handles the email notifications after the bill generation
+ */
+public class EmailSendingHandler implements BillingHandler {
+    private static Log log = LogFactory.getLog(EmailSendingHandler.class);
+    private static String DEFAULT_EMAIL_NOTIFICATION_TEMPLATE_FILE = "email-billing-notification.xml";
+    private static String DEFAULT_REPORT_EMAIL_TEMPLATE_FILE = "email-bill-generated.xml";
+    private static String EMAIL_SENDING_CONF_KEY = "file";
+    private static String REPORT_EMAIL_TO_ADDRESS ="cloudservice@wso2.com";
+    BulkEmailSender bulkEmailSender;
+    EmailSender reportMailSender;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        if(CommonUtil.getStratosConfig()!=null){
+            REPORT_EMAIL_TO_ADDRESS = CommonUtil.getStratosConfig().getNotificationEmail();
+        }
+        
+        String confFileName = handlerConfig.get(EMAIL_SENDING_CONF_KEY);
+        if (confFileName == null) {
+            confFileName = DEFAULT_EMAIL_NOTIFICATION_TEMPLATE_FILE;
+        }
+        confFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator
+                       +StratosConstants.EMAIL_CONFIG+ File.separator + confFileName;
+
+        EmailSenderConfiguration emailSenderConfig =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(confFileName);
+        bulkEmailSender = new BulkEmailSender(emailSenderConfig);
+
+        //this is the email sent to the admin after bill generation
+        String reportMailFileName = DEFAULT_REPORT_EMAIL_TEMPLATE_FILE;
+        reportMailFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator
+                             +StratosConstants.EMAIL_CONFIG+File.separator+ reportMailFileName;
+
+        EmailSenderConfiguration reportEmailSenderConfig =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(reportMailFileName);
+        reportMailSender = new EmailSender(reportEmailSenderConfig);
+
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+        List<Integer> creditLimitExceededCustomers = new ArrayList<Integer>();
+        //this holds the data to be sent to bulk email bulkEmailSender
+        List<EmailDataHolder> emailDataList = new ArrayList<EmailDataHolder>();
+        
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            Invoice invoice = customer.getActiveInvoice();
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        for (Invoice invoice : invoiceMap.values()) {
+
+            //checkinh whether the carried forward is $0 because we dont want to
+            //send emails for $0 bills
+            Cash diff = Cash.subtract(new Cash("$0"), invoice.getCarriedForward());
+            if(diff.getSign().equals(Cash.Sign.NEGATIVE)){
+                Map<String, String> mailParameters = deriveInvoiceMailParameters(invoice);
+                Customer customer = invoice.getCustomer();
+                String emailAddress = customer.getEmail();
+                EmailDataHolder emailData = new EmailDataHolder();
+                emailData.setEmail(emailAddress);
+                emailData.setEmailParameters(mailParameters);
+                //we keep the data in the list to be sent as bulk
+                emailDataList.add(emailData);
+            }
+
+            //adding the customers who have exceeded the credit limit
+            // to a list to be informed to the admin
+            if(isExceedsCreditLimit(invoice)){
+                log.debug("Customer " + invoice.getCustomer().getName() + " needs to be reported");
+                creditLimitExceededCustomers.add(invoice.getCustomer().getId());
+            }
+
+        }
+
+        try {
+            log.info("Sending emails to the customers: " + emailDataList.size());
+            bulkEmailSender.sendBulkEmails(emailDataList);
+            log.info("Email (invoices) sending completed");
+        } catch (Exception e) {
+            String msg = "Error in sending the invoices to the customers";
+            log.error(msg, e);
+        }
+        //now sending the email with customers who have exceeded the credit limit
+        Map<String, String> reportEmailParameters = deriveReportEmailParameters(creditLimitExceededCustomers, invoiceMap);
+        try {
+            reportMailSender.sendEmail(REPORT_EMAIL_TO_ADDRESS, reportEmailParameters);
+            log.info("Email sent to the admin.");
+        } catch (Exception e) {
+            String msg = "Error in sending the bill generation completed email";
+            log.error(msg, e);
+        }
+
+    }
+
+    public static Map<String, String> deriveInvoiceMailParameters(Invoice invoice) {
+        Map<String, String> mailParameters = new HashMap<String, String>();
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+        mailParameters.put("start-date", dateFormat.format(invoice.getStartDate()));
+        mailParameters.put("end-date", dateFormat.format(invoice.getEndDate()));
+
+        Customer customer = invoice.getCustomer();
+
+        try{
+            TenantManager tenantManager = Util.getRealmService().getTenantManager();
+            Tenant tenant = (Tenant) tenantManager.getTenant(customer.getId());
+            mailParameters.put("tenant-domain", tenant.getDomain());
+            String customerName =
+                    ClaimsMgtUtil.getFirstName(Util.getRealmService(), customer.getId());
+            if(customerName!=null){
+                mailParameters.put("customer-name", customerName);
+            }else{
+                mailParameters.put("customer-name", "");
+            }
+
+        }catch(Exception e){
+            log.error("Could not get tenant information for tenant: " +
+                    customer.getName() + "\n" + e.getMessage());
+            mailParameters.put("customer-name", "");
+        }
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        if (subscriptions != null) {
+            StringBuffer subscriptionText = new StringBuffer();
+            for (Subscription subscription : subscriptions) {
+
+                if(subscription.isActive()){
+                    mailParameters.put("current-subscription", subscription.getSubscriptionPlan());
+                }
+                Item item = subscription.getItem();
+                String itemName = item.getDescription();
+                Cash itemCost = item.getCost();
+
+                String subscriptionPlan = subscription.getSubscriptionPlan();
+                if(itemCost!=null){
+                    subscriptionText.append(subscriptionPlan).append("\t\t\t").append(itemCost.toString()).append("\n");
+                }else{
+                    subscriptionText.append(subscriptionPlan).append("\n");
+                }
+
+                List<? extends Item> children = item.getChildren();
+                if (children != null) {
+                    for (Item childItem : children) {
+                        String childItemName = childItem.getDescription();
+                        Cash childItemCost = childItem.getCost();
+                        String childItemCostStr;
+                        if(childItemCost!=null){
+                            childItemCostStr = childItemCost.toString();
+                        }else{
+                            childItemCostStr = "$0.00";
+                        }
+                        subscriptionText.append("\t").append(childItemName).append("\t\t")
+                                .append(childItemCostStr).append("\n");
+                    }
+                }
+                subscriptionText.append("-------------------------------------------").append("\n");
+            }
+            mailParameters.put("subscription-charges", subscriptionText.toString());
+        }
+
+        StringBuffer paymentText = new StringBuffer();
+        if (invoice.getPayments() != null && invoice.getPayments().size()>0) {
+            for (Payment payment : invoice.getPayments()) {
+                Date paymentDate = payment.getDate();
+                Cash paymentAmount = payment.getAmount();
+
+                paymentText.append(dateFormat.format(paymentDate)).append("\t\t")
+                        .append(paymentAmount.toString()).append("\n");
+            }
+        }else{
+            paymentText.append("No payment details during this period");
+        }
+        mailParameters.put("payment-details", paymentText.toString());
+
+        if (invoice.getBoughtForward() != null) {
+            mailParameters.put("bought-forward", invoice.getBoughtForward().toString());
+        } else {
+            mailParameters.put("bought-forward", "$0");
+        }
+        if (invoice.getTotalCost() != null) {
+            mailParameters.put("total-cost", invoice.getTotalCost().toString());
+        } else {
+            mailParameters.put("total-cost", "$0");
+        }
+        if (invoice.getTotalPayment() != null) {
+            mailParameters.put("total-payments", invoice.getTotalPayment().toString());
+        } else {
+            mailParameters.put("total-payments", "$0");
+        }
+        if (invoice.getCarriedForward() != null) {
+            mailParameters.put("carried-forward", invoice.getCarriedForward().toString());
+        } else {
+            mailParameters.put("carried-forward", "$0");
+        }
+
+        return mailParameters;
+    }
+
+    private boolean isExceedsCreditLimit(Invoice invoice) throws BillingException{
+        boolean exceedsCreditLimit = false;
+        Cash creditLimit = new Cash("$0");
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        for(Subscription subscription : subscriptions){
+            if(subscription.isActive()){
+                List<? extends Item> subItems = subscription.getItem().getChildren();
+                for (Item item : subItems){
+                    if(BillingConstants.SUBSCRIPTION_SUBITEM.equals(item.getName())){
+                        if(item.getCreditLimit()!=null){
+                            creditLimit = Cash.add(creditLimit, item.getCreditLimit());
+                        }else{
+                            creditLimit = Cash.add(creditLimit, new Cash("$0"));
+                        }
+                        break;
+                    }
+                }
+                break;
+            }
+        }
+
+        Cash difference = Cash.subtract(invoice.getCarriedForward(), creditLimit);
+        if(Cash.Sign.POSITIVE == difference.getSign() && difference.getWholeNumber()>0){
+            exceedsCreditLimit = true;
+        }
+        return exceedsCreditLimit;
+    }
+
+    public Map<String, String> deriveReportEmailParameters(List<Integer> creditExceededCustomers, Map<Integer, Invoice> invoiceMap){
+        Map<String, String> mailParameters = new HashMap<String, String>();
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+        //note that I haven't considered the timezone here
+        mailParameters.put("date", dateFormat.format(new Date()));
+
+        StringBuffer reportedCustomers = new StringBuffer();
+        if(creditExceededCustomers.isEmpty()){
+            reportedCustomers.append("No customers to be reported");
+        }else{
+            for(Integer customerId : creditExceededCustomers){
+                Invoice invoice = invoiceMap.get(customerId);
+                List<Subscription> subscriptions = invoice.getSubscriptions();
+                String activeSubscriptionName = "";
+                for(Subscription subscription : subscriptions){
+                    if(subscription.isActive()){
+                        activeSubscriptionName = subscription.getSubscriptionPlan();
+                        break;
+                    }
+                }
+                reportedCustomers.append(invoice.getCustomer().getName()).append("\t\t").
+                        append(activeSubscriptionName).append("\t\t").append(invoice.getCarriedForward().toString()).
+                        append("\n");
+            }
+        }
+        mailParameters.put("reported-customers", reportedCustomers.toString());
+
+        return mailParameters;
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
new file mode 100644
index 0000000..99fd286
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.*;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+
+import java.text.NumberFormat;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Calculates overusage charges, CF value, total payments etc.
+ */
+public class InvoiceCalculationHandler implements BillingHandler {
+
+    Log log = LogFactory.getLog(InvoiceCalculationHandler.class);
+    Map<Integer, Discount> discountMap = new HashMap<Integer, Discount>();
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        //we are getting the discount list and put them in to a map
+        List<Discount> discountList = BillingManager.getInstance().getDataAccessObject().getAllActiveDiscounts();
+        for(Discount discount : discountList){
+            discountMap.put(discount.getTenantId(), discount);
+        }
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        // calculate the bill
+        calculateInvoice(handlerContext);
+    }
+
+    private void calculateInvoice(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+       
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+
+            // invoice should be already set..
+            Invoice invoice = customer.getActiveInvoice();
+            Cash totalCost = invoice.getTotalCost();
+            if (totalCost == null) {
+                totalCost = new Cash("$0");
+            }
+        
+            Item item = subscription.getItem();
+            //prorate the subscription cost
+            //prorateItemCosts(item, invoice, subscription);
+            calculateItemCost(item, invoice, subscription);
+            Cash itemCost = getItemCost(item);
+            totalCost = Cash.add(totalCost, itemCost);
+            invoice.setTotalCost(totalCost);
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        // from the invoice set we are calculating the payments       purchase orders
+        for (Invoice invoice : invoiceMap.values()) {
+            Cash totalPayment = invoice.getTotalPayment();
+            if (totalPayment == null) {
+                totalPayment = new Cash("$0");
+            }
+            List<Payment> payments = invoice.getPayments();
+            if (payments != null) {
+                for (Payment payment : payments) {
+                    Cash paymentCash = payment.getAmount();
+                    totalPayment = Cash.add(paymentCash, totalPayment);
+                }
+            }
+            invoice.setTotalPayment(totalPayment);
+
+            // setting the carried forward
+            Cash boughtForward = invoice.getBoughtForward();
+            if (boughtForward == null) {
+                boughtForward = new Cash("$0");
+            }
+            Cash totalCost = invoice.getTotalCost();
+            Cash carriedForward = Cash.subtract(Cash.add(boughtForward, totalCost), totalPayment);
+            invoice.setCarriedForward(carriedForward);
+        }
+
+        log.info("Invoice calculation phase completed. " + invoiceMap.size() + " invoices were calculated");
+    }
+
+    private Cash getItemCost(Item item) throws BillingException {
+        Cash itemCost = item.getCost();
+        if (itemCost == null) {
+            itemCost = new Cash("$0");
+        }
+        if (item.getChildren() != null) {
+            // and iterate through all the item children
+            for (Item subItem : item.getChildren()) {
+                Cash subItemCost = subItem.getCost();
+                if (subItemCost != null) {
+                    itemCost = Cash.add(itemCost, subItemCost);
+                }
+            }
+        }
+        return itemCost;
+    }
+
+    private void calculateItemCost(Item item, Invoice invoice, Subscription subscription) throws BillingException {
+        if(item.getChildren()!=null){
+            for(Item subItem : item.getChildren()){
+                if((BillingConstants.BANDWIDTH_SUBITEM.equals(subItem.getName()) ||
+                    BillingConstants.STORAGE_SUBITEM.equals(subItem.getName())) && subscription.isActive()){
+                    calculateOverUseCharges(item, subItem, subscription);
+                }else if(BillingConstants.SUBSCRIPTION_SUBITEM.equals(subItem.getName())){
+                    prorateItemCosts(subItem, invoice, subscription);
+                }
+            }
+        }
+    }
+
+    private void calculateOverUseCharges(Item item, Item subItem, Subscription subscription) throws BillingException {
+        //calculating cost for bandwidth overuse
+        if(BillingConstants.BANDWIDTH_SUBITEM.equals(subItem.getName())){
+            long bandwidthUsage = subscription.getCustomer().getTotalBandwidth()/(1024 * 1024L);
+            long bandwidthOveruse = 0;
+            if(bandwidthUsage > item.getBandwidthLimit()){
+                bandwidthOveruse = bandwidthUsage - item.getBandwidthLimit();
+                subItem.setCost(item.getBandwidthOveruseCharge().multiply(bandwidthOveruse));
+            }
+            StringBuffer description = new StringBuffer();
+            description.append(subItem.getDescription());
+            description.append(": ").append(bandwidthOveruse).append("MB");
+            subItem.setDescription(description.toString());
+        //calculating cost for storage overuse    
+        }else if(BillingConstants.STORAGE_SUBITEM.equals(subItem.getName())){
+            long storageUsage = subscription.getCustomer().getTotalStorage()/(1024 * 1024L);
+            long storageOveruse = 0;
+            if(storageUsage > item.getResourceVolumeLimit()){
+                storageOveruse = storageUsage - item.getResourceVolumeLimit();
+                subItem.setCost(item.getResourceVolumeOveruseCharge().multiply(storageOveruse));
+            }
+            StringBuffer description = new StringBuffer();
+            description.append(subItem.getDescription());
+            description.append(": ").append(storageOveruse).append("MB");
+            subItem.setDescription(description.toString());
+        }
+
+    }
+
+    //by looking at the start and end dates of the invoice, subscription item's cost is interpolated
+    private void prorateItemCosts(Item subItem, Invoice invoice, Subscription subscription) throws BillingException {
+        long milisecondsPerDay = 24*60*60*1000L;
+        NumberFormat nf = NumberFormat.getInstance();
+		nf.setMaximumFractionDigits(2);
+
+        int tenantId = invoice.getCustomer().getId();
+        Discount discount = discountMap.get(tenantId);
+
+        long period;
+        long days;
+
+        if(subscription.isActive()){
+            if(subscription.getActiveSince().before(invoice.getStartDate())){
+                period = invoice.getEndDate().getTime() - invoice.getStartDate().getTime();
+            }else{
+                period = invoice.getEndDate().getTime() - subscription.getActiveSince().getTime();
+            }
+        }else{ 
+            if(subscription.getActiveSince().before(invoice.getStartDate())){
+                period = subscription.getActiveUntil().getTime() - invoice.getStartDate().getTime();
+            }else{
+                period = subscription.getActiveUntil().getTime() - subscription.getActiveSince().getTime();
+            }
+        }
+
+        //I am considering 28 days or more as a complete month
+        days = period/milisecondsPerDay;
+        if(days<28){
+            float multiplyingFactor = (float)days/30;
+            multiplyingFactor = Float.parseFloat(nf.format(multiplyingFactor));
+
+            //prorate the subscription fee...
+            if(subItem.getCost()!=null){
+                subItem.setCost(subItem.getCost().multiply(multiplyingFactor));
+            }
+
+            //prorating the discount too (if the discount is defined as a raw amount)...
+            if(discount!=null && !discount.isPercentageType()){
+                discount.setAmount(Float.parseFloat(nf.format(discount.getAmount()*multiplyingFactor)));
+            }
+        }
+        
+        //Check whether the customer is offered any discounts and reduce the subscription fee
+        
+        if(discount!=null){
+            
+            if(discount.isPercentageType()){
+                subItem.setCost(subItem.getCost().multiply(1 - (discount.getPercentage()/100)));
+                subItem.setDescription(subItem.getDescription() + " (with " + discount.getPercentage() + "% discount)");
+                log.info("Customer: " + tenantId + " was qualified for a discount of " +
+                        discount.getPercentage() + "% for subscription:" + subscription.getSubscriptionPlan() +
+                        " which started from:" + subscription.getActiveSince().toString());
+            }else{
+                subItem.setCost(Cash.subtract(subItem.getCost(), new Cash(String.valueOf(discount.getAmount()))));
+                subItem.setDescription(subItem.getDescription() + " (with " + new Cash(String.valueOf(discount.getAmount())).toString() + " discount)");
+                log.info("Customer: " + tenantId + " was qualified for a discount of " +
+                        new Cash(String.valueOf(discount.getAmount())).toString() + " for subscription:" + subscription.getSubscriptionPlan() +
+                        " which started from:" + subscription.getActiveSince().toString());
+            }
+
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
new file mode 100644
index 0000000..630db9f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.rule.common.Rule;
+import org.wso2.carbon.rule.common.RuleSet;
+import org.wso2.carbon.rule.common.exception.RuleConfigurationException;
+import org.wso2.carbon.rule.common.exception.RuleRuntimeException;
+import org.wso2.carbon.rule.common.util.Constants;
+import org.wso2.carbon.rule.kernel.backend.RuleBackendRuntime;
+import org.wso2.carbon.rule.kernel.backend.RuleBackendRuntimeFactory;
+import org.wso2.carbon.rule.kernel.backend.Session;
+import org.wso2.carbon.rule.kernel.config.RuleEngineProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.*;
+
+/**
+ * Runs the billing rules against each subscription
+ * At the moment only the subscription fee is calculated by
+ * these rules. Overusage charges are calculated by InvoiceCalculationHandler
+ */
+public class RuleHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(RuleHandler.class);
+    private Session ruleSession;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+
+        //create a rule run time to execute rules.
+
+        RuleEngineProvider ruleEngineProvider = Util.getRuleEngineConfigService().getRuleConfig().getRuleEngineProvider();
+
+        Class ruleBackendRuntimeFactoryClass;
+
+        try {
+            ruleBackendRuntimeFactoryClass = Class.forName(ruleEngineProvider.getClassName());
+            RuleBackendRuntimeFactory ruleBackendRuntimeFactory =
+                    (RuleBackendRuntimeFactory) ruleBackendRuntimeFactoryClass.newInstance();
+            RuleBackendRuntime ruleBackendRuntime =
+                           ruleBackendRuntimeFactory.getRuleBackendRuntime(ruleEngineProvider.getProperties(),
+                           Thread.currentThread().getContextClassLoader());
+
+            // create a rule set to add
+            RuleSet ruleSet = new RuleSet();
+            Rule rule = new Rule();
+            rule.setResourceType(Constants.RULE_RESOURCE_TYPE_REGULAR);
+
+            rule.setSourceType(Constants.RULE_SOURCE_TYPE_URL);
+
+            String ruleFile = handlerConfig.get("file");
+            ruleFile = CarbonUtils.getCarbonConfigDirPath() + File.separator + ruleFile;
+            rule.setValue("file://" + ruleFile);
+            log.info("Rule: " + rule.getValue());
+
+            ruleSet.addRule(rule);
+
+            ruleBackendRuntime.addRuleSet(ruleSet);
+
+            this.ruleSession = ruleBackendRuntime.createSession(Constants.RULE_STATEFUL_SESSION);
+
+        } catch (Exception e) {
+            String msg = "Error occurred while initializing the rule executing environment: " +
+                    e.getMessage();
+            log.error(msg);
+            throw new BillingException(msg, e);
+        } 
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+
+        List<Object> rulesInput = new ArrayList<Object>();
+        Set<Integer> customerSet = new HashSet<Integer>();
+
+        for (Subscription subscription : subscriptions) {
+            // add the subscriptions
+            rulesInput.add(subscription);
+
+            // add the customers
+            Customer customer = subscription.getCustomer();
+            if (!customerSet.contains(customer.getId())) {
+                customerSet.add(customer.getId());
+                rulesInput.add(customer);
+
+                // add the invoice too
+                Invoice invoice = customer.getActiveInvoice();
+                rulesInput.add(invoice);
+
+                // add each purchases
+                List<Payment> payments = invoice.getPayments();
+                if (payments != null) {
+                    for (Payment payment : payments) {
+                        rulesInput.add(payment);
+                    }
+                }
+            }
+
+            // add the items
+            Item item = subscription.getItem();
+            rulesInput.add(item);
+
+            List<? extends Item> children = item.getChildren();
+            if (children != null) {
+                for (Item subItem : item.getChildren()) {
+                    rulesInput.add(subItem);
+                }
+            }
+        }
+
+        try {
+            this.ruleSession.execute(rulesInput);
+        } catch (RuleRuntimeException e) {
+            String msg = "Error occurred while executing rules during the bill generation: " +
+                    e.getMessage();
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+        log.info("Rule execution phase completed.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
new file mode 100644
index 0000000..131430f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Payment;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Subscriptions found in the subscription feeding handler are
+ * added to relevant invoices via this class
+ */
+public class SubscriptionTreeBuildingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(SubscriptionTreeBuildingHandler.class);
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        buildSubscriptionTree(handlerContext);
+    }
+
+    /**
+     * Creates maps of <customer, list of subscriptions>. Then creates
+     * invoices for each customers.
+     * @param handlerContext this is the BillingEngineContext
+     * @throws BillingException throws a BillingException
+     */
+    private void buildSubscriptionTree(BillingEngineContext handlerContext) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+
+        // get the subscription from handler context
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+
+        Map<Customer, List<Subscription>> customersSubscriptions = new HashMap<Customer, List<Subscription>>();
+
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            List<Subscription> customerSubscriptions = customersSubscriptions.get(customer);
+            if (customerSubscriptions == null) {
+                customerSubscriptions = new ArrayList<Subscription>();
+            }
+            customerSubscriptions.add(subscription);
+            customersSubscriptions.put(customer, customerSubscriptions);
+        }
+
+        // so iterating all the customers
+        for (Map.Entry<Customer, List<Subscription>> entry : customersSubscriptions.entrySet()) {
+            Customer customer = entry.getKey();
+            List<Subscription> customerSubscriptions = entry.getValue();
+
+            // create an empty invoice
+            Invoice invoice = new Invoice();
+
+            // get the last invoice for the customer
+            Invoice lastInvoice = dataAccessObject.getLastInvoice(customer);
+
+            if (lastInvoice != null) {
+                invoice.setBoughtForward(lastInvoice.getCarriedForward());
+                long lastInvoiceEnd = lastInvoice.getEndDate().getTime();
+                long currentInvoiceStart = lastInvoiceEnd + 1000;    //one second after
+                                                                    // the last invoice
+                invoice.setStartDate(new Date(currentInvoiceStart));
+            } else {
+                invoice.setBoughtForward(new Cash("$0"));
+                // the earliest of the subscriptions
+                long earliestSubscriptionStart = -1;
+                for (Subscription subscription : customerSubscriptions) {
+                    long subscriptionStartDate = subscription.getActiveSince().getTime();
+                    if (earliestSubscriptionStart == -1 ||
+                        subscriptionStartDate < earliestSubscriptionStart) {
+                        earliestSubscriptionStart = subscriptionStartDate;
+                    }
+                }
+                invoice.setStartDate(new Date(earliestSubscriptionStart));
+            }
+            
+            Date currentDate = new Date();
+            invoice.setEndDate(currentDate);
+            // this is the date the billing is initialized, this can be probably overwritten
+            invoice.setDate(currentDate);
+
+            // and we will count for the subscriptions for the invoice
+            invoice.setSubscriptions(customerSubscriptions);
+
+            // and then we will count on the un-billed purchases of all the subscriptions of the
+            // customer
+            Map<Integer, Payment> purchaseOrders = new HashMap<Integer, Payment>();
+            for (Subscription subscription : customerSubscriptions) {
+                dataAccessObject.fillUnbilledPayments(subscription, purchaseOrders, invoice );
+            }
+            for (Payment payment : purchaseOrders.values()) {
+                invoice.addPayment(payment);
+            }
+
+            customer.setActiveInvoice(invoice);
+            invoice.setCustomer(customer);
+        }
+
+        log.info("Subscription-tree building phase completed");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
new file mode 100644
index 0000000..ad697e9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
@@ -0,0 +1,171 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.internal;
+
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingTenantMgtListenerImpl;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.ndatasource.core.DataSourceService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.rule.kernel.config.RuleEngineConfigService;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.stratos.common.util.StratosConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * @scr.component name="org.wso2.carbon.billing.core" immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1"
+ *                policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="org.wso2.carbon.billing.core.billing.handler.service"
+ *                interface="org.wso2.carbon.billing.core.BillingHandler"
+ *                cardinality="0..n"
+ *                policy="dynamic" bind="setBillingHandlerService"
+ *                unbind="unsetBillingHandlerService"
+ * @scr.reference name="org.wso2.carbon.billing.core.task.schedule.helper.service"
+ *                interface="org.wso2.carbon.billing.core.scheduler.ScheduleHelper"
+ *                cardinality="0..n"
+ *                policy="dynamic" bind="setScheduleHelperService"
+ *                unbind="unsetScheduleHelperService"
+ * @scr.reference name="rule.engine.config.server.component"
+ *                interface="org.wso2.carbon.rule.kernel.config.RuleEngineConfigService"
+ *                cardinality="1..1"
+ *                policy="dynamic" bind="setRuleEngineConfigService"
+ *                unbind="unsetRuleEngineConfigService"
+ * @scr.reference name="org.wso2.carbon.tenant.mgt.listener.service"
+ *                interface="org.wso2.carbon.stratos.common.listeners.TenantMgtListener"
+ *                cardinality="0..n" policy="dynamic"
+ *                bind="setTenantMgtListenerService"
+ *                unbind="unsetTenantMgtListenerService"
+ * @scr.reference name="datasources.service"
+ *                interface="org.wso2.carbon.ndatasource.core.DataSourceService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setDataSourceService" unbind="unsetDataSourceService" 
+ */
+public class BillingServiceComponent {
+    private static Log log = LogFactory.getLog(BillingServiceComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            if(CommonUtil.getStratosConfig()==null){
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+            Util.initBillingManager(context.getBundleContext());
+            Util.initDataAccessManager();
+
+            BillingTenantMgtListenerImpl billingTenantMgtListener = new BillingTenantMgtListenerImpl();
+            context.getBundleContext().registerService(
+                    org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
+                    billingTenantMgtListener, null);
+            if (log.isDebugEnabled()) {
+                log.debug("******* Billing bundle is activated ******* ");
+            }
+        } catch (Throwable e) {
+            log.error("******* Billing bundle failed activating ****", e);
+        }
+    }
+
+    @SuppressWarnings("unused")
+    protected void deactivate(ComponentContext context) {
+        Util.cleanBillingManager();
+        log.debug("******* Billing is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    protected void setBillingHandlerService(BillingHandler billingHandler) {
+        BillingTaskConfiguration.addBillingHandler(billingHandler);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetBillingHandlerService(BillingHandler billingHandler) {
+        // we are not dynamically removing billing handlers
+    }
+
+    protected void setScheduleHelperService(ScheduleHelper scheduleHelper) {
+        BillingTaskConfiguration.addScheduleHelper(scheduleHelper);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetScheduleHelperService(ScheduleHelper scheduleHelper) {
+        // we are not dynamically removing schedule helpers
+    }
+
+    protected void setRuleEngineConfigService(RuleEngineConfigService ruleEngineConfigService) {
+        Util.setRuleEngineConfigService(ruleEngineConfigService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRuleEngineConfigService(RuleEngineConfigService ruleEngineConfigService) {
+        Util.setRuleEngineConfigService(null);
+    }
+
+    protected void setTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.addTenantMgtListenerService(tenantMgtListener);
+    }
+
+    protected void unsetTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.removeTenantMgtListenerService(tenantMgtListener);
+    }
+
+    protected void setDataSourceService(DataSourceService dataSourceService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the Data Sources Service");
+        }
+        Util.setDataSourceService(dataSourceService);
+    }
+
+    protected void unsetDataSourceService(DataSourceService dataSourceService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Data Sources Service");
+        }
+        Util.setDataSourceService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/Util.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
new file mode 100644
index 0000000..b6a0951
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
@@ -0,0 +1,132 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.billing.core.internal;
+
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.DataAccessManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.ndatasource.core.DataSourceService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.rule.kernel.config.RuleEngineConfigService;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class Util {
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static RuleEngineConfigService ruleEngineConfigService;
+    private static List<TenantMgtListener> tenantMgtListeners = new ArrayList<TenantMgtListener>();
+    private static DataAccessManager dataAccessManager;
+    private static DataSourceService dataSourceService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService(){
+        return Util.realmService;
+    }
+
+    public static void setRuleEngineConfigService(RuleEngineConfigService ruleServerManagerService) {
+        Util.ruleEngineConfigService = ruleServerManagerService;
+    }
+
+    public static RuleEngineConfigService getRuleEngineConfigService() {
+        return Util.ruleEngineConfigService;
+    }
+
+    public static void initBillingManager(BundleContext bundleContext) throws BillingException {
+        // load the configuration and initialize the billing engine + do the
+        // necessary scheduling.
+        String configFile =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator + BillingConstants.BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+
+        bundleContext.registerService(BillingManager.class.getName(), billingManager, null);
+    }
+    
+    public static void initDataAccessManager() throws BillingException{
+        Util.dataAccessManager = new DataAccessManager(BillingManager.getInstance().getDataAccessObject());
+    }
+
+    public static DataAccessManager getDataAccessManager(){
+        return dataAccessManager;
+    }
+
+    public static void cleanBillingManager() {
+        BillingManager.destroyInstance();
+    }
+    
+    public static void addTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.add(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void removeTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.remove(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void setDataSourceService(DataSourceService service) {
+        if (dataSourceService == null) {
+            dataSourceService = service;
+        }
+    }
+
+    public static DataSourceService getDataSourceService(){
+        return dataSourceService;
+    }
+
+    private static void sortTenantMgtListeners() {
+        Collections.sort(tenantMgtListeners, new Comparator<TenantMgtListener>() {
+            public int compare(TenantMgtListener o1, TenantMgtListener o2) {
+                return o1.getListenerOrder() - o2.getListenerOrder();
+            }
+        });
+    }
+
+    public static void alertTenantSubscriptionPlanChange(int tenantId, String oldSubscriptionPlan, 
+                                          String newSubscriptionPlan) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onSubscriptionPlanChange(
+                    tenantId, oldSubscriptionPlan, newSubscriptionPlan);
+        }
+    }
+}


[48/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
new file mode 100644
index 0000000..f30ab9a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AutoscaleDeciderCallable.java
@@ -0,0 +1,242 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.state.check.TerminatingInstancesStateChecker;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+/** Take auto-scaling decisions for each service domain, sub domain combination **/
+public class AutoscaleDeciderCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AutoscaleDeciderCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    private String clusterStr;
+    
+    public AutoscaleDeciderCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        clusterStr = AutoscaleUtil.domainSubDomainString(domain, subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        // expire tokens
+        if (appDomainContext != null) {
+            appDomainContext.expireRequestTokens();
+
+            serviceConfig = appDomainContext.getServiceConfig();
+
+            appDomainContext.recordRequestTokenListLength();
+            if (!appDomainContext.canMakeScalingDecision()) {
+                return true;
+            }
+
+            long average = appDomainContext.getAverageRequestsInFlight();
+            int runningAppInstances = appDomainContext.getRunningInstanceCount();
+            int terminatingAppInstances = appDomainContext.getTerminatingInstanceCount();
+
+            int maxRPS = serviceConfig.getMaxRequestsPerSecond();
+            double taskInterval =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getWholeLoadBalancerConfig()
+                    .getLoadBalancerConfig()
+                    .getAutoscalerTaskInterval() / (double)1000;
+            double aur = serviceConfig.getAlarmingUpperRate();
+            double alr = serviceConfig.getAlarmingLowerRate();
+            double scaleDownFactor = serviceConfig.getScaleDownFactor();
+
+            // scale up early
+            double maxhandleableReqs = maxRPS * taskInterval * aur;
+            // scale down slowly
+            double minhandleableReqs = maxRPS * taskInterval * alr * scaleDownFactor;
+
+            if (log.isDebugEnabled()) {
+                log.debug(clusterStr +": Average requests in flight: " + average + " **** Handleable requests: " +
+                    (runningAppInstances * maxhandleableReqs));
+            }
+            if (average > (runningAppInstances * maxhandleableReqs) && maxhandleableReqs > 0) {
+                
+                // estimate number of instances we might want to spawn
+                int requiredInstances = (int) Math.ceil(average/maxhandleableReqs);
+                
+                log.debug(clusterStr+" : Required instance count: "+requiredInstances);
+                
+                // current average is higher than that can be handled by current nodes.
+                scaleUp(requiredInstances - runningAppInstances);
+            } else if (terminatingAppInstances == 0 && average < ((runningAppInstances - 1) * minhandleableReqs)) {
+                // current average is less than that can be handled by (current nodes - 1).
+                scaleDown();
+            }
+        }
+
+        return true;
+    }
+
+    private void scaleDown() {
+
+        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int terminatingInstances = appDomainContext.getTerminatingInstanceCount();
+        int minAppInstances = serviceConfig.getMinAppInstances();
+//        int serverStartupDelay = AutoscalerTaskDSHolder
+//                                            .getInstance()
+//                                            .getWholeLoadBalancerConfig()
+//                                            .getLoadBalancerConfig()
+//                                            .getServerStartupDelay();
+
+        if ( (runningInstances - terminatingInstances) > minAppInstances) {
+
+            if (log.isDebugEnabled()) {
+                log.debug("Scale Down - " +
+                    clusterStr +
+                        ". Running instances:" +
+                        runningInstances +
+                        ". Terminating instances: " +
+                        terminatingInstances +
+                        ". Min instances:" +
+                        minAppInstances);
+            }
+            // ask to scale down
+            try {
+                if (client.terminateInstance(domain, subDomain)) {
+                    
+                    Thread th = new Thread(new TerminatingInstancesStateChecker(appDomainContext, domain, subDomain));
+                    th.start();
+                    
+//                        log.debug(clusterStr +": There's an instance who's in shutting down state " +
+//                            "(but still not left ELB), hence we should wait till " +
+//                            "it leaves the cluster.");
+//
+//                        int totalWaitedTime = 0;
+//
+//                        log.debug(clusterStr +": Task will wait maximum of (milliseconds) : " +
+//                            serverStartupDelay +
+//                                ", to let the member leave the cluster.");
+//                        
+//                        // for each sub domain, get the clustering group management agent
+//                        GroupManagementAgent agent =
+//                            AutoscalerTaskDSHolder.getInstance().getAgent()
+//                                .getGroupManagementAgent(domain,
+//                                    subDomain);
+//
+//                        // we give some time for the server to be terminated, we'll check time to time
+//                        // whether the instance has actually left the cluster.
+//                        while (agent.getMembers().size() == runningInstances &&
+//                            totalWaitedTime < serverStartupDelay) {
+//
+//                            try {
+//                                Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+//                            } catch (InterruptedException ignore) {
+//                            }
+//
+//                            totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+//                        }
+//
+//                        log.debug(clusterStr+ " : task waited for (milliseconds) : " + totalWaitedTime);
+//
+//                        // we recalculate number of alive instances
+//                        runningInstances = agent.getMembers().size();
+//                        
+//                        appDomainContext.setRunningInstanceCount(runningInstances);
+//
+//                        log.debug(clusterStr+" : New running instance count: " + runningInstances);
+                }
+
+            } catch (Exception e) {
+                log.error("Instance termination failed for " + clusterStr, e);
+            }
+        }
+
+    }
+
+    private void scaleUp(int requiredInstanceCount) {
+
+        int maxAppInstances = serviceConfig.getMaxAppInstances();
+//        int instancesPerScaleUp = serviceConfig.getInstancesPerScaleUp();
+//        int runningInstances = appDomainContext.getRunningInstanceCount();
+//        int pendingInstances = appDomainContext.getPendingInstanceCount();
+        int totalInstanceCount = appDomainContext.getInstances();
+        
+        log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Total Running/Pending instance count: "+totalInstanceCount);
+        
+        if(maxAppInstances > totalInstanceCount){
+            
+            int availableQuotaOfInstances = maxAppInstances - totalInstanceCount;
+            
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain)+ " - Available Quota of Instances: "+availableQuotaOfInstances);
+            
+            requiredInstanceCount = requiredInstanceCount <= availableQuotaOfInstances ? requiredInstanceCount : availableQuotaOfInstances;
+            
+            log.debug(clusterStr + " - Going to start " +
+                    requiredInstanceCount + " instance/s.");
+
+                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+                    requiredInstanceCount);
+                
+        } else if (totalInstanceCount > maxAppInstances) {
+            log.fatal("Number of running instances has over reached the maximum limit of " +
+                maxAppInstances + " of " + clusterStr);
+        }
+
+//        int failedInstances = 0;
+//        if (runningInstances < maxAppInstances && pendingInstances == 0) {
+//
+//            log.debug(clusterStr + " - Going to start " +
+//                    requiredInstanceCount + " instance/s. Running instances:" + runningInstances);
+//
+//                AutoscaleUtil.runInstances(client, appDomainContext, domain, subDomain,
+//                    requiredInstanceCount);
+
+//            if (successfullyStarted != instancesPerScaleUp) {
+//                failedInstances = instancesPerScaleUp - successfullyStarted;
+//                if (log.isDebugEnabled()) {
+//                    log.debug(successfullyStarted +
+//                        " instances successfully started and\n" + failedInstances +
+//                        " instances failed to start for " + clusterStr);
+//                }
+//            }
+//
+//            // we increment the pending instance count
+//            // appDomainContext.incrementPendingInstances(instancesPerScaleUp);
+//            else {
+//                log.debug("Successfully started " + successfullyStarted +
+//                    " instances of " + clusterStr);
+//            }
+
+       
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
new file mode 100644
index 0000000..580db58
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/InstanceCountCallable.java
@@ -0,0 +1,77 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.callables;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+
+/** Calculate instances of each service domain, sub domain combination **/
+public class InstanceCountCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(InstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appCtxt;
+    private ExecutorService executor = Executors.newFixedThreadPool(10);
+    
+    public InstanceCountCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appCtxt = appCtxt;
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+        log.debug("Computation of instance counts started for domain: " + this.domain +
+            " and sub domain: " + this.subDomain);
+
+        Callable<Integer> worker = new RunningInstanceCountCallable(this.domain, this.subDomain);
+        Future<Integer> runningInstanceCount = executor.submit(worker);
+
+//        worker = new PendingInstanceCountCallable(this.domain, this.subDomain, client);
+//        Future<Integer> pendingInstanceCount = executor.submit(worker);
+
+        int runningInstances = 0, pendingInstances = 0;
+        if (appCtxt != null) {
+
+            try {
+                // get the values of Callables
+                runningInstances = runningInstanceCount.get();
+                pendingInstances = appCtxt.getPendingInstanceCount();
+            } catch (Exception e) {
+                // no need to throw
+                log.error(e.getMessage(), e);
+            }
+
+            appCtxt.setRunningInstanceCount(runningInstances);
+            appCtxt.setPendingInstanceCount(pendingInstances);
+            
+        }
+        return true;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
new file mode 100644
index 0000000..bf3f336
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/PendingInstanceCountCallable.java
@@ -0,0 +1,64 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+
+/** Calculate pending instances of each service domain, sub domain combination **/
+public class PendingInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(PendingInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    
+    public PendingInstanceCountCallable(String domain, String subDomain, CloudControllerClient client){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int pendingInstanceCount = 0;
+
+        try {
+            pendingInstanceCount =
+                client.getPendingInstanceCount(this.domain,
+                    this.subDomain);
+
+        } catch (Exception e) {
+            log.error("Failed to retrieve pending instance count for domain: " +
+                this.domain + " and sub domain: " + this.subDomain, e);
+        }
+
+        log.debug("Pending instance count for domain: " +
+            this.domain +
+            ", sub domain: " +
+            this.subDomain +
+            " is " +
+            pendingInstanceCount);
+
+        return pendingInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
new file mode 100644
index 0000000..7f151fb
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/RunningInstanceCountCallable.java
@@ -0,0 +1,67 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+/** Calculate running instances of each service domain, sub domain combination **/
+public class RunningInstanceCountCallable implements Callable<Integer> {
+
+    private static final Log log = LogFactory.getLog(RunningInstanceCountCallable.class);
+    private String domain;
+    private String subDomain;
+    
+    public RunningInstanceCountCallable(String domain, String subDomain){
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+    
+    @Override
+    public Integer call() throws Exception {
+        int runningInstances;
+        // for each sub domain, get the clustering group management agent
+        GroupManagementAgent agent =
+            AutoscalerTaskDSHolder.getInstance().getAgent()
+                .getGroupManagementAgent(this.domain,
+                    this.subDomain);
+
+        // if it isn't null
+        if (agent != null) {
+            // we calculate running instance count for this service domain
+            runningInstances = agent.getMembers().size();
+        } else {
+            // if agent is null, we assume no service instances are running
+            runningInstances = 0;
+        }
+
+        log.debug("Running instance count for domain: " +
+            this.domain +
+                ", sub domain: " +
+                this.subDomain +
+                " is " +
+                runningInstances);
+        
+        return runningInstances;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
new file mode 100644
index 0000000..8ca9764
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerClient.java
@@ -0,0 +1,65 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.clients;
+
+/**
+ * Each Implementation which provides access to Cloud Controller, should implement this interface.
+ */
+public abstract class CloudControllerClient {
+
+    /**
+     * Initializes the client.
+     */
+    public abstract void init();
+    
+    /**
+     * Should start an instance.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return Public IP of the spawned instance.
+     * @throws Exception 
+     */
+    public abstract String startInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates an instance belongs to the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Terminates lastly spawned instance of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return whether the termination is successful or not.
+     * @throws Exception
+     */
+    public abstract boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception;
+    
+    /**
+     * Return pending instance count of the given cluster.
+     * @param domainName clustering domain.
+     * @param subDomainName clustering sub domain.
+     * @return pending instance count.
+     * @throws Exception
+     */
+    public abstract int getPendingInstanceCount(String domainName, String subDomainName) throws Exception;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
new file mode 100644
index 0000000..e05c809
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerOsgiClient.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.clients;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerOsgiClient extends CloudControllerClient {
+
+    private CloudControllerService cloudControllerService;
+
+    private static final Log log = LogFactory.getLog(CloudControllerOsgiClient.class);
+
+    // public CloudControllerStubClient(String epr) throws AxisFault {
+    //
+    // try {
+    //
+    // stub = new CloudControllerServiceStub(epr);
+    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
+    //
+    // } catch (AxisFault axisFault) {
+    // String msg =
+    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+    // log.error(msg, axisFault);
+    // throw new AxisFault(msg, axisFault);
+    // }
+    // }
+
+    // public boolean init(boolean isSpi) throws Exception {
+    //
+    // return stub.initAutoscaler(isSpi);
+    // }
+
+    public String startInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.startInstance(domainName, subDomainName);
+    }
+
+    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateInstance(domainName, subDomainName);
+    }
+
+    public boolean
+        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.terminateLastlySpawnedInstance(domainName, subDomainName);
+    }
+
+    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+        return cloudControllerService.getPendingInstanceCount(domainName, subDomainName);
+    }
+
+    @Override
+    public void init() {
+
+        cloudControllerService = AutoscalerTaskDSHolder.getInstance().getCloudControllerService();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
new file mode 100644
index 0000000..09feb78
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/clients/CloudControllerStubClient.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceStub;
+
+/**
+ * This is the client class this calls Autoscaler service.
+ */
+public class CloudControllerStubClient extends CloudControllerClient {
+
+    private CloudControllerServiceStub stub;
+    private static final String CLOUD_CONTROLLER_EPR = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerServiceEpr();
+
+    private static final Log log = LogFactory.getLog(CloudControllerStubClient.class);
+
+    // public CloudControllerStubClient(String epr) throws AxisFault {
+    //
+    // try {
+    //
+    // stub = new CloudControllerServiceStub(epr);
+    // stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(90000);
+    //
+    // } catch (AxisFault axisFault) {
+    // String msg =
+    // "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+    // log.error(msg, axisFault);
+    // throw new AxisFault(msg, axisFault);
+    // }
+    // }
+
+    // public boolean init(boolean isSpi) throws Exception {
+    //
+    // return stub.initAutoscaler(isSpi);
+    // }
+
+    public String startInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.startInstance(domainName, subDomainName);
+    }
+
+    public boolean terminateInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.terminateInstance(domainName, subDomainName);
+    }
+
+    public boolean
+        terminateLastlySpawnedInstance(String domainName, String subDomainName) throws Exception {
+
+        return stub.terminateLastlySpawnedInstance(domainName, subDomainName);
+    }
+
+    public int getPendingInstanceCount(String domainName, String subDomainName) throws Exception {
+
+        return stub.getPendingInstanceCount(domainName, subDomainName);
+    }
+
+    @Override
+    public void init() {
+
+        try {
+
+            stub = new CloudControllerServiceStub(CLOUD_CONTROLLER_EPR);
+            stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RuntimeException(msg, axisFault);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
new file mode 100644
index 0000000..add198e
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/AppDomainContext.java
@@ -0,0 +1,169 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.context;
+
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+
+
+/**
+ * Contextual information related to autoscaling for a particular clustering domain
+ */
+public class AppDomainContext extends LoadBalancerContext{
+
+    private static final long serialVersionUID = 6582721801663800609L;
+
+    private static final Log log = LogFactory.getLog(AppDomainContext.class);
+
+    /**
+     * Request tokens of requests in flight
+     * <p/>
+     * Key - request token ID, Value - message received time
+     */
+    private Map<String, Long> requestTokens = new ConcurrentHashMap<String, Long>();
+    private List<Integer> requestTokenListLengths;
+    private LoadBalancerConfiguration.ServiceConfiguration serviceConfig;
+
+    public AppDomainContext(LoadBalancerConfiguration.ServiceConfiguration serviceConfig) {
+        this.serviceConfig = serviceConfig;
+        requestTokenListLengths = new Vector<Integer>(serviceConfig.getRoundsToAverage());
+    }
+
+    public LoadBalancerConfiguration.ServiceConfiguration getServiceConfig() {
+        return serviceConfig;
+    }
+
+    /**
+     * If there is insufficient number of messages we cannot make a scaling decision.
+     *
+     * @return true - if a scaling decision can be made
+     */
+    public boolean canMakeScalingDecision() {
+        return requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage();
+    }
+
+    public void addRequestToken(String tokenId) {
+        requestTokens.put(tokenId, System.currentTimeMillis());
+        if (log.isDebugEnabled()) {
+            log.debug("Request Tokens Added : "+requestTokens.size());
+        }
+    }
+
+    public void removeRequestToken(String tokenId) {
+        requestTokens.remove(tokenId);
+    }
+
+//    public int getRunningInstanceCount() {
+//        return super.getRunningInstanceCount();
+//    }
+
+    /**
+     * This will set the running instance count for this app domain
+     * and also will return the difference of current running instance count and previous count.
+     * @param runningInstanceCount current running instance count
+     * @return difference of current running instance count and previous count.
+     */
+//    public int setRunningInstanceCount(int runningInstanceCount) {
+//        int diff = 0;
+//        
+//        if(this.runningInstanceCount < runningInstanceCount){
+//            diff = runningInstanceCount - this.runningInstanceCount;
+//        }
+//        
+//        this.runningInstanceCount = runningInstanceCount;
+//        
+//        return diff;
+//    }
+
+    public void expireRequestTokens() {
+        for (Map.Entry<String, Long> entry : requestTokens.entrySet()) {
+            if (System.currentTimeMillis() - entry.getValue() >= serviceConfig.getMessageExpiryTime()) {
+                requestTokens.remove(entry.getKey());
+                if (log.isDebugEnabled()) {
+                    log.debug("Request Tokens Expired : " + requestTokens.get(entry.getKey()));
+                }
+            }
+        }
+    }
+
+    public void recordRequestTokenListLength() {
+        if (requestTokenListLengths.size() >= serviceConfig.getRoundsToAverage()) {
+            int count = requestTokenListLengths.remove(0);
+            if (log.isDebugEnabled()) {
+                log.debug("Request Tokens Removed : " + count);
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Request Tokens Added : " + requestTokens.size());
+        }
+        requestTokenListLengths.add(requestTokens.size());
+    }
+
+
+//    public synchronized int getPendingInstances() {
+//        return pendingInstances;
+//    }
+
+//    public synchronized void incrementPendingInstances() {
+//        this.pendingInstances++;
+//    }
+
+//    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+//        
+//        while (diff > 0 && this.pendingInstances > 0 ){
+//            this.pendingInstances--;
+//            diff--;
+//        }
+//        
+//    }
+    
+//    public synchronized int getInstances() {
+//        return runningInstanceCount + pendingInstances;
+//    }
+
+    /**
+     * Get the average requests in flight, averaged over the number of  of observations rounds
+     *
+     * @return number of average requests in flight. -1 if there no requests were received
+     */
+    public long getAverageRequestsInFlight() {
+        long total = 0;
+        for (Integer messageQueueLength : requestTokenListLengths) {
+            total += messageQueueLength;
+        }
+        int size = requestTokenListLengths.size();
+        if (size == 0) {
+            return -1; // -1 means that no requests have been received
+        }
+        
+        if (log.isDebugEnabled()) {
+            log.debug("Total Tokens : "+total+ " : Size: "+size);
+        }
+        return (long) total / size;
+    }
+
+
+//    public synchronized void resetRunningPendingInstances() {
+//        pendingInstances = 0;
+//        runningInstanceCount = 0;
+//    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
new file mode 100644
index 0000000..d7f7993
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/context/LoadBalancerContext.java
@@ -0,0 +1,103 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.context;
+
+import java.io.Serializable;
+
+/**
+ * Contextual information related to autoscaling for a particular domain
+ */
+public class LoadBalancerContext implements Serializable{
+
+    private static final long serialVersionUID = -2022110665957598060L;
+    private int runningInstances;
+    private int pendingInstances;
+    private int terminatingInstances;
+    
+    public synchronized int getTerminatingInstanceCount() {
+        return terminatingInstances;
+    }
+    
+    public synchronized int getRunningInstanceCount() {
+        return runningInstances;
+    }
+    
+    public synchronized int getPendingInstanceCount() {
+        return pendingInstances;
+    }
+
+    /**
+     * This will set the running instance count for a domain
+     * and also will return the difference of current running instance count and previous count.
+     * @param runningInstanceCount current running instance count
+     * @return difference of current running instance count and previous count.
+     */
+    public synchronized int setRunningInstanceCount(int count) {
+        int diff = 0;
+
+        if (this.runningInstances < count) {
+            diff = count - this.runningInstances;
+        }
+
+        this.runningInstances = count;
+
+        return diff;
+    }
+
+    public synchronized int getInstances() {
+        return runningInstances + pendingInstances;
+    }
+    
+    public synchronized void setPendingInstanceCount(int count) {
+        
+        this.pendingInstances = count;
+    }
+    
+    public synchronized void setTerminatingInstanceCount(int count) {
+        
+        this.terminatingInstances = count;
+    }
+
+    public synchronized void incrementPendingInstances(int diff) {
+
+        this.pendingInstances += diff;
+    }
+    
+    public synchronized void incrementTerminatingInstances(int diff) {
+
+        this.terminatingInstances += diff;
+    }
+    
+    public synchronized void decrementPendingInstancesIfNotZero(int diff) {
+
+        while (diff > 0 && this.pendingInstances > 0) {
+            this.pendingInstances--;
+            diff--;
+        }
+
+    }
+    
+    public synchronized void decrementTerminatingInstancesIfNotZero(int diff) {
+
+        while (diff > 0 && this.terminatingInstances > 0) {
+            this.terminatingInstances--;
+            diff--;
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
new file mode 100644
index 0000000..eec09fa
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/AutoscalerTaskServiceComponent.java
@@ -0,0 +1,328 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.internal;
+
+import java.util.Date;
+import java.util.Map;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.Mediator;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.mediators.base.SequenceMediator;
+import org.apache.synapse.mediators.filters.InMediator;
+import org.apache.synapse.mediators.filters.OutMediator;
+import org.apache.synapse.task.Task;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.quartz.JobBuilder;
+import org.quartz.JobDetail;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.mediators.AutoscaleInMediator;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.mediators.AutoscaleOutMediator;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalerTaskInitializer;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalerTaskMgmtAdminService;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.task.AutoscalingJob;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.task.ServiceRequestsInFlightAutoscaler;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.task.TaskSchedulingManager;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="autoscaler.task.component" immediate="true"
+ * @scr.reference name="carbon.core.configurationContextService"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="1..1" policy="dynamic"
+ * bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ * @scr.reference name="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="org.wso2.carbon.lb.common"
+ * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ * @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="org.wso2.carbon.stratos.cloud.controller"
+ * interface="org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService"
+ * cardinality="1..1" policy="dynamic" bind="setCloudControllerService"
+ * unbind="unsetCloudControllerService"
+ */
+public class AutoscalerTaskServiceComponent {
+
+    private static final Log log = LogFactory.getLog(AutoscalerTaskServiceComponent.class);
+    private ConfigurationContext configurationContext = null;
+
+    protected void activate(ComponentContext context) {
+    	
+    	try{
+
+        // read config file
+//        String configURL = System.getProperty(AutoscaleConstants.LOAD_BALANCER_CONFIG);
+//        LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration();
+//        lbConfig.init(configURL);
+        
+        if(configurationContext == null){
+            String msg = "Configuration context is null. Autoscaler task activation failed.";
+            log.fatal(msg);
+            throw new RuntimeException(msg);
+        }
+
+        // load synapse environment
+        Parameter synEnv =
+                configurationContext.getAxisConfiguration().getParameter(SynapseConstants.SYNAPSE_ENV);
+
+        if (synEnv == null || synEnv.getValue() == null ||
+                !(synEnv.getValue() instanceof SynapseEnvironment)) {
+
+            String message = "Unable to initialize the Synapse Configuration : Can not find the ";
+            log.fatal(message + "Synapse Environment");
+            throw new SynapseException(message + "Synapse Environment");
+        }
+
+        SynapseEnvironment synapseEnv = (SynapseEnvironment) synEnv.getValue();
+
+        /** Initializing autoscaleIn and autoscaleOut Mediators.**/
+
+        LoadBalancerConfiguration lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+        // check whether autoscaling is enabled
+        if (lbConfig.getLoadBalancerConfig().isAutoscaleEnabled()) {
+
+            // get the main sequence mediator
+            SequenceMediator mainSequence =
+                    (SequenceMediator) synapseEnv.getSynapseConfiguration().getSequence("main");
+
+            // iterate through its child mediators
+            for (Mediator child : mainSequence.getList()) {
+
+                // find the InMediator
+                if (child instanceof InMediator) {
+                    InMediator inSequence = (InMediator) child;
+
+                    // if the first child of InMediator isn't an AutoscaleInMediator
+                    if (!(inSequence.getList().get(0) instanceof AutoscaleInMediator)) {
+
+                        // we gonna add it!
+                        inSequence.getList().add(0, new AutoscaleInMediator());
+                        if (log.isDebugEnabled()) {
+                            log.debug("Added Mediator: " + inSequence.getChild(0) + "" +
+                                    " to InMediator. Number of child mediators in InMediator" + " is " +
+                                    inSequence.getList().size() + ".");
+                        }
+                    }
+
+                }
+
+                // find the OutMediator
+                if (child instanceof OutMediator) {
+
+                    OutMediator outSequence = (OutMediator) child;
+
+                    // if the first child of OutMediator isn't an AutoscaleOutMediator
+                    if (!(outSequence.getList().get(0) instanceof AutoscaleOutMediator)) {
+
+                        // we gonna add it!
+                        outSequence.getList().add(0, new AutoscaleOutMediator());
+
+                        if (log.isDebugEnabled()) {
+                            log.debug("Added Mediator: " + outSequence.getChild(0) + "" +
+                                    " to OutMediator. Number of child mediators in OutMediator" +
+                                    " is " + outSequence.getList().size() + ".");
+                        }
+
+                    }
+                }
+            }
+
+            /** Initializing Autoscaler Task **/
+
+            BundleContext bundleContext = context.getBundleContext();
+            if (log.isDebugEnabled()) {
+                log.debug("Initiating Autoscaler task service component");
+            }
+
+            if (bundleContext.getServiceReference(TaskManagementService.class.getName()) != null) {
+                bundleContext.registerService(TaskManagementService.class.getName(),
+                        new AutoscalerTaskMgmtAdminService(), null);
+            }
+
+
+            AutoscalerTaskInitializer listener = new AutoscalerTaskInitializer();
+
+            if (bundleContext.getServiceReference(Axis2ConfigurationContextObserver.class.getName()) != null) {
+                bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
+                        listener, null);
+            }
+
+            if (configurationContext != null) {
+                TaskScheduler scheduler =
+                        (TaskScheduler) configurationContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+                if (scheduler == null) {
+                    scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+                    scheduler.init(null);
+                    configurationContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER,
+                            scheduler);
+                } else if (!scheduler.isInitialized()) {
+                    scheduler.init(null);
+                }
+            }
+            
+            String autoscalerClass = lbConfig.getLoadBalancerConfig().getAutoscalerTaskClass();
+            Task task;
+            if (autoscalerClass != null) {
+                try {
+                    task = (Task) Class.forName(autoscalerClass).newInstance();
+                } catch (Exception e) {
+                    String msg = "Cannot instantiate Autoscaling Task. Class: " + autoscalerClass
+                    		+". It should implement 'org.apache.synapse.task.Task' and "
+                    		+"'org.apache.synapse.ManagedLifecycle' interfaces.";
+                    log.error(msg, e);
+                    throw new RuntimeException(msg, e);
+                }
+            } else {
+                task = new ServiceRequestsInFlightAutoscaler();
+            }
+
+//            ServiceRequestsInFlightAutoscaler autoscalerTask =
+//                    new ServiceRequestsInFlightAutoscaler();
+
+            ((ManagedLifecycle) task).init(synapseEnv);
+
+            // specify scheduler task details
+            JobBuilder jobBuilder = JobBuilder.newJob(AutoscalingJob.class)
+                .withIdentity("autoscalerJob");
+            JobDetail job = jobBuilder.build();
+
+            Map<String, Object> dataMap = job.getJobDataMap();
+            dataMap.put(AutoscalingJob.AUTOSCALER_TASK, task);
+            dataMap.put(AutoscalingJob.SYNAPSE_ENVI, synapseEnv);
+
+            final TaskDescription taskDescription = new TaskDescription();
+            taskDescription.setTaskClass(ServiceRequestsInFlightAutoscaler.class.getName());
+            taskDescription.setName("autoscaler");
+            //taskDescription.setCount(SimpleTrigger.REPEAT_INDEFINITELY);
+
+            int interval = AutoscalerTaskDSHolder.getInstance().getLoadBalancerConfig().getAutoscalerTaskInterval();
+            taskDescription.setInterval(interval);
+            taskDescription.setStartTime(new Date(System.currentTimeMillis() + (interval*2)));
+
+            TaskSchedulingManager scheduler = new TaskSchedulingManager();
+            scheduler.scheduleTask(taskDescription, dataMap, configurationContext);
+
+
+        } else {
+
+            log.info("Autoscaling is disabled.");
+        }
+    	} catch (Throwable e) {
+            log.error("Failed to activate Autoscaler Task Service Component. ", e);
+        }
+    }
+
+
+    protected void deactivate(ComponentContext ctx) {
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+        if (log.isDebugEnabled()) {
+            log.debug("Autoscaler task bundle is deactivated");
+        }
+    }
+
+	protected void setCloudControllerService(CloudControllerService cc) {
+        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(cc);
+    }
+    
+    protected void unsetCloudControllerService(CloudControllerService cc) {
+        AutoscalerTaskDSHolder.getInstance().setCloudControllerService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService context) {
+        if (log.isDebugEnabled()) {
+            log.debug("ConfigurationContextService bound to the Autoscaler task initialization process");
+        }
+        this.configurationContext = context.getServerConfigContext();
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(context);
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
+        if (log.isDebugEnabled()) {
+            log.debug("ConfigurationContextService unbound from the Autoscaler task");
+        }
+        this.configurationContext = null;
+        AutoscalerTaskDSHolder.getInstance().setConfigurationContextService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Bound realm service from the Autoscaler task");
+        }
+        AutoscalerTaskDSHolder.getInstance().setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unbound realm service from the Autoscaler task");
+        }
+        AutoscalerTaskDSHolder.getInstance().setRealmService(null);
+    }
+    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        AutoscalerTaskDSHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        AutoscalerTaskDSHolder.getInstance().setLbConfigService(null);
+    }
+    
+    protected void setRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService bound to the endpoint component");
+        }
+        try {
+            AutoscalerTaskDSHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+            AutoscalerTaskDSHolder.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");
+        }
+        AutoscalerTaskDSHolder.getInstance().setConfigRegistry(null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
new file mode 100644
index 0000000..8442bcc
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/internal/RegistryManager.java
@@ -0,0 +1,51 @@
+/*
+ *  Copyright WSO2 Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+import org.wso2.carbon.lb.common.util.DomainMapping;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+public class RegistryManager {
+    UserRegistry governanceRegistry = AutoscalerTaskDSHolder.getInstance().getGovernanceRegistry();
+    private static final Log log = LogFactory.getLog(RegistryManager.class);
+    /**
+     *
+     */
+    private Resource resource = null;
+    public static final String HOST_INFO = "hostinfo/";
+    public static final String ACTUAL_HOST = "actual.host";
+
+    public DomainMapping getMapping(String hostName) {
+        DomainMapping domainMapping;
+        try {
+            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
+                resource = governanceRegistry.get(HOST_INFO + hostName);
+                domainMapping = new DomainMapping(hostName);
+                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
+                return domainMapping;
+            }
+        } catch (RegistryException e) {
+            log.info("Error while getting registry resource");
+            throw new RuntimeException(e);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
new file mode 100644
index 0000000..ea0138a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleInMediator.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.http.protocol.HTTP;
+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;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.cache.URLMappingCache;
+import org.wso2.carbon.lb.common.util.DomainMapping;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.internal.RegistryManager;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator generates a token per request received. These tokens are used for tracking
+ * the number of requests in flight. Once a response is received, the relevant token will be removed
+ * by the {@link AutoscaleOutMediator}
+ *
+ * @see AutoscaleOutMediator
+ */
+public class AutoscaleInMediator extends AbstractMediator implements ManagedLifecycle {
+
+    private LoadBalancerConfiguration lbConfig;
+    private Map<String, HostContext> hostCtxts;
+    /**
+     * keep the size of cache which used to keep hostNames of url mapping.
+     */
+    private URLMappingCache mappingCache;
+    private RegistryManager registryManager;
+    private int sizeOfCache;
+
+    public AutoscaleInMediator() {
+
+        this.lbConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+        hostCtxts = lbConfig.getHostContextMap();
+        sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
+        mappingCache = URLMappingCache.getInstance(sizeOfCache);
+    }
+
+    public boolean mediate(MessageContext synCtx) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("Mediation started .......... " + AutoscaleInMediator.class.getName());
+
+        }
+
+        ConfigurationContext configCtx =
+                                         ((Axis2MessageContext) synCtx).getAxis2MessageContext()
+                                                                       .getConfigurationContext();
+        String uuid = org.apache.axiom.util.UIDGenerator.generateUID();
+        synCtx.setProperty(AutoscaleConstants.REQUEST_ID, uuid);
+
+        Map<String, Map<String, ?>> appDomainContexts =
+                                                                       AutoscaleUtil.getAppDomainContexts(configCtx,
+                                                                                                          lbConfig);
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
+                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
+        
+        String toAddress = synCtx.getTo().getAddress();
+        if (targetHost.contains(":")) {
+            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
+        }
+
+        int tenantId = AutoscaleUtil.getTenantId(synCtx.getTo().toString());
+
+        String domain = null, subDomain = null;
+        
+        log.debug("************ Target Host: "+targetHost + " -- Tenant id : "+tenantId);
+
+        HostContext ctxt = hostCtxts.get(targetHost);
+        
+        if (ctxt == null) {
+
+            DomainMapping domainMapping = mappingCache.getMapping(targetHost);
+            if (domainMapping == null) {
+                registryManager = new RegistryManager();
+                domainMapping = registryManager.getMapping(targetHost);
+                mappingCache.addValidMapping(targetHost, domainMapping);
+            }
+            if (domainMapping != null) {
+
+                String actualHost = domainMapping.getActualHost();
+
+                // get the HostContext from the actual host name in the case of domain 
+                // mapping.
+                ctxt = hostCtxts.get(actualHost);
+
+            }
+        }
+
+        if (ctxt == null) {
+            log.debug("Host Context is null.");
+        	// we don't need to do anything 
+        	return true;
+        }
+
+
+        // gets the corresponding domain
+        domain = ctxt.getDomainFromTenantId(tenantId);
+        synCtx.setProperty(AutoscaleConstants.TARGET_DOMAIN, domain);
+
+        // gets the corresponding sub domain
+        subDomain = ctxt.getSubDomainFromTenantId(tenantId);
+        synCtx.setProperty(AutoscaleConstants.TARGET_SUB_DOMAIN, subDomain);
+
+        if (appDomainContexts.get(domain) == null) {
+            // if we do not find a correct context, we just ignore
+            log.debug("AppDomainContext not found for domain " + domain);
+
+        } else {
+            AppDomainContext appDomainContext = (AppDomainContext) appDomainContexts.get(domain).get(subDomain);
+
+            if (appDomainContext != null) {
+                appDomainContext.addRequestToken(uuid);
+                System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+
+            } else {
+                // if we do not find a correct context, we just ignore
+                log.debug("AppDomainContext not found for sub domain: " + subDomain +
+                          " of domain: " + domain);
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public void destroy() {
+
+        log.info("Mediator destroyed! " + AutoscaleInMediator.class.getName());
+    }
+
+    @Override
+    public void init(SynapseEnvironment arg0) {
+
+        if (log.isDebugEnabled()) {
+            log.debug("Mediator initialized! " + AutoscaleInMediator.class.getName());
+        }
+    }
+    
+    private void throwException(String msg){
+        log.error(msg);
+        throw new RuntimeException(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
new file mode 100644
index 0000000..c6f41ab
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/mediators/AutoscaleOutMediator.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.mediators;
+
+import org.apache.axis2.context.ConfigurationContext;
+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;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+
+import java.util.Map;
+
+/**
+ * This Synapse mediator removes the request token generated by the {@link AutoscaleInMediator}
+ * 
+ * @see AutoscaleInMediator
+ */
+public class AutoscaleOutMediator extends AbstractMediator implements ManagedLifecycle {
+
+    public boolean mediate(MessageContext synCtx) {
+
+        log.debug("Mediation started ....... " + AutoscaleOutMediator.class.getName());
+
+        ConfigurationContext configCtx =
+            ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
+
+        String domain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_DOMAIN);
+        // gets the corresponding sub domain
+        String subDomain = (String) synCtx.getProperty(AutoscaleConstants.TARGET_SUB_DOMAIN);
+        
+        String tokenId = (String) synCtx.getProperty(AutoscaleConstants.REQUEST_ID);
+        @SuppressWarnings("unchecked")
+        Map<String, Map<String, AppDomainContext>> appDomainContexts =
+            (Map<String, Map<String, AppDomainContext>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+        AppDomainContext appDomainContext = null ;
+        
+        if(appDomainContexts.get(domain) != null){
+        	appDomainContext = appDomainContexts.get(domain).get(subDomain);
+        }
+        
+        if (appDomainContext != null) {
+            appDomainContext.removeRequestToken(tokenId);
+            System.setProperty(AutoscaleConstants.IS_TOUCHED, "true");
+        } else {
+            log.debug("AppDomainContext not found for domain " + domain+" and sub domain : "+subDomain);
+        }
+        return true;
+    }
+
+    @Override
+    public void destroy() {
+        log.debug("Autoscale out mediator destroyed...");
+    }
+
+    @Override
+    public void init(SynapseEnvironment arg0) {
+        log.debug("Autoscale out mediator started...");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
new file mode 100644
index 0000000..0e84608
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/PendingInstancesStateChecker.java
@@ -0,0 +1,147 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+public class PendingInstancesStateChecker implements Runnable {
+    
+    private static final Log log = LogFactory.getLog(PendingInstancesStateChecker.class);
+    private LoadBalancerContext groupCtxt = null;
+    private String domain;
+    private String subDomain;
+    private int expectedIncrementOfinstanceCount, originalRunningInstanceCount;
+    private CloudControllerClient ccClient;
+    
+    public PendingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain,
+            int anexpectedInstanceCount, int currentCount, CloudControllerClient client) {
+        groupCtxt = ctxt;
+        domain = aDomain;
+        subDomain = aSubDomain;
+        expectedIncrementOfinstanceCount = anexpectedInstanceCount;
+        originalRunningInstanceCount = currentCount;
+        ccClient = client;
+    }
+
+    @Override
+    public void run() {
+
+        if (groupCtxt != null) {
+
+            int totalWaitedTime = 0;
+            int serverStartupDelay = AutoscalerTaskDSHolder
+                .getInstance()
+                .getWholeLoadBalancerConfig()
+                .getLoadBalancerConfig()
+                .getServerStartupDelay();
+
+            log.debug("Pending Instances State Checker has started for: " +
+                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+            // for each sub domain, get the clustering group management agent
+            GroupManagementAgent agent =
+                AutoscalerTaskDSHolder.getInstance().getAgent()
+                    .getGroupManagementAgent(domain,
+                        subDomain);
+            int startingRunningInstanceCount = agent.getMembers().size();
+
+            // we give some time for the server to get joined, we'll check time to time
+            // whether the instance has actually joined the ELB.
+            while ((agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) &&
+                totalWaitedTime < serverStartupDelay) {
+                int upToDateRunningInstanceCount = agent.getMembers().size();
+
+                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                    " - Number of current running instances " +
+                        upToDateRunningInstanceCount);
+
+                if (upToDateRunningInstanceCount > startingRunningInstanceCount) {
+                    int newlyJoinedInstanceCount = upToDateRunningInstanceCount - startingRunningInstanceCount;
+                    // set new running instance count
+                    groupCtxt.setRunningInstanceCount(upToDateRunningInstanceCount);
+                    // decrement the pending instance count
+                    groupCtxt.decrementPendingInstancesIfNotZero(newlyJoinedInstanceCount);
+                    // update the starting running instance count
+                    startingRunningInstanceCount = upToDateRunningInstanceCount;
+
+                    log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                        " - Instances newly joined: " +
+                            newlyJoinedInstanceCount);
+                }
+
+                try {
+                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+                } catch (InterruptedException ignore) {
+                }
+
+                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+            }
+
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+                totalWaitedTime +
+                " (milliseconds) till pending members get joined.");
+
+            if (agent.getMembers().size() < (originalRunningInstanceCount + expectedIncrementOfinstanceCount)) {
+
+                int instanceCountFailedToJoin =
+                    originalRunningInstanceCount + expectedIncrementOfinstanceCount - agent.getMembers().size();
+                log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                    "Instances that are failed to join: " +
+                        instanceCountFailedToJoin);
+
+                // to avoid an infinite loop
+                int retries = instanceCountFailedToJoin + 2;
+
+                while (instanceCountFailedToJoin > 0 && retries > 0) {
+                    // instances spawned haven't joined ELB, so we assume that instance is
+                    // corrupted.
+                    // hence, we ask CC to terminate it.
+                    try {
+                        log.debug("Terminating lastly spwaned instance of " +
+                            AutoscaleUtil.domainSubDomainString(domain, subDomain));
+                        ccClient.terminateLastlySpawnedInstance(domain, subDomain);
+                        instanceCountFailedToJoin--;
+                        // decrement pending count
+                        groupCtxt.decrementPendingInstancesIfNotZero(1);
+                    } catch (Exception e) {
+                        log
+                            .error(
+                                "Instance termination failed for " +
+                                    AutoscaleUtil.domainSubDomainString(domain, subDomain),
+                                e);
+                    } finally {
+                        retries--;
+                    }
+                }
+
+                // decrement pending count
+                groupCtxt.decrementPendingInstancesIfNotZero(instanceCountFailedToJoin);
+            }
+
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
new file mode 100644
index 0000000..3807f7b
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/state/check/TerminatingInstancesStateChecker.java
@@ -0,0 +1,88 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.state.check;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+public class TerminatingInstancesStateChecker implements Runnable {
+    
+    private static final Log log = LogFactory.getLog(TerminatingInstancesStateChecker.class);
+    private LoadBalancerContext groupCtxt = null;
+    private String domain;
+    private String subDomain;
+    
+    public TerminatingInstancesStateChecker(LoadBalancerContext ctxt, String aDomain, String aSubDomain) {
+        groupCtxt = ctxt;
+        domain = aDomain;
+        subDomain = aSubDomain;
+    }
+
+    @Override
+    public void run() {
+
+        if (groupCtxt != null) {
+
+            groupCtxt.incrementTerminatingInstances(1);
+            
+            int totalWaitedTime = 0;
+            int serverStartupDelay = AutoscalerTaskDSHolder
+                .getInstance()
+                .getWholeLoadBalancerConfig()
+                .getLoadBalancerConfig()
+                .getServerStartupDelay();
+            log.info("Terminating Instances State Checker has started for: " +
+                AutoscaleUtil.domainSubDomainString(domain, subDomain) + ". Check expiry time : " + serverStartupDelay);
+
+            // for each sub domain, get the clustering group management agent
+            GroupManagementAgent agent =
+                AutoscalerTaskDSHolder.getInstance().getAgent()
+                    .getGroupManagementAgent(domain,
+                        subDomain);
+
+            int startingRunningInstanceCount = agent.getMembers().size();
+
+            // we give some time for the server to be terminated, we'll check time to time
+            // whether the instance has actually left the cluster.
+            while (agent.getMembers().size() == startingRunningInstanceCount &&
+                totalWaitedTime < serverStartupDelay) {
+
+                try {
+                    Thread.sleep(AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME);
+                } catch (InterruptedException ignore) {
+                }
+
+                totalWaitedTime += AutoscaleConstants.INSTANCE_REMOVAL_CHECK_TIME;
+            }
+
+            log.debug(AutoscaleUtil.domainSubDomainString(domain, subDomain) + "- Waited for : " +
+                totalWaitedTime +
+                " (milliseconds) till terminating member left the cluster.");
+
+            // we recalculate number of alive instances
+            groupCtxt.decrementTerminatingInstancesIfNotZero(1);
+        }
+
+    }
+
+}


[05/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
new file mode 100644
index 0000000..dccd471
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/publisher/CartridgeInstanceDataPublisherTask.java
@@ -0,0 +1,476 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.publisher;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.databridge.agent.thrift.Agent;
+import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
+import org.wso2.carbon.databridge.agent.thrift.conf.AgentConfiguration;
+import org.wso2.carbon.databridge.commons.Event;
+import org.wso2.carbon.databridge.commons.exception.NoStreamDefinitionExistException;
+import org.wso2.carbon.ntask.core.Task;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInstanceData;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasContext;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.MapDifference.ValueDifference;
+import com.google.common.collect.Maps;
+
+public class CartridgeInstanceDataPublisherTask implements Task{
+    
+    private static final Log log = LogFactory.getLog(CartridgeInstanceDataPublisherTask.class);
+    private static DataPublisher dataPublisher;
+    private static String streamId;
+    private static final String cloudControllerEventStreamVersion = "1.0.0";
+    private static List<CartridgeInstanceData> dataToBePublished ;
+
+    protected enum NodeStatus {
+        PENDING, RUNNING, SUSPENDED, TERMINATED, ERROR, UNRECOGNIZED
+    };   
+
+    @Override
+    public void execute() {
+        
+        publish();
+    }
+    
+    public static void publish(){
+        if(FasterLookUpDataHolder.getInstance().isPublisherRunning() ||
+                // this is a temporary fix to avoid task execution - limitation with ntask
+                !FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
+            return;
+        }
+        
+        log.debug(CloudControllerConstants.DATA_PUB_TASK_NAME+" cycle started.");
+        FasterLookUpDataHolder.getInstance().setPublisherRunning(true);
+        dataToBePublished = new ArrayList<CartridgeInstanceData>();
+
+        if(dataPublisher==null){
+            createDataPublisher();
+
+            //If we cannot create a data publisher we should give up
+            //this means data will not be published
+            if(dataPublisher == null){
+                log.error("Data Publisher cannot be created or found.");
+                release();
+                return;
+            }
+        }
+
+        if(streamId == null){
+            try{
+                streamId = dataPublisher.findStream(CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM, cloudControllerEventStreamVersion);
+            }catch (NoStreamDefinitionExistException e){
+                log.info("Defining the event stream because it was not found in BAM");
+                try{
+                    defineStream();
+                } catch(Exception ex){
+                    String msg = "Error occurred while defining the event stream for publishing Cloud Controller data. " + ex.getMessage();
+                    log.error(msg, ex);
+                    //We do not want to proceed without an event stream. Therefore we return.
+                    release();
+                    return;
+                }
+            }catch (Exception exc){
+                log.error("Error occurred while searching for stream id. " + exc.getMessage(), exc);
+                //We do not want to proceed without an event stream. Therefore we return.
+                release();
+                return;
+            }
+        }
+        
+        // build the new node - state Map
+        Map<String, String> newNodeToStateMap;
+        try{
+            newNodeToStateMap = getNodeIdToStatusMap();
+        }catch (Exception e) {
+
+            release();
+            throw new CloudControllerException(e.getMessage(), e);
+            
+        } 
+        
+        // compare it with old map and populate data to be published with ones newly added
+        // and once whose state got changed
+        populateNewlyAddedOrStateChangedNodes(newNodeToStateMap);
+        
+        // issue events for the ones obtained from above
+        for (CartridgeInstanceData dataObj : dataToBePublished) {
+            StringBuffer temp = new StringBuffer("");
+            
+            String privateIpAddresses="";
+            // Concatenate private IP addresses
+            for (String ip : dataObj.getMetaData().getPrivateAddresses()) {
+                temp.append(ip+",");
+            }
+            
+            if(!"".equals(temp.toString())){
+                // remove comma at the end of the string
+                privateIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
+            }
+            
+            temp = new StringBuffer("");
+            String publicIpAddresses="";
+            // Concatenate public IP addresses
+            for (String ip : dataObj.getMetaData().getPublicAddresses()) {
+                temp.append(ip+",");
+            }
+            
+            if(!"".equals(temp.toString())){
+                // remove comma at the end of the string
+                publicIpAddresses = temp.toString().substring(0, temp.toString().length()-1);
+            }
+            
+            try {
+
+                Event cloudControllerEvent = new Event(streamId, System.currentTimeMillis(), new Object[]{}, null,
+                                            new Object[]{dataObj.getNodeId(),
+                                                         dataObj.getType(),
+                                                         dataObj.getDomain(),
+                                                         dataObj.getSubDomain(),
+                                                         dataObj.getAlias(),
+                                                         dataObj.getTenantRange(),
+                                                         String.valueOf(dataObj.isMultiTenant()),
+                                                         dataObj.getIaas(),
+                                                         dataObj.getStatus(),
+                                                         dataObj.getMetaData().getHostname(),
+                                                         dataObj.getMetaData().getHardware().getHypervisor(),
+                                                         String.valueOf(dataObj.getMetaData().getHardware().getRam()),
+                                                         dataObj.getMetaData().getImageId(),
+                                                         String.valueOf(dataObj.getMetaData().getLoginPort()),
+                                                         dataObj.getMetaData().getOperatingSystem().getName(),
+                                                         dataObj.getMetaData().getOperatingSystem().getVersion(),
+                                                         dataObj.getMetaData().getOperatingSystem().getArch(),
+                                                         String.valueOf(dataObj.getMetaData().getOperatingSystem().is64Bit()),
+                                                         privateIpAddresses,
+                                                         publicIpAddresses});
+
+                dataPublisher.publish(cloudControllerEvent);
+                
+                log.debug("Data published : "+cloudControllerEvent.toString());
+
+            } catch (Exception e) {
+                String msg = "Error occurred while publishing Cartridge instance event to BAM. ";
+                log.error(msg, e);
+                release();
+                throw new CloudControllerException(msg, e);
+            }
+            
+        }
+        
+        // replace old map with new one only if data is published
+        FasterLookUpDataHolder.getInstance().setNodeIdToStatusMap(newNodeToStateMap);
+        
+        //TODO remove
+//        CassandraDataRetriever.init();
+//        CassandraDataRetriever.connect();
+//        HiveQueryExecutor hive = new HiveQueryExecutor();
+//        hive.createHiveTable();
+//        System.out.println("***********");
+//        for (String str : hive.getRunningNodeIds()) {
+//         
+//            System.out.println(str);
+//        }
+//        System.out.println("***********");
+        release();
+    }
+    
+    private static void release(){
+        FasterLookUpDataHolder.getInstance().setPublisherRunning(false);
+    }
+    
+    private static void defineStream() throws Exception {
+        streamId = dataPublisher.
+                defineStream("{" +
+                        "  'name':'" + CloudControllerConstants.CLOUD_CONTROLLER_EVENT_STREAM +"'," +
+                        "  'version':'" + cloudControllerEventStreamVersion +"'," +
+                        "  'nickName': 'cloud.controller'," +
+                        "  'description': 'Instances booted up by the Cloud Controller '," +
+                        "  'metaData':[]," +
+                        "  'payloadData':[" +
+                        "          {'name':'"+CloudControllerConstants.NODE_ID_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.CARTRIDGE_TYPE_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.DOMAIN_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.SUB_DOMAIN_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.ALIAS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.TENANT_RANGE_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IS_MULTI_TENANT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IAAS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.STATUS_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.HOST_NAME_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.HYPERVISOR_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.RAM_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.IMAGE_ID_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.LOGIN_PORT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_NAME_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_VERSION_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_ARCH_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.OS_BIT_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.PRIV_IP_COL+"','type':'STRING'}," +
+                        "          {'name':'"+CloudControllerConstants.PUB_IP_COL+"','type':'STRING'}" +
+                        "  ]" +
+                        "}");
+        
+    }
+
+    @Override
+    public void init() {
+
+    	// this is a temporary fix to avoid task execution - limitation with ntask
+		if(!FasterLookUpDataHolder.getInstance().getEnableBAMDataPublisher()){
+			log.debug("BAM data publisher is disabled. ");
+			return;
+		}
+		
+        if((dataPublisher = FasterLookUpDataHolder.getInstance().getDataPublisher()) == null){
+            createDataPublisher();
+        }
+        streamId = FasterLookUpDataHolder.getInstance().getStreamId();
+        
+    }
+
+    @Override
+    public void setProperties(Map<String, String> arg0) {}
+    
+    private static void createDataPublisher(){
+        //creating the agent
+        AgentConfiguration agentConfiguration = new AgentConfiguration();
+
+        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
+        String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
+        String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
+        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
+        String adminUsername = FasterLookUpDataHolder.getInstance().getBamUsername();
+        String adminPassword = FasterLookUpDataHolder.getInstance().getBamPassword();
+
+        System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+        System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
+
+        Agent agent = new Agent(agentConfiguration);
+
+        try {
+            dataPublisher = new DataPublisher(bamServerUrl, adminUsername, adminPassword, agent);
+            FasterLookUpDataHolder.getInstance().setDataPublisher(dataPublisher);
+            
+        } catch (Exception e) {
+            String msg = "Unable to create a data publisher to " + bamServerUrl +
+                    ". Usage Agent will not function properly. ";
+            log.error(msg, e);
+            throw new CloudControllerException(msg, e);
+        }
+        
+    }
+    
+    private static void bundleData(String key, String val, ServiceContext serviceCtxt) {
+        
+        CartridgeInstanceData instanceData = new CartridgeInstanceData();
+        instanceData.setNodeId(key);
+        instanceData.setStatus(val);
+        instanceData.setDomain(serviceCtxt.getDomainName());
+        instanceData.setSubDomain(serviceCtxt.getSubDomainName());
+        instanceData.setAlias("".equals(serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY))
+            ? "NULL"
+                : serviceCtxt.getProperty(CloudControllerConstants.ALIAS_PROPERTY));
+        instanceData.setTenantRange("".equals(serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY))
+            ? serviceCtxt.getTenantRange()
+                : serviceCtxt.getProperty(CloudControllerConstants.TENANT_ID_PROPERTY));
+        
+        if (serviceCtxt.getCartridge() != null) {
+            instanceData.setMultiTenant(serviceCtxt.getCartridge().isMultiTenant());
+
+            for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+                IaasContext ctxt = null;
+                if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
+                    ctxt = serviceCtxt.addIaasContext(iaas.getType());
+                }
+
+                if (ctxt.didISpawn(key)) {
+                    instanceData.setIaas(iaas.getType());
+                    instanceData.setMetaData(ctxt.getNode(key));
+
+                    // clear to be removed data
+                    ctxt.removeToBeRemovedNodeId(key);
+
+                    // if the node is terminated
+                    if (val.equals(NodeStatus.TERMINATED.toString())) {
+                        // since this node is terminated
+                        FasterLookUpDataHolder.getInstance().removeNodeId(key);
+
+                        // remove node meta data
+                        ctxt.removeNodeMetadata(ctxt.getNode(key));
+                    }
+
+                    break;
+                }
+            }
+
+            instanceData.setType(serviceCtxt.getCartridge().getType());
+        } else {
+            log.warn("Cartridge is null for Service Context : (domain: " +
+                serviceCtxt.getDomainName() +
+                    ", sub domain: " +
+                    serviceCtxt.getSubDomainName() +
+                    ")");
+        }
+        
+        dataToBePublished.add(instanceData);
+        
+    }
+    
+    private static Map<String, String> getNodeIdToStatusMap() throws Exception {
+        
+        Map<String, String> statusMap = new HashMap<String, String>();
+        
+        // iterate through all ServiceContexts
+        for (Iterator<?> it1 = FasterLookUpDataHolder.getInstance().getServiceContexts().entrySet().iterator(); it1.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, Map<String, ServiceContext>> entry = (Map.Entry<String, Map<String, ServiceContext>>) it1.next();
+            
+            Map<String, ServiceContext> map = (Map<String, ServiceContext>) entry.getValue();
+            
+            for (Iterator<ServiceContext> it2 = map.values().iterator(); it2.hasNext();) {
+                ServiceContext subjectedSerCtxt = (ServiceContext) it2.next();
+                
+                if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridge() != null) {
+                    List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
+
+                    for (IaasProvider iaas : iaases) {
+
+                        ComputeService computeService = iaas.getComputeService();
+                        
+                        if(computeService == null){
+                            continue;
+                        }
+                        
+                        IaasContext ctxt = null;
+                        if((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null){
+                        	ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
+                        }
+
+                        // get list of node Ids
+                        List<String> nodeIds = ctxt.getAllNodeIds();
+
+                        if (nodeIds.isEmpty()) {
+                            
+                            continue;
+                        }
+                        
+                        try {
+
+                            // get all the nodes spawned by this IaasContext
+                            Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+                            Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+                            // traverse through all nodes of this ComputeService object
+                            while (iterator.hasNext()) {
+                                NodeMetadata nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+                                // if this node belongs to the requested domain
+                                if (nodeIds.contains(nodeMetadata.getId())) {
+
+                                    statusMap.put(nodeMetadata.getId(), nodeMetadata.getStatus()
+                                                                                    .toString());
+
+                                    ctxt.addNodeMetadata(nodeMetadata);
+                                }
+
+                            }
+
+                        }catch (Exception e) {
+                            log.error(e.getMessage(), e);
+                            throw e;
+                        }
+
+                    }
+                }
+            }
+            
+            
+        }
+        return statusMap;
+
+    }
+    
+    private static void populateNewlyAddedOrStateChangedNodes(Map<String, String> newMap){
+        
+        MapDifference<String, String> diff = Maps.difference(newMap, 
+                                                             FasterLookUpDataHolder.getInstance().getNodeIdToStatusMap());
+        
+        // adding newly added nodes
+        Map<String, String> newlyAddedNodes = diff.entriesOnlyOnLeft();
+        
+        for (Iterator<?> it = newlyAddedNodes.entrySet().iterator(); it.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
+            String key = entry.getKey();
+            String val = entry.getValue();
+            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
+            
+            log.debug("------ Node id: "+key+" --- node status: "+val+" -------- ctxt: "+ctxt);
+            
+            if (ctxt != null && key != null && val != null) {
+                // bundle the data to be published
+                bundleData(key, val, ctxt);
+            }   
+                    
+        }
+        
+        // adding nodes with state changes
+        Map<String, ValueDifference<String>> stateChangedNodes = diff.entriesDiffering();
+        
+        for (Iterator<?> it = stateChangedNodes.entrySet().iterator(); it.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map.Entry<String, ValueDifference<String>> entry = (Map.Entry<String, ValueDifference<String>>) it.next();
+            
+            String key = entry.getKey();
+            String newState = entry.getValue().leftValue();
+            ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);
+            
+            log.debug("------- Node id: "+key+" --- node status: "+newState+" -------- ctxt: "+ctxt);
+            
+            if (ctxt != null && key != null && newState != null) {
+                // bundle the data to be published
+                bundleData(key, newState, ctxt);
+            }  
+            
+        }
+
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
new file mode 100644
index 0000000..8d86d67
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java
@@ -0,0 +1,101 @@
+package org.wso2.carbon.stratos.cloud.controller.registry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.persist.Serializer;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException;
+
+/**
+ *
+ */
+public class RegistryManager {
+	private final static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registryService;
+	private static RegistryManager registryManager;
+	
+	public static RegistryManager getInstance() {
+
+		registryService = DeclarativeServiceReferenceHolder.getInstance().getRegistry();
+				
+		if (registryManager == null) {
+			synchronized(RegistryManager.class){
+				if (registryManager == null) {
+					if(registryService == null){
+//						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
+						return registryManager;
+					}
+					registryManager = new RegistryManager();
+				}
+			}
+		}
+
+		return registryManager;
+	}
+	
+	private RegistryManager() {
+		try {
+			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
+				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
+				                    registryService.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Failed to create the registry resource " +
+			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+	}
+
+	/**
+     * Persist an object in the local registry.
+     * @param dataObj object to be persisted.
+     */
+	public void persist(FasterLookUpDataHolder dataObj) throws RegistryException {
+		try {
+
+			registryService.beginTransaction();
+			
+			Resource nodeResource = registryService.newResource();
+
+			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
+
+			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
+			
+			registryService.commitTransaction();
+			
+		} catch (Exception e) {
+			String msg = "Failed to persist the cloud controller data in registry.";
+			registryService.rollbackTransaction();
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+			
+		} 
+	}
+	
+	public Object retrieve(){
+		
+		try {
+	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
+	        
+	        return resource.getContent();
+	        
+        } catch (ResourceNotFoundException ignore) {
+        	// this means, we've never persisted CC info in registry
+        	return null;
+        }catch (RegistryException e) {
+        	String msg = "Failed to retrieve cloud controller data from registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+        }
+		
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
new file mode 100644
index 0000000..3ab6681
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/registry/RegistryManager.java.back
@@ -0,0 +1,96 @@
+package org.wso2.carbon.stratos.cloud.controller.registry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.persist.Serializer;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerServiceReferenceHolder;
+
+/**
+ *
+ */
+public class RegistryManager {
+	private final static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registryService = CloudControllerServiceReferenceHolder.getInstance().getRegistry();
+	private static RegistryManager registryManager;
+	
+	public static RegistryManager getInstance() {
+
+		if (registryManager == null) {
+			synchronized(RegistryManager.class){
+				if (registryManager == null) {
+					if(registryService == null){
+						log.warn("Registry Service is null. Hence unable to fetch data from registry.");
+						return registryManager;
+					}
+					registryManager = new RegistryManager();
+				}
+			}
+		}
+
+		return registryManager;
+	}
+	
+	private RegistryManager() {
+		try {
+			if (!registryService.resourceExists(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE)) {
+				registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE,
+				                    registryService.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Failed to create the registry resource " +
+			                     CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+	}
+
+	/**
+     * Persist a node id in the local registry.
+     * @param nodeId node id to be persisted.
+     */
+	public void persist(Object dataObj) throws RegistryException {
+		try {
+
+			registryService.beginTransaction();
+			
+			Resource nodeResource = registryService.newResource();
+
+			nodeResource.setContent(Serializer.serializeToByteArray(dataObj));
+
+			registryService.put(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE, nodeResource);
+			
+			registryService.commitTransaction();
+			
+		} catch (Exception e) {
+			String msg = "Failed to persist the cloud controller data in registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+			
+		} finally{
+			registryService.rollbackTransaction();
+			
+		}
+	}
+	
+	public Object retrieve(){
+		
+		try {
+	        Resource resource = registryService.get(CloudControllerConstants.CLOUD_CONTROLLER_RESOURCE+ CloudControllerConstants.DATA_RESOURCE);
+	        
+	        return resource.getContent();
+	        
+        } catch (RegistryException e) {
+        	String msg = "Failed to retrieve cloud controller data from registry.";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+        }
+		
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
new file mode 100644
index 0000000..d990738
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/runtime/FasterLookUpDataHolder.java
@@ -0,0 +1,425 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.runtime;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.wso2.carbon.databridge.agent.thrift.DataPublisher;
+import org.wso2.carbon.stratos.cloud.controller.registry.RegistryManager;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+
+/**
+ * This object holds all runtime data and provides faster access. This is a Singleton class.
+ */
+public class FasterLookUpDataHolder implements Serializable{
+
+    private static final long serialVersionUID = -2662307358852779897L;
+
+	private static volatile FasterLookUpDataHolder ctxt;
+
+	/* We keep following maps in order to make the look up time, small. */
+
+	/**
+	 * Map of maps.
+	 * Map 1:
+	 * Key - domain
+	 * Value - is another map
+	 * Map 2:
+	 * key - sub domain
+	 * value - {@link ServiceContext}
+	 */
+	private Map<String, Map<String, ServiceContext>> serviceCtxts;
+	
+	/**
+	 * To make data retrieval from registry faster.
+	 */
+	private List<ServiceContext> serviceCtxtList;
+
+	public List<ServiceContext> getServiceCtxtList() {
+    	return serviceCtxtList;
+    }
+
+	/**
+	 * Key - node id
+	 * Value - {@link ServiceContext}
+	 */
+	private Map<String, ServiceContext> nodeIdToServiceCtxt;
+	
+	/**
+	 * List of registered {@link Cartridge}s
+	 */
+	private List<Cartridge> cartridges;
+
+	/**
+	 * List of IaaS Providers.
+	 */
+	private List<IaasProvider> iaasProviders;
+
+	private String serializationDir;
+	private boolean enableBAMDataPublisher;
+	private boolean enableTopologySync;
+	private String bamUsername = CloudControllerConstants.DEFAULT_BAM_SERVER_USER_NAME;
+	private String bamPassword = CloudControllerConstants.DEFAULT_BAM_SERVER_PASSWORD;
+	private String dataPublisherCron = CloudControllerConstants.PUB_CRON_EXPRESSION;
+	private String cassandraConnUrl = CloudControllerConstants.DEFAULT_CASSANDRA_URL;
+	private String cassandraUser = CloudControllerConstants.DEFAULT_CASSANDRA_USER;
+	private String cassandraPassword = CloudControllerConstants.DEFAULT_CASSANDRA_PASSWORD;
+	/**
+	 * Key - node id 
+	 * Value - Status of the instance
+	 * This map is only used by BAM data publisher in CC.
+	 */
+	private Map<String, String> nodeIdToStatusMap = new HashMap<String, String>();
+	private transient DataPublisher dataPublisher;
+	private String streamId;
+	private boolean isPublisherRunning;
+	private boolean isTopologySyncRunning;
+	private String topologySynchronizerCron = CloudControllerConstants.TOPOLOGY_SYNC_CRON;
+
+	private BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue = new LinkedBlockingQueue<List<ServiceContext>>();
+
+
+	private String mbServerUrl = CloudControllerConstants.MB_SERVER_URL;
+
+	public static FasterLookUpDataHolder getInstance() {
+
+		if (ctxt == null) {
+			synchronized (FasterLookUpDataHolder.class) {
+				if (ctxt == null && RegistryManager.getInstance() != null) {
+
+					Object obj = RegistryManager.getInstance().retrieve();
+					if (obj != null) {
+						if (obj instanceof FasterLookUpDataHolder) {
+							ctxt = (FasterLookUpDataHolder) obj;
+							System.out.println("*********** FasterLookUpDataHolder ********");
+						} else {
+							System.out.println("*********** Not a FasterLookUpDataHolder *******");
+						}
+
+					} 
+					
+				}
+				if(ctxt == null) {
+					ctxt = new FasterLookUpDataHolder();
+				}
+			}
+		}
+
+		return ctxt;
+	}
+
+	private FasterLookUpDataHolder() {
+
+		serviceCtxtList = new ArrayList<ServiceContext>();
+		serviceCtxts = new ConcurrentHashMap<String, Map<String, ServiceContext>>();
+		nodeIdToServiceCtxt = new LinkedHashMap<String, ServiceContext>();
+		cartridges = new ArrayList<Cartridge>();
+
+	}
+
+	public void addServiceContext(ServiceContext ctx) {
+
+		if (ctx == null) {
+			return;
+		}
+
+		String domain = ctx.getDomainName();
+		String subDomain = ctx.getSubDomainName();
+
+		if (domain != null && subDomain != null) {
+			addToServiceCtxts(domain, subDomain, ctx);
+		}
+
+	}
+
+	public void removeServiceContext(ServiceContext ctxt) {
+
+		if (ctxt == null) {
+			return;
+		}
+
+		String domain = ctxt.getDomainName();
+		String subDomain = ctxt.getSubDomainName();
+
+		if (domain != null && subDomain != null) {
+			if (serviceCtxts.containsKey(domain)) {
+				Map<String, ServiceContext> subDomainMap = serviceCtxts.get(domain);
+				subDomainMap.remove(subDomain);
+			}
+		}
+		
+		serviceCtxtList.remove(ctxt);
+
+	}
+
+	public ServiceContext getServiceContext(String domain, String subDomain) {
+
+		if (serviceCtxts.get(domain) != null) {
+			return serviceCtxts.get(domain).get(subDomain);
+		}
+		return null;
+	}
+
+	public ServiceContext getServiceContext(String nodeId) {
+
+		return nodeIdToServiceCtxt.get(nodeId);
+	}
+	
+	public List<Object> getNodeIdsOfServiceCtxt(ServiceContext ctxt){
+		return CloudControllerUtil.getKeysFromValue(nodeIdToServiceCtxt, ctxt);
+	}
+
+	public Map<String, Map<String, ServiceContext>> getServiceContexts() {
+		return serviceCtxts;
+	}
+
+	public void addNodeId(String nodeId, ServiceContext ctxt) {
+		nodeIdToServiceCtxt.put(nodeId, ctxt);
+	}
+
+	public void removeNodeId(String nodeId) {
+		nodeIdToServiceCtxt.remove(nodeId);
+	}
+	
+	public void setNodeIdToServiceContextMap(Map<String, ServiceContext> map) {
+		nodeIdToServiceCtxt = map;
+	}
+
+	public Map<String, ServiceContext> getNodeIdToServiceContextMap() {
+		return nodeIdToServiceCtxt;
+	}
+
+	private void addToServiceCtxts(String domainName, String subDomainName, ServiceContext ctxt) {
+
+		Map<String, ServiceContext> map;
+
+		if (serviceCtxts.get(domainName) == null) {
+			map = new HashMap<String, ServiceContext>();
+
+		} else {
+			map = serviceCtxts.get(domainName);
+		}
+
+		map.put(subDomainName, ctxt);
+		serviceCtxts.put(domainName, map);
+		
+		serviceCtxtList.add(ctxt);
+
+	}
+
+	public List<Cartridge> getCartridges() {
+		return cartridges;
+	}
+
+	public Cartridge getCartridge(String cartridgeType) {
+		for (Cartridge cartridge : cartridges) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				return cartridge;
+			}
+		}
+
+		return null;
+
+	}
+
+//	public void addCartridges(List<Cartridge> newCartridges) {
+//		if (this.cartridges == null) {
+//			this.cartridges = newCartridges;
+//		} else {
+//			for (Cartridge cartridge : newCartridges) {
+//				int idx;
+//				if ((idx = cartridges.indexOf(cartridge)) != -1) {
+//					Cartridge ref = cartridges.get(idx);
+//					ref = cartridge;
+//				} else {
+//					cartridges.add(cartridge);
+//				}
+//			}
+//		}
+//
+//	}
+	
+	public void addCartridge(Cartridge newCartridges) {
+	
+		cartridges.add(newCartridges);
+	}
+
+	public void removeCartridges(List<Cartridge> cartridges) {
+		if (this.cartridges != null) {
+			this.cartridges.removeAll(cartridges);
+		}
+
+	}
+
+	public List<IaasProvider> getIaasProviders() {
+		return iaasProviders;
+	}
+
+	public void setIaasProviders(List<IaasProvider> iaasProviders) {
+		this.iaasProviders = iaasProviders;
+	}
+
+	public String getSerializationDir() {
+		return serializationDir;
+	}
+
+	public void setSerializationDir(String serializationDir) {
+		this.serializationDir = serializationDir;
+	}
+
+	public String getBamUsername() {
+		return bamUsername;
+	}
+
+	public void setBamUsername(String bamUsername) {
+		this.bamUsername = bamUsername;
+	}
+
+	public String getBamPassword() {
+		return bamPassword;
+	}
+
+	public void setBamPassword(String bamPassword) {
+		this.bamPassword = bamPassword;
+	}
+
+	public String getDataPublisherCron() {
+		return dataPublisherCron;
+	}
+
+	public void setDataPublisherCron(String dataPublisherCron) {
+		this.dataPublisherCron = dataPublisherCron;
+	}
+
+	public Map<String, String> getNodeIdToStatusMap() {
+		return nodeIdToStatusMap;
+	}
+
+	public void setNodeIdToStatusMap(Map<String, String> nodeIdToStatusMap) {
+		this.nodeIdToStatusMap = nodeIdToStatusMap;
+	}
+
+	public DataPublisher getDataPublisher() {
+		return dataPublisher;
+	}
+
+	public void setDataPublisher(DataPublisher dataPublisher) {
+		this.dataPublisher = dataPublisher;
+	}
+
+	public String getStreamId() {
+		return streamId;
+	}
+
+	public void setStreamId(String streamId) {
+		this.streamId = streamId;
+	}
+
+	public boolean getEnableBAMDataPublisher() {
+		return enableBAMDataPublisher;
+	}
+
+	public void setEnableBAMDataPublisher(boolean enableBAMDataPublisher) {
+		this.enableBAMDataPublisher = enableBAMDataPublisher;
+	}
+
+	public String getCassandraConnUrl() {
+		return cassandraConnUrl;
+	}
+
+	public void setCassandraConnUrl(String cassandraHostAddr) {
+		this.cassandraConnUrl = cassandraHostAddr;
+	}
+
+	public String getCassandraUser() {
+		return cassandraUser;
+	}
+
+	public void setCassandraUser(String cassandraUser) {
+		this.cassandraUser = cassandraUser;
+	}
+
+	public String getCassandraPassword() {
+		return cassandraPassword;
+	}
+
+	public void setCassandraPassword(String cassandraPassword) {
+		this.cassandraPassword = cassandraPassword;
+	}
+
+	public boolean isPublisherRunning() {
+		return isPublisherRunning;
+	}
+
+	public void setPublisherRunning(boolean isPublisherRunning) {
+		this.isPublisherRunning = isPublisherRunning;
+	}
+
+	public BlockingQueue<List<ServiceContext>> getSharedTopologyDiffQueue() {
+		return sharedTopologyDiffQueue;
+	}
+
+	public void setSharedTopologyDiffQueue(BlockingQueue<List<ServiceContext>> sharedTopologyDiffQueue) {
+		this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
+	}
+
+	public String getTopologySynchronizerCron() {
+		return topologySynchronizerCron;
+	}
+
+	public void setTopologySynchronizerCron(String topologySynchronizerCron) {
+		this.topologySynchronizerCron = topologySynchronizerCron;
+	}
+
+	public void setMBServerUrl(String ip) {
+		this.mbServerUrl = ip;
+	}
+
+	public String getMBServerUrl() {
+		return mbServerUrl;
+	}
+
+	public boolean getEnableTopologySync() {
+		return enableTopologySync;
+	}
+
+	public void setEnableTopologySync(boolean enableTopologySync) {
+		this.enableTopologySync = enableTopologySync;
+	}
+
+	public boolean isTopologySyncRunning() {
+	    return isTopologySyncRunning;
+    }
+
+	public void setTopologySyncRunning(boolean isTopologySyncRunning) {
+	    this.isTopologySyncRunning = isTopologySyncRunning;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
new file mode 100644
index 0000000..20ac038
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/ConfigurationPublisher.java
@@ -0,0 +1,65 @@
+package org.wso2.carbon.stratos.cloud.controller.topic;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+
+public class ConfigurationPublisher {
+	private TopicPublisher topicPublisher;
+	private TopicSession topicSession;
+	private TopicConnection topicConnection;
+	private TopicConnectionFactory topicConnectionFactory;
+	private static final Log log = LogFactory.getLog(ConfigurationPublisher.class);
+	
+	
+	public ConfigurationPublisher() {
+	    
+		Properties initialContextProperties = new Properties();
+		initialContextProperties.put("java.naming.factory.initial",
+				"org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+		String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://"+FasterLookUpDataHolder.getInstance().getMBServerUrl()+"'";
+		initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+		
+		try {
+			InitialContext initialContext = new InitialContext(initialContextProperties);
+			topicConnectionFactory =
+					(TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+			
+//			topicConnection.stop();
+//			topicConnection.close();
+			
+		} catch (NamingException e) {
+			log.error(e.getMessage(), e);
+		} 
+    }
+
+	
+	public void publish(String topicName, String message) {
+		try {
+			topicConnection = topicConnectionFactory.createTopicConnection();
+			topicConnection.start();
+			topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+			Topic topic = topicSession.createTopic(topicName);
+			topicPublisher = topicSession.createPublisher(topic);
+			TextMessage textMessage = topicSession.createTextMessage(message);
+
+			topicPublisher.publish(textMessage);
+			
+			topicPublisher.close();
+			topicSession.close();
+			topicConnection.stop();
+			topicConnection.close();
+			
+		}  catch (JMSException e) {
+			log.error(e.getMessage(), e);
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
new file mode 100644
index 0000000..6a9c155
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/topic/TopologySynchronizerTask.java
@@ -0,0 +1,78 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.topic;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.ntask.core.Task;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+
+public class TopologySynchronizerTask implements Task{
+    
+    private static final Log log = LogFactory.getLog(TopologySynchronizerTask.class);
+    private DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
+    private File topologyFile;
+    
+    @Override
+    public void execute() {
+    	if(FasterLookUpDataHolder.getInstance().isTopologySyncRunning()||
+        		// this is a temporary fix to avoid task execution - limitation with ntask
+        		!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
+            return;
+        }
+    	
+    	log.debug("TopologySynchronizerTask ... ");
+        
+    	// publish to the topic 
+		try {
+			if (topologyFile.exists()) {
+				data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME,
+				                               FileUtils.readFileToString(topologyFile));
+			}
+		} catch (IOException e) {
+        	String msg = "Failed when publishing to the topic "+CloudControllerConstants.TOPIC_NAME+
+        			" - Reason : Failed while reading topology from "+topologyFile.getAbsolutePath();
+        	log.error(msg, e);
+        	throw new CloudControllerException(msg, e);
+        }
+    }
+    
+    @Override
+    public void init() {
+
+    	// this is a temporary fix to avoid task execution - limitation with ntask
+		if(!FasterLookUpDataHolder.getInstance().getEnableTopologySync()){
+			log.debug("Topology Sync is disabled.");
+			return;
+		}
+    	
+    	topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
+        
+    }
+
+    @Override
+    public void setProperties(Map<String, String> arg0) {}
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
new file mode 100644
index 0000000..ee8e209
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/AppType.java
@@ -0,0 +1,44 @@
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+
+/**
+ * domain mapping related data.
+ *
+ */
+public class AppType implements Serializable{
+	
+    private static final long serialVersionUID = 3550489774139807168L;
+	private String name;
+	private boolean appSpecificMapping = true;
+	
+	public AppType(){
+		
+	}
+	
+	public AppType(String name){
+		this.setName(name);
+	}
+	
+	public AppType(String name, boolean appSpecificMapping){
+		this.setName(name);
+		this.setAppSpecificMapping(appSpecificMapping);
+	}
+
+	public String getName() {
+	    return name;
+    }
+
+	public void setName(String name) {
+	    this.name = name;
+    }
+
+	public boolean isAppSpecificMapping() {
+	    return appSpecificMapping;
+    }
+
+	public void setAppSpecificMapping(boolean appSpecificMapping) {
+	    this.appSpecificMapping = appSpecificMapping;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
new file mode 100644
index 0000000..c9042fa
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Cartridge.java
@@ -0,0 +1,254 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+
+/**
+ * Holds information regarding a Cartridge.
+ */
+public class Cartridge implements Serializable{
+
+    private static final long serialVersionUID = 6637409027085059072L;
+
+	private String type;
+    
+    private String hostName;
+    
+    private String provider;
+    
+    private String displayName;
+    
+    private String description;
+    
+    private String baseDir;
+    
+    private String version;
+    
+    private boolean multiTenant;
+    
+    private List<PortMapping> portMappings = new ArrayList<PortMapping>();
+    
+    private List<AppType> appTypeMappings = new ArrayList<AppType>();
+    
+    /**
+     * Property map of this Cartridge.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * A Cartridge can have 1..n {@link IaasProvider}s
+     */
+    private List<IaasProvider> iaases = new ArrayList<IaasProvider>();
+    
+    private List<String> deploymentDirs = new ArrayList<String>();
+    
+    private IaasProvider lastlyUsedIaas;
+    
+    public Cartridge(){}
+    
+    public Cartridge(String type, String host, String provider, String version, boolean multiTenant) {
+        this.type = type;
+        this.hostName = host;
+        this.provider = provider;
+        this.version = version;
+        this.multiTenant = multiTenant;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public String getProperty(String key) {
+        return properties.get(key);
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public void addIaasProvider(IaasProvider iaas) {
+        for (IaasProvider anIaas : iaases) {
+            if(anIaas.equals(iaas)){
+                int idx = iaases.indexOf(anIaas);
+                iaases.remove(idx);
+                iaases.add(idx, iaas);
+                return;
+            }
+        }
+        this.iaases.add(iaas);
+    }
+    
+    public IaasProvider getIaasProvider(String iaasType){
+    	for (IaasProvider iaas : iaases) {
+	        if(iaas.getType().equals(iaasType)){
+	        	return iaas;
+	        }
+        }
+    	
+    	return null;
+    }
+
+    public List<IaasProvider> getIaases() {
+        return iaases;
+    }
+
+    public void setIaases(List<IaasProvider> iaases) {
+        this.iaases = iaases;
+    }
+    
+	public boolean equals(Object obj) {
+		if (obj instanceof Cartridge) {
+			return this.type.equals(((Cartridge)obj).getType());
+		}
+		return false;
+	}
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(type).
+            toHashCode();
+    }
+
+    public IaasProvider getLastlyUsedIaas() {
+        return lastlyUsedIaas;
+    }
+
+    public void setLastlyUsedIaas(IaasProvider lastlyUsedIaas) {
+        this.lastlyUsedIaas = lastlyUsedIaas;
+    }
+
+//    public boolean isJcloudsObjectsBuilt() {
+//        return isJcloudsObjectsBuilt;
+//    }
+//
+//    public void setJcloudsObjectsBuilt(boolean isJcloudsObjectsBuilt) {
+//        this.isJcloudsObjectsBuilt = isJcloudsObjectsBuilt;
+//    }
+
+	public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+	public String getHostName() {
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+	
+	public void reset(){
+//		lastlyUsedIaas = null;
+	}
+
+	public List<String> getDeploymentDirs() {
+	    return deploymentDirs;
+    }
+
+	public void setDeploymentDirs(List<String> deploymentDirs) {
+	    this.deploymentDirs = deploymentDirs;
+    }
+	
+	public void addDeploymentDir(String dir){
+		deploymentDirs.add(dir);
+	}
+	
+	public void addPortMapping(PortMapping mapping){
+		portMappings.add(mapping);
+	}
+	
+	public void addAppType(AppType type){
+		appTypeMappings.add(type);
+	}
+
+	public String getProvider() {
+	    return provider;
+    }
+
+	public void setProvider(String provider) {
+	    this.provider = provider;
+    }
+
+	public String getVersion() {
+		return version;
+	}
+
+	public void setVersion(String version) {
+		this.version = version;
+	}
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getBaseDir() {
+	    return baseDir;
+    }
+
+	public void setBaseDir(String baseDir) {
+	    this.baseDir = baseDir;
+    }
+
+	public List<PortMapping> getPortMappings() {
+	    return portMappings;
+    }
+
+	public void setPortMappings(List<PortMapping> portMappings) {
+	    this.portMappings = portMappings;
+    }
+
+	public List<AppType> getAppTypeMappings() {
+    	return appTypeMappings;
+    }
+
+	public void setAppTypeMappings(List<AppType> appTypeMappings) {
+    	this.appTypeMappings = appTypeMappings;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
new file mode 100644
index 0000000..fd02233
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInfo.java
@@ -0,0 +1,162 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Holds useful information for externals, regarding a Cartridge.
+ */
+public class CartridgeInfo {
+
+    private String type;
+    
+    private String hostName;
+    
+    private String displayName;
+    
+    private String description;
+    
+    private String[] deploymentDirs;
+    
+    private PortMapping[] portMappings;
+    
+    private AppType[] appTypes;
+    
+    private String provider;
+    
+    private String version;
+    
+    private boolean multiTenant;
+    
+    private String baseDir;
+    
+    private Property[] properties;
+    
+    public CartridgeInfo(){
+    	
+    }
+    
+    public CartridgeInfo(String type, String host, String desc, List<String> deploymentDirs, String provider) {
+        this.type = type;
+        this.hostName = host;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+	public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+	public String getHostName() {
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+
+	public String[] getDeploymentDirs() {
+	    return deploymentDirs;
+    }
+
+	public void setDeploymentDirs(List<String> deploymentDirsList) {
+		if(deploymentDirsList == null){
+			deploymentDirsList = new ArrayList<String>();
+		}
+	    this.deploymentDirs = new String[deploymentDirsList.size()];
+	    
+	    deploymentDirsList.toArray(deploymentDirs);
+	    
+    }
+	
+    public String getProvider() {
+	    return provider;
+    }
+
+	public void setProvider(String provider) {
+	    this.provider = provider;
+    }
+
+	public String getVersion() {
+		return version;
+	}
+
+	public void setVersion(String version) {
+		this.version = version;
+	}
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getBaseDir() {
+	    return baseDir;
+    }
+
+	public void setBaseDir(String baseDir) {
+	    this.baseDir = baseDir;
+    }
+
+	public PortMapping[] getPortMappings() {
+	    return portMappings;
+    }
+
+	public void setPortMappings(PortMapping[] portMappings) {
+	    this.portMappings = portMappings;
+    }
+
+	public AppType[] getAppTypes() {
+	    return appTypes;
+    }
+
+	public void setAppTypes(AppType[] appTypes) {
+	    this.appTypes = appTypes;
+    }
+
+	public Property[] getProperties() {
+	    return properties;
+    }
+
+	public void setProperties(Property[] properties) {
+	    this.properties = properties;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
new file mode 100644
index 0000000..b828cb2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CartridgeInstanceData.java
@@ -0,0 +1,129 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import org.jclouds.compute.domain.NodeMetadata;
+
+/**
+ * This class holds the data to be published to BAM.
+ */
+public class CartridgeInstanceData {
+
+    // Cartridge type
+    private String type;
+    
+    private String nodeId;
+    
+    private String domain;
+    
+    private String subDomain;
+    
+    private String iaas;
+    
+    private String status;
+    
+    private String tenantRange;
+    
+    private String alias;
+    
+    private boolean isMultiTenant;
+    
+    private NodeMetadata metaData;
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
+
+    public String getNodeId() {
+        return nodeId;
+    }
+
+    public void setNodeId(String nodeId) {
+        this.nodeId = nodeId;
+    }
+
+    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;
+    }
+
+    public String getIaas() {
+        return iaas;
+    }
+
+    public void setIaas(String iaas) {
+        this.iaas = iaas;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public NodeMetadata getMetaData() {
+        return metaData;
+    }
+
+    public void setMetaData(NodeMetadata metaData) {
+        this.metaData = metaData;
+    }
+
+    public String getTenantRange() {
+        return tenantRange;
+    }
+
+    public void setTenantRange(String tenantRange) {
+        this.tenantRange = tenantRange;
+    }
+
+    public boolean isMultiTenant() {
+        return isMultiTenant;
+    }
+
+    public void setMultiTenant(boolean isMultiTenant) {
+        this.isMultiTenant = isMultiTenant;
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    public void setAlias(String alias) {
+        this.alias = alias;
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
new file mode 100644
index 0000000..cb537a1
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerConstants.java
@@ -0,0 +1,216 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.File;
+
+import org.wso2.carbon.utils.CarbonUtils;
+
+public final class CloudControllerConstants {
+
+    /**
+     * cloud-controller XML file's elements
+     */
+    public static final String CLOUD_CONTROLLER_ELEMENT = "cloudController";
+    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
+    public static final String IAAS_PROVIDERS_ELEMENT = "iaasProviders";
+    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
+    public static final String DEPLOYMENT_ELEMENT = "deployment";
+    public static final String PORT_MAPPING_ELEMENT = "portMapping";
+    public static final String APP_TYPES_ELEMENT = "appTypes";
+    public static final String TYPE_ATTR = "type";
+    public static final String HOST_ATTR = "host";
+    public static final String BASE_DIR_ATTR = "baseDir";
+    public static final String PROVIDER_ATTR = "provider";
+    public static final String VERSION_ATTR = "version";
+    public static final String MULTI_TENANT_ATTR = "multiTenant";
+    public static final String PORT_ATTR = "port";
+    public static final String PROXY_PORT_ATTR = "proxyPort";
+    public static final String NAME_ATTR = "name";
+    public static final String APP_SPECIFIC_MAPPING_ATTR = "appSpecificMapping";
+    
+    public static final String CARTRIDGES_ELEMENT = "cartridges";
+    public static final String CARTRIDGE_ELEMENT = "cartridge";
+    
+    public static final String DISPLAY_NAME_ELEMENT = "displayName";
+    public static final String DESCRIPTION_ELEMENT = "description";
+    public static final String PROPERTY_ELEMENT = "property";
+    public static final String PROPERTY_NAME_ATTR= "name";
+    public static final String PROPERTY_VALUE_ATTR = "value";
+    public static final String IMAGE_ID_ELEMENT = "imageId";
+    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
+    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
+    public static final String CLASS_NAME_ELEMENT = "className";
+    public static final String MAX_INSTANCE_LIMIT_ELEMENT = "maxInstanceLimit";
+    public static final String PROVIDER_ELEMENT = "provider";
+    public static final String IDENTITY_ELEMENT = "identity";
+    public static final String CREDENTIAL_ELEMENT = "credential";
+    public static final String DEFAULT_SERVICE_ELEMENT = "default";
+    public static final String SERVICE_ELEMENT = "service";
+    public static final String SERVICES_ELEMENT = "services";
+    public static final String DIRECTORY_ELEMENT = "dir";
+    public static final String HTTP_ELEMENT = "http";
+    public static final String HTTPS_ELEMENT = "https";
+    public static final String APP_TYPE_ELEMENT = "appType";
+    public static final String SERVICE_DOMAIN_ATTR = "domain";
+    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
+    public static final String SERVICE_TENANT_RANGE_ATTR = "tenantRange";
+    public static final String PAYLOAD_ELEMENT = "payload";
+    public static final String DATA_PUBLISHER_ELEMENT = "dataPublisher";
+    public static final String TOPOLOGY_SYNC_ELEMENT = "topologySync";
+    public static final String ENABLE_ATTR = "enable";
+    public static final String BAM_SERVER_ELEMENT = "bamServer";
+    public static final String MB_SERVER_ELEMENT = "mbServerUrl";
+    public static final String CRON_ELEMENT = "cron";
+    public static final String BAM_SERVER_ADMIN_USERNAME_ELEMENT = "adminUserName";
+    public static final String BAM_SERVER_ADMIN_PASSWORD_ELEMENT = "adminPassword";
+    public static final String CASSANDRA_INFO_ELEMENT = "cassandraInfo";
+    public static final String HOST_ELEMENT = "host";
+    public static final String CONNECTION_URL_ELEMENT = "connectionUrl";
+    public static final String HOST_PORT_ELEMENT = "port";
+    public static final String USER_NAME_ELEMENT = "userName";
+    public static final String PASSWORD_ELEMENT = "password";
+    public static final String CLOUD_CONTROLLER_EVENT_STREAM = "org.wso2.stratos.cloud.controller";
+    public static final String CLOUD_CONTROLLER_COL_FAMILY = CLOUD_CONTROLLER_EVENT_STREAM.replaceAll("[/.]", "_");
+    
+    /**
+     * column names
+     */
+    public static final String PAYLOAD_PREFIX = "payload_";
+    public static final String NODE_ID_COL = "nodeId";
+    public static final String CARTRIDGE_TYPE_COL = "cartridgeType";
+    public static final String DOMAIN_COL = "domain";
+    public static final String SUB_DOMAIN_COL = "subDomain";
+    public static final String ALIAS_COL = "alias";
+    public static final String TENANT_RANGE_COL = "tenantRange";
+    public static final String IS_MULTI_TENANT_COL = "isMultiTenant";
+    public static final String IAAS_COL = "iaas";
+    public static final String STATUS_COL = "status";
+    public static final String HOST_NAME_COL = "hostName";
+    public static final String HYPERVISOR_COL = "hypervisor";
+    public static final String RAM_COL = "ram";
+    public static final String IMAGE_ID_COL = "imageId";
+    public static final String LOGIN_PORT_COL = "loginPort";
+    public static final String OS_NAME_COL = "osName";
+    public static final String OS_VERSION_COL = "osVersion";
+    public static final String OS_ARCH_COL = "osArch";
+    public static final String OS_BIT_COL = "is64bitOS";
+    public static final String PRIV_IP_COL = "privateIPAddresses";
+    public static final String PUB_IP_COL = "publicIPAddresses";
+    
+    
+    /**
+     * Properties
+     */
+    public static final String REGION_PROPERTY = "region";
+    public static final String PUBLIC_IP_PROPERTY = "public_ip";
+    public static final String TENANT_ID_PROPERTY = "tenant_id";
+    public static final String ALIAS_PROPERTY = "alias";
+    public static final String AUTO_ASSIGN_IP_PROPERTY = "autoAssignIp";
+    
+    /**
+     * XPath expressions
+     */
+    public static final String IAAS_PROVIDER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+"/"+
+     IAAS_PROVIDERS_ELEMENT+"/"+IAAS_PROVIDER_ELEMENT;
+    public static final String PROPERTY_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
+    public static final String IMAGE_ID_ELEMENT_XPATH = "/"+IMAGE_ID_ELEMENT;
+    public static final String SCALE_UP_ORDER_ELEMENT_XPATH = "/"+SCALE_UP_ORDER_ELEMENT;
+    public static final String SCALE_DOWN_ORDER_ELEMENT_XPATH = "/"+SCALE_DOWN_ORDER_ELEMENT;
+    public static final String PROVIDER_ELEMENT_XPATH = "/"+PROPERTY_ELEMENT;
+    public static final String IDENTITY_ELEMENT_XPATH = "/"+IDENTITY_ELEMENT;
+    public static final String CREDENTIAL_ELEMENT_XPATH = "/"+CREDENTIAL_ELEMENT;
+    public static final String SERVICES_ELEMENT_XPATH = "/"+SERVICES_ELEMENT+"/"+SERVICE_ELEMENT;
+    public static final String SERVICE_ELEMENT_XPATH = "/"+SERVICE_ELEMENT;
+    public static final String CARTRIDGE_ELEMENT_XPATH = "/"+CARTRIDGE_ELEMENT;
+    public static final String PAYLOAD_ELEMENT_XPATH = "/"+PAYLOAD_ELEMENT;
+    public static final String HOST_ELEMENT_XPATH = "/"+HOST_ELEMENT;
+    public static final String CARTRIDGES_ELEMENT_XPATH = "/"+CARTRIDGES_ELEMENT+"/"+CARTRIDGE_ELEMENT;
+    public static final String IAAS_PROVIDER_ELEMENT_XPATH = "/"+IAAS_PROVIDER_ELEMENT;
+    public static final String DEPLOYMENT_ELEMENT_XPATH = "/"+DEPLOYMENT_ELEMENT;
+    public static final String PORT_MAPPING_ELEMENT_XPATH = "/"+PORT_MAPPING_ELEMENT;
+    public static final String APP_TYPES_ELEMENT_XPATH = "/"+APP_TYPES_ELEMENT;
+    
+    public static final String DATA_PUBLISHER_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+DATA_PUBLISHER_ELEMENT;
+    public static final String TOPOLOGY_SYNC_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+TOPOLOGY_SYNC_ELEMENT;
+    public static final String DATA_PUBLISHER_CRON_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+CRON_ELEMENT;
+    public static final String BAM_SERVER_ADMIN_USERNAME_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+BAM_SERVER_ADMIN_USERNAME_ELEMENT;
+    public static final String BAM_SERVER_ADMIN_PASSWORD_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+            "/"+BAM_SERVER_ADMIN_PASSWORD_ELEMENT;
+//    public static final String CASSANDRA_HOST_ADDRESS_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+//            "/"+CASSANDRA_HOST_ADDRESS;
+//    public static final String CASSANDRA_HOST_PORT_XPATH = "/"+CLOUD_CONTROLLER_ELEMENT+
+//            "/"+CASSANDRA_HOST_PORT;
+    
+    
+    /**
+     * Secret Manager related aliases.
+     */
+    public static final String ALIAS_ATTRIBUTE = "svns:secretAlias";
+    
+    /**
+     * Payload related constants
+     */
+    public static final String PAYLOAD_FOLDER = "payload";
+    public static final String ENTRY_SEPARATOR = ",";
+    
+    /**
+     * Publisher task related constants
+     */
+    public static final String DATA_PUB_TASK_TYPE = "CLOUD_CONTROLLER_DATA_PUBLISHER_TASK";
+    // default is : data publisher will run in first second of every minute
+    public static final String PUB_CRON_EXPRESSION = "1 * * * * ? *";
+    public static final String DATA_PUB_TASK_NAME = "CartridgeInstanceDataPublisherTask";
+    public static final String DEFAULT_BAM_SERVER_USER_NAME = "admin";
+    public static final String DEFAULT_BAM_SERVER_PASSWORD = "admin";
+    public static final String DEFAULT_CASSANDRA_URL = "localhost:9160";
+    public static final String DEFAULT_CASSANDRA_USER = "admin";
+    public static final String DEFAULT_CASSANDRA_PASSWORD = "admin";
+    public static final String DEFAULT_CASSANDRA_CLUSTER_NAME = "Test Cluster";
+    public static final String DEFAULT_CASSANDRA_KEY_SPACE = "EVENT_KS";
+    
+	/**
+	 * Directories
+	 */
+	public static final String PAYLOAD_DIR = CarbonUtils.getCarbonHome() + File.separator +
+	                                         "resources" + File.separator + PAYLOAD_FOLDER +
+	                                         File.separator;
+	public static final String SERVICES_DIR = CarbonUtils.getCarbonRepository() 
+    		+ File.separator + "services"+File.separator;
+    
+    /**
+     * Topology sync related constants
+     */
+    public static final String TOPOLOGY_FILE_PATH = CarbonUtils.getCarbonConfigDirPath()+File.separator+"service-topology.conf";
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+	public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySynchronizerTask";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SYNC_TASK";
+	public static final String MB_SERVER_URL = "localhost:5672";
+    
+	/**
+	 * Persistence
+	 */
+	public static final String CLOUD_CONTROLLER_RESOURCE = "/cloud.controller";
+	public static final String DATA_RESOURCE = "/data";
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
new file mode 100644
index 0000000..64169b6
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/CloudControllerUtil.java
@@ -0,0 +1,102 @@
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.xml.stream.XMLStreamException;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+
+public class CloudControllerUtil {
+	private static final Log log = LogFactory.getLog(CloudControllerUtil.class);
+
+	public static OMElement serviceCtxtToOMElement(ServiceContext ctxt) throws XMLStreamException{
+		String xml;
+		
+		xml = ctxt.toXml();
+		
+		return AXIOMUtil.stringToOM(xml);
+	}
+
+	public static byte[] getBytesFromFile(String path) {
+
+		try {
+	        return FileUtils.readFileToByteArray(new File(path));
+        } catch (IOException e) {
+
+        	handleException("Failed to read the file "+path, e);
+        }
+		return new byte[0];
+    }
+	
+	public static CartridgeInfo toCartridgeInfo(Cartridge cartridge) {
+
+		CartridgeInfo carInfo = new CartridgeInfo();
+		carInfo.setType(cartridge.getType());
+		carInfo.setDisplayName(cartridge.getDisplayName());
+		carInfo.setDescription(cartridge.getDescription());
+		carInfo.setHostName(cartridge.getHostName());
+		carInfo.setDeploymentDirs(cartridge.getDeploymentDirs());
+		carInfo.setProvider(cartridge.getProvider());
+		carInfo.setVersion(cartridge.getVersion());
+		carInfo.setMultiTenant(cartridge.isMultiTenant());
+		carInfo.setBaseDir(cartridge.getBaseDir());
+		carInfo.setPortMappings(cartridge.getPortMappings()
+		                                 .toArray(new PortMapping[cartridge.getPortMappings()
+		                                                                   .size()]));
+		carInfo.setAppTypes(cartridge.getAppTypeMappings()
+                                .toArray(new AppType[cartridge.getAppTypeMappings()
+                                                                  .size()]));
+		
+		List<Property> propList = new ArrayList<Property>();
+		
+		for (Iterator<?> iterator = cartridge.getProperties().entrySet().iterator(); iterator.hasNext();) {
+	        @SuppressWarnings("unchecked")
+            Map.Entry<String, String> entry = (Entry<String, String>) iterator.next();
+	        
+	        Property prop = new Property(entry.getKey(), entry.getValue());
+	        propList.add(prop);
+        }
+		Property[] props = new Property[propList.size()];
+		
+		carInfo.setProperties(propList.toArray(props));
+
+		return carInfo;
+	}
+	
+	public static List<Object> getKeysFromValue(Map<?, ?> hm, Object value) {
+		List<Object> list = new ArrayList<Object>();
+		for (Object o : hm.keySet()) {
+			if (hm.get(o).equals(value)) {
+				list.add(o);
+			}
+		}
+		return list;
+	}
+	
+	public static void sleep(long time){
+    	try {
+    		Thread.sleep(time);
+    	} catch (InterruptedException ignore) {}
+    	
+    }
+	
+	public static void handleException(String msg, Exception e){
+		log.error(msg, e);
+		throw new CloudControllerException(msg, e);
+	}
+	
+	public static void handleException(String msg){
+		log.error(msg);
+		throw new CloudControllerException(msg);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
new file mode 100644
index 0000000..a5efb07
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/DeclarativeServiceReferenceHolder.java
@@ -0,0 +1,69 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.stratos.cloud.controller.topic.ConfigurationPublisher;
+
+/**
+ * Singleton class to hold all the service references.
+ */
+public class DeclarativeServiceReferenceHolder {
+
+    private static DeclarativeServiceReferenceHolder instance;
+    private TaskService taskService;
+    private ConfigurationPublisher configPub;
+    private Registry registry;
+    
+    private DeclarativeServiceReferenceHolder() {
+    }
+
+    public static DeclarativeServiceReferenceHolder getInstance() {
+        if (instance == null) {
+            instance = new DeclarativeServiceReferenceHolder();
+        }
+        return instance;
+    }
+    
+    public ConfigurationPublisher getConfigPub(){
+    	return configPub;
+    }
+
+    public TaskService getTaskService() {
+        return taskService;
+    }
+
+    public void setTaskService(TaskService taskService) {
+        this.taskService = taskService;
+    }
+    
+    public void setConfigPub(ConfigurationPublisher configPub) {
+        this.configPub = configPub;
+    }
+
+	public void setRegistry(UserRegistry governanceSystemRegistry) {
+		registry = governanceSystemRegistry;
+    }
+
+	public Registry getRegistry() {
+	    return registry;
+    }
+    
+}


[37/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepoNotificationService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepoNotificationService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepoNotificationService.java
new file mode 100644
index 0000000..2d3f640
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepoNotificationService.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.service;
+
+import java.io.File;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.dao.CartridgeSubscription;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.adc.mgt.utils.CartridgeConstants;
+import org.wso2.carbon.adc.mgt.utils.PersistenceManager;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.core.deployment.SynchronizeGitRepositoryRequest;
+import org.wso2.carbon.utils.CarbonUtils;
+
+
+public class RepoNotificationService {
+
+	private static final Log log = LogFactory.getLog(RepoNotificationService.class);
+	
+
+	public void notifyRepoUpdate(String tenantDomain, String cartridgeAlias) throws Exception {
+		// FIXME Throwing generic Exception is wrong
+		log.info("Updating repository of tenant : " + tenantDomain + " , cartridge: " +
+				cartridgeAlias);
+
+		CartridgeSubscription subscription = null;
+		try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to find subscription for " + cartridgeAlias + ". "
+					+ (e.getMessage() != null ? e.getMessage() : "");
+			log.error(msg, e);
+			throw new Exception(msg, e);
+		}
+		
+		if (subscription == null) {
+			String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+			log.error(msg);
+			throw new Exception("You have not subscribed for " + cartridgeAlias);
+		}
+		
+		try {
+			handleRepoSynch(subscription);
+		} catch (Exception e) {
+			String msg = "Failed to synchronize the repository for " + cartridgeAlias + ". "
+					+ (e.getMessage() != null ? e.getMessage() : "");
+			log.error(msg, e);
+			throw new Exception(msg, e);
+		}
+		
+	}
+
+	public void synchronize(String repositoryURL) throws Exception {
+
+		log.info(" repository URL received : " + repositoryURL);
+		List<CartridgeSubscription> subscription = PersistenceManager.getSubscription(repositoryURL);
+		for (CartridgeSubscription cartridgeSubscription : subscription) {			
+			handleRepoSynch(cartridgeSubscription);   
+        }
+	}
+
+	private void handleRepoSynch(CartridgeSubscription subscription) throws Exception {
+		if (subscription == null) {
+			throw new Exception("Cannot synchronize repository. subscription is null");
+		}
+
+		if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(subscription.getProvider())) {
+			log.info(" wso2 cartridge.. ");
+			createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
+			                            UUID.randomUUID(), subscription.getClusterDomain(),
+			                            subscription.getClusterSubdomain());
+			//for manager node
+			           /* if (subscription.getMgtClusterSubDomain() != null && !subscription.getMgtClusterSubDomain().isEmpty()) {
+			                createAndSendClusterMessage(subscription.getTenantId(), subscription.getTenantDomain(),
+			                        UUID.randomUUID(), subscription.getMgtClusterDomain(),
+			                        subscription.getMgtClusterSubDomain());
+			            }
+			            else {
+			                if(log.isDebugEnabled())
+			                    log.debug("Manager node cluster information not found, not sending the SynchronizeGitRepositoryRequest");
+			            }*/
+
+		} else {
+
+			// Query DB and get all the IP s for this tenant 
+			// Invoke update-instance script
+			
+			String appPath = subscription.getBaseDirectory();
+			String cartridgePrivateKey = System.getProperty(CartridgeConstants.CARTRIDGE_KEY);
+			
+			File keyFile = new File(cartridgePrivateKey);
+			if (!keyFile.exists()) {
+				log.error("The key file does not exist! " + cartridgePrivateKey);
+			}
+
+			if (subscription != null) {
+				TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+
+				
+				if (topologyMgtService == null) {
+					String msg = " Topology Management Service is null ";
+					log.error(msg);
+					throw new Exception(msg);
+				}
+
+				String[] activeIpArray =
+				                         topologyMgtService.getActiveIPs(subscription.getCartridge(),
+				                                                         subscription.getClusterDomain(),
+				                                                         subscription.getClusterSubdomain());
+				try {
+
+					for (String instanceIp : activeIpArray) {
+						String command =
+						                 CarbonUtils.getCarbonHome() + File.separator + "bin" +
+						                         File.separator + "update-instance.sh " +
+						                         instanceIp + " " + appPath + " " +
+						                         cartridgePrivateKey + " /";
+						log.info("Update instance command.... " + command);
+						Process proc = Runtime.getRuntime().exec(command);
+						proc.waitFor();
+					}
+
+				} catch (Exception e) {
+					log.error("Exception is occurred in notify update operation. Reason : " +
+					          e.getMessage());
+					throw e;
+				}
+			}
+		}
+	}
+
+	private void createAndSendClusterMessage(int tenantId, String tenantDomain, UUID uuid,
+	                                         String clusterDomain, String clusterSubdomain) {
+
+		SynchronizeGitRepositoryRequest request =
+		                                          new SynchronizeGitRepositoryRequest(tenantId,
+		                                                                              tenantDomain,
+		                                                                              uuid);
+
+		ClusteringAgent clusteringAgent =
+		                                  DataHolder.getServerConfigContext()
+		                                            .getAxisConfiguration().getClusteringAgent();
+		GroupManagementAgent groupMgtAgent =
+		                                     clusteringAgent.getGroupManagementAgent(clusterDomain,
+		                                                                             clusterSubdomain);
+
+		try {
+			log.info("Sending Request to.. " + clusterDomain + " : " + clusterSubdomain);
+			groupMgtAgent.send(request);
+			
+		} catch (ClusteringFault e) {
+			e.printStackTrace();
+		}
+		 
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInfoBean.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInfoBean.java
new file mode 100644
index 0000000..859dcc6
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInfoBean.java
@@ -0,0 +1,78 @@
+/**
+ * 
+ */
+package org.wso2.carbon.adc.mgt.service;
+
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.CartridgeInfo;
+
+/**
+ * @author wso2
+ *
+ */
+public class RepositoryInfoBean {
+
+	private String repoURL;
+	private String cartridgeAlias;
+	private String tenantDomain;
+	private String userName;
+	private String password;
+	private String[] dirArray;
+	private CartridgeInfo cartridgeInfo;	
+	
+	
+	public RepositoryInfoBean(String repoURL, String cartridgeAlias, String tenantDomain,
+                              String userName, String password, String[] dirArray, CartridgeInfo cartridgeInfo) {
+	    this.repoURL = repoURL;
+	    this.cartridgeAlias = cartridgeAlias;
+	    this.tenantDomain = tenantDomain;
+	    this.userName = userName;
+	    this.setPassword(password);
+	    this.dirArray = dirArray;
+	    this.cartridgeInfo = cartridgeInfo;
+    }
+	public String getRepoURL() {
+    	return repoURL;
+    }
+	public void setRepoURL(String repoURL) {
+    	this.repoURL = repoURL;
+    }
+	public String getCartridgeAlias() {
+    	return cartridgeAlias;
+    }
+	public void setCartridgeAlias(String cartridgeAlias) {
+    	this.cartridgeAlias = cartridgeAlias;
+    }
+	public String getTenantDomain() {
+    	return tenantDomain;
+    }
+	public void setTenantDomain(String tenantDomain) {
+    	this.tenantDomain = tenantDomain;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String[] getDirArray() {
+    	return dirArray;
+    }
+	public void setDirArray(String[] dirArray) {
+    	this.dirArray = dirArray;
+    }
+	public CartridgeInfo getCartridgeInfo() {
+    	return cartridgeInfo;
+    }
+	public void setCartridgeInfo(CartridgeInfo cartridgeInfo) {
+    	this.cartridgeInfo = cartridgeInfo;
+    }
+    public String getPassword() {
+        return password;
+    }
+    public void setPassword(String password) {
+        this.password = password;
+    }
+	
+	
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInformationService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInformationService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInformationService.java
new file mode 100644
index 0000000..ded0e64
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/RepositoryInformationService.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.dao.RepositoryCredentials;
+import org.wso2.carbon.adc.mgt.utils.PersistenceManager;
+
+/**
+ * 
+ * Exposes information related to internally created repositories  
+ * 
+ */
+public class RepositoryInformationService {
+
+	private static final Log log = LogFactory.getLog(RepositoryInformationService.class);
+
+	public String getRepositoryUrl(int tenantId, String cartridgeType) throws Exception {
+
+		String repoUrl = null;
+		try {
+			repoUrl = PersistenceManager.getRepoURL(tenantId, cartridgeType);
+		} catch (Exception e) {
+			String msg = "System Exception is occurred when retriving repo URL";
+			log.error(msg + ". Reason :" + e.getMessage());
+			throw new Exception(msg);
+		}
+		if (repoUrl == null) {
+			log.error("Repository URL is not successfully retrieved " + "for tenant [" + tenantId +
+			          "] and cartridge [" + cartridgeType + "] ");
+		}
+		return repoUrl;
+	}
+
+    public RepositoryCredentials getRepositoryCredentials(int tenantId, String cartridgeType, String alias) throws Exception {
+
+    	RepositoryCredentials repoCredentials = null;
+        try {
+        	repoCredentials = PersistenceManager.getRepoCredentials(tenantId,cartridgeType, alias);
+        } catch (Exception e) {
+            String msg = "System Exception is occurred when retrieving user credentials";
+            log.error(msg + ". Reason :" + e.getMessage());
+            throw new Exception(msg);
+        }
+        if (repoCredentials == null) {
+            log.error("Repository credentials are not successfully retrieved " + "for tenant [" + tenantId +
+                    "] and cartridge [" + cartridgeType + "] ");
+        }
+        return repoCredentials;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/ApplicationManagementUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/ApplicationManagementUtil.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/ApplicationManagementUtil.java
new file mode 100644
index 0000000..504ca52
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/ApplicationManagementUtil.java
@@ -0,0 +1,1095 @@
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.rmi.RemoteException;
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+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.eclipse.jgit.api.Git;
+import org.eclipse.jgit.api.LsRemoteCommand;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.api.errors.InvalidRemoteException;
+import org.eclipse.jgit.api.errors.TransportException;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.storage.file.FileRepository;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+import org.wso2.carbon.adc.mgt.client.CloudControllerServiceClient;
+import org.wso2.carbon.adc.mgt.dao.CartridgeSubscription;
+import org.wso2.carbon.adc.mgt.dao.DataCartridge;
+import org.wso2.carbon.adc.mgt.dao.PortMapping;
+import org.wso2.carbon.adc.mgt.dao.Repository;
+import org.wso2.carbon.adc.mgt.dns.DNSManager;
+import org.wso2.carbon.adc.mgt.dto.Cartridge;
+import org.wso2.carbon.adc.mgt.dto.Policy;
+import org.wso2.carbon.adc.mgt.dto.RepositoryInformation;
+import org.wso2.carbon.adc.mgt.dto.SubscriptionInfo;
+import org.wso2.carbon.adc.mgt.exception.ADCException;
+import org.wso2.carbon.adc.mgt.exception.AlreadySubscribedException;
+import org.wso2.carbon.adc.mgt.exception.DuplicateCartridgeAliasException;
+import org.wso2.carbon.adc.mgt.exception.InvalidCartridgeAliasException;
+import org.wso2.carbon.adc.mgt.exception.InvalidRepositoryException;
+import org.wso2.carbon.adc.mgt.exception.NotSubscribedException;
+import org.wso2.carbon.adc.mgt.exception.PolicyException;
+import org.wso2.carbon.adc.mgt.exception.RepositoryCredentialsRequiredException;
+import org.wso2.carbon.adc.mgt.exception.RepositoryRequiredException;
+import org.wso2.carbon.adc.mgt.exception.RepositoryTransportException;
+import org.wso2.carbon.adc.mgt.exception.UnregisteredCartridgeException;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.adc.mgt.service.RepositoryInfoBean;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.adc.topology.mgt.serviceobjects.DomainContext;
+import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.Properties;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.Property;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import com.google.gson.Gson;
+
+/**
+ * This class contains utility methods used by ApplicationManagementService.
+ */
+public class ApplicationManagementUtil {
+
+    private static Log log = LogFactory.getLog(ApplicationManagementUtil.class);
+    private static volatile CloudControllerServiceClient serviceClient;
+
+    /**
+     * Method used to subscribe to cartridges.
+     */
+	public static SubscriptionInfo doSubscribe(String cartridgeType, String alias, String policy, String repoURL,
+			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
+			String dataCartridgeAlias, String username, int tenantId, String tenantDomain) throws ADCException,
+            PolicyException, UnregisteredCartridgeException, InvalidCartridgeAliasException,
+            DuplicateCartridgeAliasException, RepositoryRequiredException, AlreadySubscribedException,
+            RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
+
+		String clusterDomain = "";
+        String clusterSubDomain = CartridgeConstants.DEFAULT_SUBDOMAIN;
+        String mgtClusterDomain = "";
+        String mgtClusterSubDomain = CartridgeConstants.DEFAULT_MGT_SUBDOMAIN;
+        CartridgeSubscription subscription = null;
+        String mysqlPassword = null;
+        Repository repository = null;
+        DataCartridge dataCartridge = null;
+        String cartName = (alias != null && alias.trim().length() > 0) ? alias : cartridgeType;
+        String payloadZipFileName = "/tmp/" + UUID.randomUUID().toString() + ".zip";
+
+		log.info("Subscribing tenant [" + tenantId + "] with username [" + username + "] Cartridge Alias " + alias
+				+ ", Cartridge Type: " + cartridgeType + ", Repo URL: " + repoURL + ", Policy: " + policy);
+		
+		// Assign auto scaling only when necessary.
+		// Muti-tenant cartridge may not need a policy.
+		Policy autoScalingPolicy = null;
+		
+		CartridgeInfo cartridgeInfo;
+		try {
+			cartridgeInfo = getServiceClient().getCartridgeInfo(cartridgeType);
+		} catch (UnregisteredCartridgeException e) {
+			String message = cartridgeType
+					+ " is not a valid cartridge type. Please try again with a valid cartridge type.";
+			log.error(message);
+			throw e;
+		} catch (Exception e) {
+			String message = "Error getting info for " + cartridgeType;
+			log.error(message, e);
+			throw new ADCException(message, e);
+		}
+
+		validateCartridgeAlias(cartName, cartridgeType);
+		
+
+        if (cartridgeType.equals(CartridgeConstants.MYSQL_CARTRIDGE_NAME)) {
+        	
+        	autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
+        	
+        	if (autoScalingPolicy == null) {
+        		throw new PolicyException("Could not load default auto-scaling policy.");
+        	}
+        	if (log.isDebugEnabled()) {
+    			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
+    		}
+        	
+            dataCartridge = new DataCartridge();
+            mysqlPassword = generatePassword();
+            dataCartridge.setPassword(mysqlPassword);
+            dataCartridge.setDataCartridgeType(cartridgeType);
+            dataCartridge.setUserName(CartridgeConstants.MYSQL_DEFAULT_USER);
+            clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+
+            registerService(cartridgeType,
+                    clusterDomain,
+                    clusterSubDomain,
+                    createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mysqlPassword, "localhost", payloadZipFileName, tenantId, tenantDomain),
+                    "*",
+                    cartName + "." + cartridgeInfo.getHostName(),
+                    setRegisterServiceProperties(autoScalingPolicy, tenantId,cartName));
+            deletePayloadFile(payloadZipFileName);
+        } else {
+        	
+			if (!new Boolean(System.getProperty(CartridgeConstants.FEATURE_INTERNAL_REPO_ENABLED))) {
+				if (log.isDebugEnabled()) {
+					log.debug("Internal repo feature is not enabled.");
+				}
+
+				if (repoURL == null || repoURL.trim().length() == 0) {
+					throw new RepositoryRequiredException("External repository required for subscription");
+				}
+			}
+
+			if (repoURL != null && repoURL.trim().length() > 0) {
+				if (log.isDebugEnabled()) {
+					log.debug("Repo URL entered: " + repoURL);
+				}
+				// Validate Remote Repository.
+				validateRepository(repoURL, repoUsername, repoPassword, privateRepo,
+						new Boolean(System.getProperty(CartridgeConstants.FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED)));
+			}
+
+            try {
+                repository = manageRepository(repoURL, repoUsername, repoPassword, cartName, cartridgeInfo, username,
+                        tenantDomain);
+            } catch (Exception e) {
+                log.error(e.getMessage());
+                throw new ADCException(e);
+            }
+        	
+            // TODO: Check logic here
+            if (!cartridgeInfo.getMultiTenant()) {
+            	
+        		if (policy != null && policy.trim().length() > 0) {
+        			autoScalingPolicy = PolicyHolder.getInstance().getPolicy(policy);
+        		} else {
+        			autoScalingPolicy = PolicyHolder.getInstance().getDefaultPolicy();
+        		}
+        		if (autoScalingPolicy == null) {
+        			throw new PolicyException("Could not load auto-scaling policy.");
+        		}
+        		if (log.isDebugEnabled()) {
+        			log.debug("Selected Policy: " + new Gson().toJson(autoScalingPolicy));
+        		}
+
+                if (cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) { //carbon cartridge private jet mode
+
+                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+                    registerService(cartridgeType,
+                            clusterDomain,
+                            clusterSubDomain,
+                            createCarbonPayload(cartridgeInfo, cartName, alias, payloadZipFileName, tenantDomain, false),
+                            Integer.toString(tenantId),
+                            cartName + "." + cartridgeInfo.getHostName(),
+                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
+                    deletePayloadFile(payloadZipFileName);
+
+                } else {
+                    clusterDomain = getDynamicClusterDomain(cartridgeType, cartName, cartridgeInfo);
+
+                    String mySQLPassword = null;
+                    String mySQLHostName = null;
+
+                    if (dataCartridgeType != null && dataCartridgeType.trim().length() > 0 && dataCartridgeAlias != null
+                            && dataCartridgeAlias.trim().length() > 0) {
+                        if (log.isInfoEnabled()) {
+                            log.info("Retrieving Data Cartridge info for connect ... Alias : " + dataCartridgeAlias
+                                    + ", Type: " + dataCartridgeType);
+                        }
+
+                        //TODO: Optimize following logic. Same logic is used in MySQLPasswordConfigurer
+                        int maxAttempts = Integer.parseInt(System.getProperty(CartridgeConstants.MAX_ATTEMPTS, "50"));
+                        int i = 0;
+
+                        while (i < maxAttempts) {
+                            i++;
+                            Cartridge c = null;
+                            try {
+                                c = getCartridgeInfo(dataCartridgeAlias, tenantDomain);
+                            } catch (NotSubscribedException e) {
+                                // This cannot happen here.
+                            }
+                            if (c != null) {
+                                if (!c.getStatus().equals("ACTIVE")) {
+                                    try {
+                                        Thread.sleep(3000);
+                                    } catch (InterruptedException ignore) {
+                                    }
+                                } else {
+                                    mySQLPassword = c.getPassword();
+                                    mySQLHostName = c.getIp();
+                                    break;
+                                }
+                            }
+                        }
+                        log.info(" MYSQL Cartridge info retrieved ");
+                    }
+
+                    registerService(cartridgeType,
+                            clusterDomain,
+                            clusterSubDomain,
+                            createPayload(cartridgeInfo, cartName, autoScalingPolicy, repoURL, mySQLPassword,
+                                    mySQLHostName, payloadZipFileName, tenantId, tenantDomain), "*",
+                            cartName + "." + cartridgeInfo.getHostName(),
+                            setRegisterServiceProperties(autoScalingPolicy,tenantId,cartName));
+                    deletePayloadFile(payloadZipFileName);
+                }
+
+            } else {
+            	
+            	boolean allowMultipleSubscription = new Boolean(
+						System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
+
+				if (!allowMultipleSubscription) {
+					// If the cartridge is multi-tenant. We should not let users
+					// subscribe twice.
+					boolean subscribed;
+					try {
+						subscribed = PersistenceManager.isAlreadySubscribed(cartridgeType, tenantId);
+					} catch (Exception e) {
+						String msg = "Error checking whether the cartridge type " + cartridgeType
+								+ " is already subscribed";
+						log.error(msg, e);
+						throw new ADCException(msg, e);
+					}
+					
+					if (subscribed) {
+						String msg = "Already subscribed to " + cartridgeType
+								+ ". This multi-tenant cartridge will not be available to subscribe";
+						if (log.isDebugEnabled()) {
+							log.debug(msg);
+						}
+						throw new AlreadySubscribedException(msg, cartridgeType);
+					}
+				}
+
+                TopologyManagementService topologyService = DataHolder.getTopologyMgtService();
+                DomainContext[] domainContexts = topologyService.getDomainsAndSubdomains(cartridgeType, tenantId);
+                log.info("Retrieved " + domainContexts.length + " domain and corresponding subdomain pairs");
+
+                if (domainContexts.length > 0) {
+                	                        if(domainContexts.length > 2) {
+                	                            if(log.isDebugEnabled())
+                	                                log.debug("Too many domain sub domain pairs");
+                	                       }
+                	
+                	                        for (int i = 0 ; i < domainContexts.length ; i++) {
+                	                            if(domainContexts[i].getSubDomain().equalsIgnoreCase("mgt")) {
+                	                                mgtClusterDomain = domainContexts[i].getDomain();
+                	                                mgtClusterSubDomain = domainContexts[i].getSubDomain();
+                	                            }
+                	                          else
+                	                          {
+                	                              clusterDomain = domainContexts[i].getDomain();
+                	                              clusterSubDomain = domainContexts[i].getSubDomain();
+                	                          }
+                	                      }
+                } else {
+                	String msg = "Domain contexts not found for " + cartridgeType + " and tenant id " + tenantId;
+                    log.warn(msg);
+                    throw new ADCException(msg);
+                }
+            }
+        }
+
+        subscription =
+                createCartridgeSubscription(cartridgeInfo, autoScalingPolicy,
+                        cartridgeType, cartName, tenantId, tenantDomain,
+                        repository, clusterDomain, clusterSubDomain,
+                        mgtClusterDomain, mgtClusterSubDomain, dataCartridge);
+
+        try {
+			PersistenceManager.persistSubscription(subscription);
+		} catch (Exception e) {
+			throw new ADCException("Error Saving Subscription", e);
+		}
+        addDNSEntry(alias, cartridgeType);
+        return createSubscriptionResponse(subscription, repository);
+
+    }
+    
+    private static File getPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL,
+                                   String mySQLPassword, String mySQLHost, String payloadZipFileName,
+                                   int tenantId, String tenantDomain) throws Exception {
+        String payloadString = "";
+
+        payloadString += "TENANT_RANGE=" + "*";
+        payloadString += ",TENANT_ID=" + tenantId;
+        payloadString +=
+            ",REPO_INFO_EPR=" +
+                    System.getProperty(CartridgeConstants.REPO_INFO_EPR);
+        payloadString +=
+                ",CARTRIDGE_AGENT_EPR=" +
+                        System.getProperty(CartridgeConstants.CARTRIDGE_AGENT_EPR);
+        payloadString += createPortMappingPayloadString(cartridgeInfo);
+        payloadString += ",HOST_NAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
+        payloadString += ",MIN=" + policy.getMinAppInstances();
+        payloadString += ",MAX=" + policy.getMaxAppInstances();
+        payloadString += ",SERVICE=" + cartridgeInfo.getType();
+        payloadString += ",TENANT_CONTEXT=" + tenantDomain;
+        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeName;
+
+        String gitRepoURL = null;
+        if (repoURL != null) {
+            gitRepoURL = repoURL;
+        } else {
+            gitRepoURL = "git@" + System.getProperty(CartridgeConstants.GIT_HOST_IP) + ":" + tenantDomain
+                    + System.getProperty("file.separator") + cartridgeName + ".git";
+        }
+        payloadString += ",GIT_REPO=" + gitRepoURL;
+        payloadString += ",APP_PATH=" + cartridgeInfo.getBaseDir();
+        payloadString += ",BAM_IP=" + System.getProperty(CartridgeConstants.BAM_IP);
+        payloadString += ",BAM_PORT=" + System.getProperty(CartridgeConstants.BAM_PORT);
+
+        // MYSQL params
+        payloadString += ",MYSQL_HOST=" + mySQLHost;
+        payloadString += ",MYSQL_USER=" + "root";
+        payloadString += ",MYSQL_PASSWORD=" + mySQLPassword;
+        
+        DecimalFormat df = new DecimalFormat("##.##");
+        df.setParseBigDecimal(true);
+
+        // Autoscaling params
+        payloadString += ",ALARMING_LOWER_RATE=" + df.format(policy.getAlarmingLowerRate());
+        payloadString += ",ALARMING_UPPER_RATE=" + df.format(policy.getAlarmingUpperRate());
+        payloadString += ",MAX_REQUESTS_PER_SEC=" + policy.getMaxRequestsPerSecond();
+        payloadString += ",ROUNDS_TO_AVERAGE=" + policy.getRoundsToAverage();
+        payloadString += ",SCALE_DOWN_FACTOR=" + df.format(policy.getScaleDownFactor());
+
+        log.info("** Payload ** " + payloadString);
+        
+        String payloadStringTempFile = "launch-params";
+
+        FileWriter fstream = new FileWriter(payloadStringTempFile);
+        BufferedWriter out = new BufferedWriter(fstream);
+        out.write(payloadString);
+        out.close();
+
+        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
+        ZipOutputStream zos = new ZipOutputStream(fos);
+
+		addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
+
+		File folder = new File(CarbonUtils.getCarbonHome()+
+				File.separator + "repository"
+				+ File.separator + "resources" + File.separator + "user-data");
+		for (File fileEntry : folder.listFiles()) {
+			if (!fileEntry.isDirectory()) {
+				addToZipFile(folder.getPath(), fileEntry.getName(), zos);
+			}
+		}
+
+        zos.close();
+        fos.close();
+
+        return new File(payloadZipFileName);
+    }
+
+    private static File getCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias,
+                                          String payloadZipFileName, String tenantDomain, boolean isMultitenant) throws Exception {
+
+        String payloadString = "";
+        payloadString += "DEPLOYMENT=" + "default";  //TODO: Currently hard coded but can be either manager, worker or default.
+        //payloadString += ",DOMAIN=" + "s2.wso2.com";
+        payloadString += ",SERVICE=" + cartridgeInfo.getType();
+        //payloadString += ",TENANT_ID=" + tenantId;
+        payloadString += ",SC_IP=" + System.getProperty(CartridgeConstants.SC_IP);
+        payloadString += ",CARTRIDGE_ALIAS=" + cartridgeAlias;
+        payloadString += ",MULTITENANT=" + "false";
+
+        if(isMultitenant) { //not used at the moment
+            payloadString += ",DOMAIN=" + "wso2." + cartridgeInfo.getType() + ".domain";
+            payloadString += ",HOSTNAME=" + cartridgeInfo.getType() + ".s2.wso2.com";
+
+        } else {
+            payloadString += ",DOMAIN=" + cartridgeName + "." + cartridgeInfo.getHostName() + "." + cartridgeInfo.getType() +
+                    ".domain";
+            payloadString += ",HOSTNAME=" + cartridgeName + "." + cartridgeInfo.getHostName();
+        }
+
+        log.info("** Payload ** " + payloadString);
+
+        String payloadStringTempFile = "launch-params";
+
+        FileWriter fstream = new FileWriter(payloadStringTempFile);
+        BufferedWriter out = new BufferedWriter(fstream);
+        out.write(payloadString);
+        out.close();
+
+        FileOutputStream fos = new FileOutputStream(payloadZipFileName);
+        ZipOutputStream zos = new ZipOutputStream(fos);
+
+        addToZipFile(System.getProperty("user.dir"), payloadStringTempFile, zos);
+
+        zos.close();
+        fos.close();
+
+        return new File(payloadZipFileName);
+    }
+
+    private static String createPortMappingPayloadString(CartridgeInfo cartridgeInfo) {
+        // port mappings
+        StringBuilder portMapBuilder = new StringBuilder();
+        org.wso2.carbon.stratos.cloud.controller.util.xsd.PortMapping[] portMappings = cartridgeInfo.getPortMappings();
+        for (org.wso2.carbon.stratos.cloud.controller.util.xsd.PortMapping portMapping : portMappings) {
+            String port = portMapping.getPort();
+            String protocol = portMapping.getProtocol();
+            String proxyPort = portMapping.getProxyPort();
+            portMapBuilder.append(protocol).append(":").append(port).append(":").append(proxyPort).append("|");
+        }
+
+        // remove last "|" character
+        String portMappingString = portMapBuilder.toString();
+        String portMappingPayloadString = null;
+        if (portMappingString.charAt(portMappingString.length() - 1) == '|') {
+            portMappingPayloadString = portMappingString.substring(0, portMappingString.length() - 1);
+        } else {
+            portMappingPayloadString = portMappingString;
+        }
+
+        return ",PORTS=" + portMappingPayloadString;
+    }
+
+    private static void addToZipFile(String dir, String fileName, ZipOutputStream zos) throws FileNotFoundException,
+            IOException {
+
+        log.info("Writing '" + fileName + "' to zip file");
+
+        File file = new File(dir+File.separator+fileName);
+        FileInputStream fis = new FileInputStream(file);
+        ZipEntry zipEntry = new ZipEntry(fileName);
+        zos.putNextEntry(zipEntry);
+
+        byte[] bytes = new byte[1024];
+        int length;
+        while ((length = fis.read(bytes)) >= 0) {
+            zos.write(bytes, 0, length);
+        }
+
+        zos.closeEntry();
+        fis.close();
+    }
+
+    private static DataHandler createPayload(CartridgeInfo cartridgeInfo, String cartridgeName, Policy policy, String repoURL, String mySQLPwd, String mySQLHost,
+                                             String payloadZipFileName, int tenantId,
+                                             String tenantDomain)
+            throws ADCException {
+
+        FileDataSource dataSource = null;
+        File payloadFile = null;
+        try {
+            payloadFile = getPayload(cartridgeInfo, cartridgeName,
+            		policy, repoURL,
+                    mySQLPwd, mySQLHost, payloadZipFileName, tenantId, tenantDomain);
+            dataSource = new FileDataSource(payloadFile);
+        } catch (Exception e) {
+            String msg = "Exception : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException("Subscribe failed ", e);
+        }
+        return new DataHandler(dataSource);
+    }
+
+    private static DataHandler createCarbonPayload (CartridgeInfo cartridgeInfo, String cartridgeName, String cartridgeAlias, String payloadZipFileName,
+                                                    String tenantDomain, boolean isMultitenant) throws ADCException {
+
+        FileDataSource dataSource = null;
+        File payloadFile = null;
+        try {
+            payloadFile = getCarbonPayload(cartridgeInfo, cartridgeName, cartridgeAlias, payloadZipFileName,
+                    tenantDomain, isMultitenant);
+            dataSource = new FileDataSource(payloadFile);
+
+        } catch (Exception e) {
+            String msg = "Exception : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException("Subscribe failed ", e);
+        }
+
+        return new DataHandler(dataSource);
+    }
+
+    protected static String getAppDeploymentDirPath(String cartridge, AxisConfiguration axisConfig) {
+        return axisConfig.getRepository().getPath() + File.separator + cartridge;
+    }
+
+    private static CartridgeSubscription createCartridgeSubscription(CartridgeInfo cartridgeInfo,
+                                                                     Policy policy,
+                                                                     String cartridgeType,
+                                                                     String cartridgeName,
+                                                                     int tenantId,
+                                                                     String tenantDomain,
+                                                                     Repository repository,
+                                                                     String clusterDomain,
+                                                                     String clusterSubDomain,
+                                                                     String mgtClusterDomain,
+                                                                     String mgtClusterSubDomain,
+                                                                     DataCartridge dataCartridge) {
+
+        CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
+        cartridgeSubscription.setCartridge(cartridgeType);
+        cartridgeSubscription.setAlias(cartridgeName);
+        cartridgeSubscription.setClusterDomain(clusterDomain);
+        cartridgeSubscription.setClusterSubdomain(clusterSubDomain);
+               cartridgeSubscription.setMgtClusterDomain(mgtClusterDomain);
+                cartridgeSubscription.setMgtClusterSubDomain(mgtClusterSubDomain);
+        String hostName = null;
+        if (cartridgeInfo.getMultiTenant()) {
+            hostName = cartridgeInfo.getHostName();
+        } else {
+            hostName = cartridgeName + "." + cartridgeInfo.getHostName();
+        }
+        cartridgeSubscription.setHostName(hostName);
+        if (policy != null) {
+        	// Policy can be null for multi-tenant cartridge
+        	cartridgeSubscription.setPolicy(policy.getName());
+        }
+        cartridgeSubscription.setRepository(repository);
+        cartridgeSubscription.setPortMappings(createPortMappings(cartridgeInfo));
+        cartridgeSubscription.setProvider(cartridgeInfo.getProvider());
+        cartridgeSubscription.setDataCartridge(dataCartridge);
+        cartridgeSubscription.setTenantId(tenantId);
+        cartridgeSubscription.setTenantDomain(tenantDomain);
+        cartridgeSubscription.setBaseDirectory(cartridgeInfo.getBaseDir());
+        cartridgeSubscription.setState("PENDING");
+        return cartridgeSubscription;
+    }
+
+
+    private static List<PortMapping> createPortMappings(CartridgeInfo cartridgeInfo) {
+        List<PortMapping> portMappings = new ArrayList<PortMapping>();
+
+        if (cartridgeInfo.getPortMappings() != null) {
+            for (org.wso2.carbon.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo.getPortMappings()) {
+                PortMapping portMap = new PortMapping();
+                portMap.setPrimaryPort(portMapping.getPort());
+                portMap.setProxyPort(portMapping.getProxyPort());
+                portMap.setType(portMapping.getProtocol());
+                portMappings.add(portMap);
+            }
+        }
+        return portMappings;
+    }
+
+    public static CloudControllerServiceClient getServiceClient() throws AxisFault {
+        if (serviceClient == null) {
+            synchronized (CloudControllerServiceClient.class) {
+                if (serviceClient == null) {
+                    serviceClient = new CloudControllerServiceClient(
+                            System.getProperty(CartridgeConstants.AUTOSCALER_SERVICE_URL));
+                }
+            }
+        }
+        return serviceClient;
+    }
+
+    public static int getTenantId(ConfigurationContext configurationContext) {
+        int tenantId = MultitenantUtils.getTenantId(configurationContext);
+        if(log.isDebugEnabled()) {
+            log.debug("Returning tenant ID : " + tenantId);
+        }
+        return tenantId;
+    }
+
+	private static void validateCartridgeAlias(String alias, String cartridgeType) throws InvalidCartridgeAliasException, DuplicateCartridgeAliasException, ADCException {
+		// Do not use quotes in messages, current UI JavaScript does not work if there are quotes
+		// TODO: Fix message display in UI
+		String patternString = "([a-z0-9]+([-][a-z0-9])*)+";
+        Pattern pattern = Pattern.compile(patternString);
+        
+        if (!pattern.matcher(alias).matches()) {
+        	String msg = "The alias " + alias + " can contain only alpha-numeric lowercase characters. Please enter a valid alias.";
+			log.error(msg);
+			throw new InvalidCartridgeAliasException(msg, cartridgeType, alias);
+        }
+		
+		boolean isAliasTaken = false;
+		try {			
+			isAliasTaken = PersistenceManager.isAliasAlreadyTaken(alias, cartridgeType);			
+		} catch (Exception e) {
+			String msg = "Exception : " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("Error when checking alias is already taken", e);
+		}
+		
+		if (isAliasTaken) {
+			String msg = "The alias " + alias + " is already taken. Please try again with a different alias.";
+			log.error(msg);
+			throw new DuplicateCartridgeAliasException(msg, cartridgeType, alias);
+		}
+	}
+	
+	public static RepositoryInformation validateRepository(String repoURL, String repoUsername, String repoPassword,
+			boolean privateRepo, boolean testConnection) throws RepositoryRequiredException, ADCException,
+			RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException {
+		RepositoryInformation repositoryInformation = new RepositoryInformation();
+		repositoryInformation.setRepoURL(repoURL);
+		if (log.isDebugEnabled()) {
+			log.debug("Validating Git Repository");
+		}
+
+		if (repoURL != null && repoURL.trim().length() > 0 && privateRepo) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo validation is a private repo: " + repoURL);
+			}
+			if (repoUsername == null || repoUsername.trim().length() == 0 || repoPassword == null
+					|| repoPassword.trim().length() == 0) {
+				throw new RepositoryCredentialsRequiredException(
+						"Username and Password are required for private repository");
+			}
+		}
+
+		if (!testConnection) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo validation is not enabled");
+			}
+			return repositoryInformation;
+		}
+
+		if (repoURL == null || repoURL.trim().length() == 0) {
+			// This means, no repo to validate.
+			return repositoryInformation;
+		}
+		
+		if (log.isDebugEnabled()) {
+			log.debug("External repo validation enabled");
+		}
+
+		// This assumes running on Linux.
+		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
+		CredentialsProvider credentialsProvider = null;
+		if (repoUsername != null && repoUsername.trim().length() > 0 && repoPassword != null
+				&& repoPassword.trim().length() > 0) {
+			if (log.isDebugEnabled()) {
+				log.debug("External repo credentails are passed: " + repoUsername);
+			}
+			credentialsProvider = new UsernamePasswordCredentialsProvider(repoUsername, repoPassword.toCharArray());
+		}
+
+		// Initialize temp local file repo
+		FileRepository localRepo = null;
+		try {
+			File f = new File(parentDirName + "/.git");
+			localRepo = new FileRepository(f);
+			if (log.isDebugEnabled()) {
+				log.debug("Local File Repo: " + f.getAbsoluteFile());
+			}
+		} catch (IOException e) {
+			throw new ADCException("Error creating local file repo", e);
+		}
+
+		Git git = new Git(localRepo);
+		LsRemoteCommand cmd = git.lsRemote().setRemote(repoURL);
+		if (credentialsProvider != null) {
+			cmd.setCredentialsProvider(credentialsProvider);
+		}
+		try {
+			Collection<Ref> collection = cmd.call();
+			List<String> refNames = new ArrayList<String>();
+			if (collection != null) {
+				for (Ref ref : collection) {
+					if (log.isDebugEnabled()) {
+						log.debug(repoURL + ": " + ref.getName());
+					}
+					refNames.add(ref.getName());
+				}
+			}
+			repositoryInformation.setRefName(refNames.toArray(new String[refNames.size()]));
+		} catch (InvalidRemoteException e) {
+			throw new InvalidRepositoryException("Provided repository url is not valid", e);
+		} catch (TransportException e) {
+			throw new RepositoryTransportException("Transport error when checking remote repository", e);
+		} catch (GitAPIException e) {
+			throw new ADCException("Git API error when checking remote repository", e);
+		}
+		return repositoryInformation;
+	}
+
+    private static String generatePassword() {
+
+        final int PASSWORD_LENGTH = 8;
+        StringBuffer sb = new StringBuffer();
+        for (int x = 0; x < PASSWORD_LENGTH; x++) {
+            sb.append((char) ((int) (Math.random() * 26) + 97));
+        }
+        return sb.toString();
+
+    }
+
+    private static void deletePayloadFile(String payloadZipFileName) {
+        File payloadFile = new File(payloadZipFileName);
+        payloadFile.delete();
+        log.info(" Payload file is deleted. ");
+    }
+
+    private static Properties setRegisterServiceProperties(Policy policy, int tenantId, String alias) {
+    	
+    	DecimalFormat df = new DecimalFormat("##.##");
+        df.setParseBigDecimal(true);
+
+        Properties properties = new Properties();
+        List<Property> allProperties = new ArrayList<Property>();
+        // min_app_instances
+        Property property = new Property();
+        property.setName("min_app_instances");
+        property.setValue(df.format(policy.getMinAppInstances()));
+        allProperties.add(property);
+        
+        
+     // max_app_instances
+        property = new Property();
+        property.setName("max_app_instances");
+        property.setValue(df.format(policy.getMaxAppInstances()));
+        allProperties.add(property);
+        
+        // max_requests_per_second
+        property = new Property();
+        property.setName("max_requests_per_second");
+        property.setValue(df.format(policy.getMaxRequestsPerSecond()));
+        allProperties.add(property);
+        
+        // alarming_upper_rate
+        property = new Property();
+        property.setName("alarming_upper_rate");
+        property.setValue(df.format(policy.getAlarmingUpperRate()));
+        allProperties.add(property);
+        
+     // alarming_lower_rate
+        property = new Property();
+        property.setName("alarming_lower_rate");
+        property.setValue(df.format(policy.getAlarmingLowerRate()));
+        allProperties.add(property);
+        
+        // scale_down_factor
+        property = new Property();
+        property.setName("scale_down_factor");
+        property.setValue(df.format(policy.getScaleDownFactor()));
+        allProperties.add(property);
+        
+     // rounds_to_average
+        property = new Property();
+        property.setName("rounds_to_average");
+        property.setValue(df.format(policy.getRoundsToAverage()));
+        allProperties.add(property);
+        
+       // tenant id
+        property = new Property();
+        property.setName("tenant_id");
+        property.setValue(String.valueOf(tenantId));
+        allProperties.add(property);
+        
+        // alias
+        property = new Property();
+        property.setName("alias");
+        property.setValue(String.valueOf(alias));
+        allProperties.add(property);
+        
+        properties.setProperties(allProperties.toArray(new Property[allProperties.size()]));
+        return properties;
+    }
+
+    private static String convertRepoURL(String gitURL) {
+        String convertedHttpURL = null;
+        if (gitURL != null && gitURL.startsWith("git@")) {
+            StringBuilder httpRepoUrl = new StringBuilder();
+            httpRepoUrl.append("http://");
+            String[] urls = gitURL.split(":");
+            String[] hostNameArray = urls[0].split("@");
+            String hostName = hostNameArray[1];
+            httpRepoUrl.append(hostName).append("/").append(urls[1]);
+            convertedHttpURL = httpRepoUrl.toString();
+        } else if (gitURL != null && gitURL.startsWith("http")) {
+            convertedHttpURL = gitURL;
+        }
+        return convertedHttpURL;
+    }
+
+    private static void addDNSEntry(String alias, String cartridgeType) {
+        new DNSManager().addNewSubDomain(alias + "." + cartridgeType, System.getProperty(CartridgeConstants.ELB_IP));
+    }
+
+    private static SubscriptionInfo createSubscriptionResponse(CartridgeSubscription cartridgeSubscription, Repository repository) {
+    	SubscriptionInfo subscriptionInfo = new SubscriptionInfo();
+    	
+        if (repository != null && repository.getRepoName() != null) {
+        	subscriptionInfo.setRepositoryURL(convertRepoURL(repository.getRepoName()));
+        }
+        
+        subscriptionInfo.setHostname(cartridgeSubscription.getHostName());
+        
+        return subscriptionInfo;
+    }
+
+    private static String getDynamicClusterDomain(String cartridgeType, String cartName,
+                                                  CartridgeInfo cartridgeInfo) {
+        return cartName + "." + cartridgeInfo.getHostName() + "." + cartridgeType +
+                ".domain";
+    }
+
+    private static Repository manageRepository(String repoURL, String repoUserName, String repoUserPassword,
+                                               String cartName, CartridgeInfo cartridgeInfo, String username,
+                                               String tenantDomain)
+            throws Exception {
+
+        Repository repository = new Repository();
+        if (repoURL != null && repoURL.trim().length() > 0) {
+            log.info("External REPO URL is provided as [" + repoURL +
+                    "]. Therefore not creating a new repo.");
+            //repository.setRepoName(repoURL.substring(0, repoURL.length()-4)); // remove .git part
+            repository.setRepoName(repoURL);
+            repository.setRepoUserName(repoUserName);
+            repository.setRepoUserPassword(repoUserPassword);
+        } else {
+
+            //log.info("External REPO URL is not provided. Therefore creating a new repo. Adding to Executor");
+            log.info("External git repo url not provided for tenant "
+                    + tenantDomain + ", creating an git internal repository");
+
+            // for internal repos  internal git server username and password is used.
+            repository.setRepoUserName(System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME));
+            repository.setRepoUserPassword(System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD));
+            /*repoCreationExecutor.execute(new RepositoryCreator(new RepositoryInfoBean(repoURL,
+                    cartName,
+                    tenantDomain,
+                    repository.getRepoUserName(),
+                    repository.getRepoUserPassword(),
+                    cartridgeInfo.getDeploymentDirs(),
+                    cartridgeInfo)));*/
+            new RepositoryCreator(new RepositoryInfoBean(repoURL,
+                    cartName,
+                    tenantDomain,
+                    repository.getRepoUserName(),
+                    repository.getRepoUserPassword(),
+                    cartridgeInfo.getDeploymentDirs(),
+                    cartridgeInfo)).createInternalRepository();
+            String repoName = tenantDomain + "/" + cartName;
+            repository.setRepoName("https://" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":8443/git/" + repoName);
+
+        }
+        return repository;
+    }
+
+    public static Cartridge getCartridgeInfo(String alias, String tenantDomain) throws ADCException, NotSubscribedException {
+        log.info("Alias: " + alias);
+        if (alias == null) {
+            String msg = "Provided alias is empty";
+            log.error(msg);
+            throw new ADCException("Alias you provided is empty.");
+        }
+
+        CartridgeSubscription sub;
+        try {
+            sub = PersistenceManager.getSubscription(tenantDomain, alias);
+        } catch (Exception e) {
+            String message = "Cannot get subscription info for " + tenantDomain + " and alias " + alias;
+            log.error(message, e);
+            throw new ADCException(message, e);
+        }
+        if (sub == null) {
+            String msg = "Info request for not subscribed cartridge";
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
+        }
+
+        log.info("Cluster domain : " + sub.getClusterDomain() + " cartridge: " + sub.getCartridge());
+        
+        CartridgeInfo cartridgeInfo = null;
+        try {
+            cartridgeInfo = getServiceClient().getCartridgeInfo(sub.getCartridge());
+        } catch (Exception e) {
+            throw new ADCException("Cannot get cartridge info: " + sub.getCartridge(), e);
+        }
+
+        TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+
+        String[] ips =
+                topologyMgtService.getActiveIPs(sub.getCartridge(),
+                        sub.getClusterDomain(),
+                        sub.getClusterSubdomain());
+        return populateCartridgeInfo(cartridgeInfo, sub, ips, tenantDomain);
+    }
+
+    private static void registerService(String cartridgeType, String domain, String subDomain,
+                                        DataHandler payload, String tenantRange, String hostName, Properties properties)
+            throws ADCException, UnregisteredCartridgeException {
+        log.info("Register service..");
+        try {
+            getServiceClient().register(domain, subDomain, cartridgeType, payload, tenantRange,
+                    hostName, properties);
+        } catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+            String msg = "Exception is occurred in register service operation. Reason :" + e.getMessage();
+            log.error(msg, e);
+            throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
+        } catch (RemoteException e) {
+        	log.error("Remote Error", e);
+        	throw new ADCException("An error occurred in subscribing process");
+        }
+    }
+
+    public static Cartridge populateCartridgeInfo(CartridgeInfo cartridgeInfo, CartridgeSubscription sub, String[] ips, String tenantDomain) throws ADCException {
+    	Cartridge cartridge = new Cartridge();
+        if (ips != null && ips.length > 0) {
+			if (log.isDebugEnabled()) {
+				log.debug("Found IPs: " + Arrays.toString(ips) + " for " + cartridgeInfo.getType() + ", "
+						+ sub.getAlias());
+			}
+			if (CartridgeConstants.DATA_CARTRIDGE_PROVIDER.equals(sub.getProvider())) {
+				// FIXME Temporary fix for SPI-301
+				cartridge.setIp(ips[ips.length - 1]);
+				if (sub.getDataCartridge() != null) {
+					if (log.isDebugEnabled()) {
+						log.debug("Data Cartridge Info: " + sub.getDataCartridge().getUserName());
+					}
+					cartridge.setPassword(sub.getDataCartridge().getPassword());
+					cartridge.setDbUserName(sub.getDataCartridge().getUserName());
+				}
+			}
+			if (cartridgeInfo.getMultiTenant()) { // TODO refactor logic for carbon cartridges.
+				cartridge.setStatus(CartridgeConstants.ACTIVE);
+				cartridge.setActiveInstances(ips.length);
+			} else {
+				Map<String, String> instanceIpMap;
+				try {
+					instanceIpMap = PersistenceManager.getCartridgeInstanceInfo(ips, sub.getClusterDomain(),
+							sub.getClusterSubdomain());
+					cartridge.setActiveInstances(Collections.frequency(instanceIpMap.values(),
+							CartridgeConstants.ACTIVE));
+					cartridge.setStatus(checkCartridgeStatus(instanceIpMap));
+				} catch (Exception e) {
+					throw new ADCException("Error checking cartridge status");
+				}
+
+                if(cartridgeInfo.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2)) {
+
+                    List<Member> members = getMemberInstances(sub.getClusterDomain(), sub.getClusterSubdomain());
+                    if(members != null) {
+                        int activeInstancesCount = 0;
+                        for (Member member : members) {
+                            if (member != null && member.isActive() && member.getDomain().equals(sub.getClusterDomain())) {
+                                cartridge.setStatus(CartridgeConstants.ACTIVE);
+                                activeInstancesCount ++;
+                            }
+                        }
+                        cartridge.setActiveInstances(activeInstancesCount);
+                    }
+                }
+			}
+        } else {
+            log.warn("IPs have not returned through Topology Management for " + sub.getAlias());
+            cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
+        }
+        cartridge.setDisplayName(cartridgeInfo.getDisplayName());
+        cartridge.setDescription(cartridgeInfo.getDescription());
+        cartridge.setVersion(cartridgeInfo.getVersion());
+        cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
+
+        List<String> accessURLs = new ArrayList<String>();
+
+        if (cartridgeInfo.getPortMappings() != null) {
+            for (org.wso2.carbon.stratos.cloud.controller.util.xsd.PortMapping portMapping : cartridgeInfo
+                    .getPortMappings()) {
+                if (portMapping != null) {
+					try {
+						int port = Integer.parseInt(portMapping.getProxyPort());
+	                	String protocol = portMapping.getProtocol();
+
+	                	if ("http".equals(protocol) && port == 80) {
+	                	    port = -1;
+	                	} else if ("https".equals(protocol) && port == 443) {
+	                	    port = -1;
+	                	}
+	                	
+	                	String file = "";
+	                	if (CartridgeConstants.PROVIDER_NAME_WSO2.equals(cartridgeInfo.getProvider()) && !cartridgeInfo.getMultiTenant()) {
+	                		// Carbon Private Jet Cartridges
+	                		file = "/t/" + tenantDomain;
+	                	}
+	                	
+	                	URL serverURL = new URL(protocol, sub.getHostName(), port, file);
+						accessURLs.add(serverURL.toExternalForm());
+					} catch (MalformedURLException e) {
+						if (log.isErrorEnabled()) {
+							log.error("Error getting access URL for " + cartridgeInfo.getType(), e);
+						}
+					} catch (NumberFormatException e) {
+						if (log.isErrorEnabled()) {
+							log.error("Error getting port of access URL for " + cartridgeInfo.getType(), e);
+						}
+					}
+                }
+            }
+        }
+
+        cartridge.setAccessURLs(accessURLs.toArray(new String[accessURLs.size()]));
+
+        cartridge.setCartridgeAlias(sub.getAlias());
+        cartridge.setCartridgeType(sub.getCartridge());
+        cartridge.setHostName(sub.getHostName());
+        cartridge.setPolicy(sub.getPolicy());
+        Policy policy = PolicyHolder.getInstance().getPolicy(sub.getPolicy());
+        if (policy != null) {
+        	cartridge.setPolicyDescription(policy.getDescription());
+        }
+        cartridge.setProvider(sub.getProvider());
+        cartridge.setMappedDomain(sub.getMappedDomain());
+
+        if (sub.getRepository() != null) {
+            cartridge.setRepoURL(convertRepoURL(sub.getRepository().getRepoName()));
+        }
+        return cartridge;
+    }
+
+    private static List<Member> getMemberInstances(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent = DataHolder.getServerConfigContext()
+                .getAxisConfiguration().getClusteringAgent();
+        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
+
+        if (groupMgtAgent == null) {
+            log.warn("Group Management Agent not found for domain : " + domain +
+                    ", sub domain : " + subDomain);
+            return null;
+        }
+
+        List<Member> members = groupMgtAgent.getMembers();
+        if (members == null || members.isEmpty()) {
+            return null;
+        }
+
+        return members;
+    }
+
+    private static String checkCartridgeStatus(Map<String, String> instanceIpMap) {
+        if (instanceIpMap.values().contains(CartridgeConstants.ACTIVE)) {
+            return CartridgeConstants.ACTIVE;
+        } else
+            return CartridgeConstants.NOT_READY;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeAppType.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeAppType.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeAppType.java
new file mode 100644
index 0000000..0406cb2
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeAppType.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+/**
+ *
+ */
+public class CartridgeAppType {
+	private String appType;
+	private boolean appSpecificMapping;
+
+	public String getAppType() {
+		return appType;
+	}
+
+	public void setAppType(String appType) {
+		this.appType = appType;
+	}
+
+	public boolean isAppSpecificMapping() {
+		return appSpecificMapping;
+	}
+
+	public void setAppSpecificMapping(boolean appSpecificMapping) {
+		this.appSpecificMapping = appSpecificMapping;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConfigFileReader.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConfigFileReader.java
new file mode 100644
index 0000000..55d6810
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConfigFileReader.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class CartridgeConfigFileReader {
+
+	private static String carbonHome = CarbonUtils.getCarbonHome();
+
+	private static final Log log = LogFactory.getLog(CartridgeConfigFileReader.class);
+
+	/**
+	 * 
+	 * Reads cartridge-config.properties file and assign properties to system
+	 * properties
+	 * 
+	 */
+	public static void readProperties() {
+
+		Properties properties = new Properties();
+		try {
+			properties.load(new FileInputStream(carbonHome + File.separator + "repository" +
+			                                    File.separator + "conf" + File.separator +
+			                                    "cartridge-config.properties"));
+		} catch (Exception e) {
+			log.error("Exception is occurred in reading properties file. Reason:" + e.getMessage());
+		}
+		if (log.isInfoEnabled()) {
+			log.info("Setting config properties into System properties");
+		}
+
+		for (String name : properties.stringPropertyNames()) {
+			String value = properties.getProperty(name);
+			System.setProperty(name, value);
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConstants.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConstants.java
new file mode 100644
index 0000000..90fad61
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeConstants.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+public class CartridgeConstants {
+    public static final String SC_IP = "sc.ip";
+	public static final String AUTOSCALER_SERVICE_URL = "autoscalerService.url";
+    public static final String ALIAS_NAMESPACE ="http://org.wso2.securevault/configuration";
+    public static final String ALIAS_LOCALPART ="secretAlias";
+    public static final String ALIAS_PREFIX ="svns";
+	public static final String CARTRIDGE_AGENT_EPR = "cartridge.agent.epr";
+	public static final String GIT_HOST_NAME = "git.host.name";
+	public static final String GIT_HOST_IP = "git.host.ip";
+	public static final String SUBSCRIPTION_ACTIVE = "SUBSCRIPTION_ACTIVE";
+	public static final String SUBSCRIPTION_INACTIVE = "SUBSCRIPTION_INACTIVE";
+	public static final String REPO_NOTIFICATION_URL = "git.repo.notification.url";
+	public static final String ACTIVE = "ACTIVE";
+	public static final String NOT_READY = "NOT-READY";
+	public static final String SUBSCRIBED = "SUBSCRIBED";
+
+	public static final String DB_DATASOURCE = "adc.datasource";
+	public static final String DB_URL = "adc.jdbc.url";
+	public static final String DB_DRIVER = "adc.jdbc.driver";
+	public static final String DB_USERNAME = "adc.jdbc.username";
+	public static final String DB_PASSWORD = "adc.jdbc.password";
+	public static final String BAM_IP = "bam.ip";
+	public static final String BAM_PORT = "bam.port";
+	public static final String SUDO_SH = "sudo sh";
+	public static final String APPEND_SCRIPT = "append.script";
+	public static final String REMOVE_SCRIPT = "remove.script";
+	public static final String BIND_FILE_PATH = "bind.file.path";
+	public static final String ELB_IP = "elb.ip";
+	public static final String REPO_KEY_PATH = "repo.key.path";
+	public static final String REPO_KEY = "repo.key";
+	public static final String MAX_ATTEMPTS = "max.attempts";
+	public static final String CARTRIDGE_KEY = "cartridge.key";
+	
+	public static final String FEATURE_EXTERNAL_REPO_VAIDATION_ENABLED = "feature.externalrepo.validation.enabled";
+	public static final String FEATURE_INTERNAL_REPO_ENABLED = "feature.internalrepo.enabled";
+	public static final String FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED = "feature.multitenant.multiplesubscription.enabled";
+	
+	public static final String MYSQL_CARTRIDGE_NAME = "mysql";
+	public static final String DEFAULT_SUBDOMAIN = "__$default";
+	public static final String DEFAULT_MGT_SUBDOMAIN = "mgt";
+	public static final String MYSQL_DEFAULT_USER = "root";
+	public static final String PROVIDER_NAME_WSO2 = "wso2";
+	public static final String NOT_SUBSCRIBED = "NOT-SUBSCRIBED";
+    public static final String SECURITY_KEY_FILE = "gitRepoKey.xml";
+    public static final String SECURITY_KEY = "securityKey";
+    public static final String DEFAULT_SECURITY_KEY = "tvnw63ufg9gh5111";
+    public static final String DATA_CARTRIDGE_PROVIDER = "data";
+	public static final String REPO_INFO_EPR = "repository.info.epr";
+	public static final String INTERNAL_GIT_USERNAME = "internal.repo.username";
+	public static final String INTERNAL_GIT_PASSWORD = "internal.repo.password";
+
+    public static final class DomainMappingInfo {
+		public static final String ACTUAL_HOST = "actual.host";
+		public static final String HOSTINFO = "hostinfo/";
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeDomain.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeDomain.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeDomain.java
new file mode 100644
index 0000000..b3ac6e0
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/CartridgeDomain.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+/**
+ *
+ */
+public class CartridgeDomain {
+
+	private String primaryPort;
+	private String proxyPort;
+	private String type;
+	private String tenantId;
+	private int min;
+	private int max;
+	private String cartridgeType;
+	private boolean volume;
+	private String tenantDomain;
+	private String clusterDomain;
+	private String clusterSubDomain;
+
+	private String hostName;
+	private boolean started;
+
+	public String getPrimaryPort() {
+		return primaryPort;
+	}
+
+	public String getProxyPort() {
+		return proxyPort;
+	}
+
+	public String getType() {
+		return type;
+	}
+
+	public String getTenantId() {
+		return tenantId;
+	}
+
+	public int getMin() {
+		return min;
+	}
+
+	public int getMax() {
+		return max;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public boolean getVolume() {
+		return volume;
+	}
+
+	public String getTenantDomain() {
+		return tenantDomain;
+	}
+
+	public void setPrimaryPort(String primaryPort) {
+		this.primaryPort = primaryPort;
+	}
+
+	public void setProxyPort(String proxyPort) {
+		this.proxyPort = proxyPort;
+	}
+
+	public void setType(String type) {
+		this.type = type;
+	}
+
+	public void setTenantId(String tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public void setMin(int min) {
+		this.min = min;
+	}
+
+	public void setMax(int max) {
+		this.max = max;
+	}
+
+	public void setCartridgeType(String cartridgeType) {
+		this.cartridgeType = cartridgeType;
+	}
+
+	public void setVolume(boolean volume) {
+		this.volume = volume;
+	}
+
+	public void setTenantDomain(String tenantDomain) {
+		this.tenantDomain = tenantDomain;
+	}
+
+	public void setStarted(boolean started) {
+		this.started = started;
+	}
+
+	public boolean isStarted() {
+		return started;
+	}
+
+	public String getHostName() {
+		return hostName;
+	}
+
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+
+	public String getClusterDomain() {
+		return clusterDomain;
+	}
+
+	public void setClusterDomain(String clusterDomain) {
+		this.clusterDomain = clusterDomain;
+	}
+
+	public String getClusterSubDomain() {
+		return clusterSubDomain;
+	}
+
+	public void setClusterSubDomain(String clusterSubDomain) {
+		this.clusterSubDomain = clusterSubDomain;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/DomainInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/DomainInfo.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/DomainInfo.java
new file mode 100644
index 0000000..82eba2d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/DomainInfo.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+public class DomainInfo {
+
+	String domain;
+	String subDomain;
+
+	public String getDomain() {
+		return domain;
+	}
+
+	public void setDomain(String domain) {
+		this.domain = domain;
+	}
+
+	public String getSubDomain() {
+		return subDomain;
+	}
+
+	public void setSubDomain(String subDomain) {
+		this.subDomain = subDomain;
+	}
+
+}


[38/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Cartridge.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Cartridge.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Cartridge.java
new file mode 100644
index 0000000..c014cbb
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Cartridge.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dto;
+
+public class Cartridge implements Comparable<Cartridge> {
+
+    private String displayName;
+    private String description;
+	private String cartridgeAlias;
+	private String cartridgeType;
+	private int activeInstances;
+	private String status;
+	private String ip;
+	private String password;
+	private String provider;
+	private String version;
+	private boolean multiTenant;
+	private String hostName;
+	private String policy;
+	private String policyDescription;
+	private String repoURL;
+	private String dbUserName;
+	private String mappedDomain;
+
+	private String[] accessURLs;
+
+	public String getDisplayName() {
+		return displayName;
+	}
+
+	public void setDisplayName(String displayName) {
+		this.displayName = displayName;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+	public void setCartridgeAlias(String cartridgeAlias) {
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public void setCartridgeType(String cartridgeType) {
+		this.cartridgeType = cartridgeType;
+	}
+
+	public int getActiveInstances() {
+		return activeInstances;
+	}
+
+	public void setActiveInstances(int activeInstances) {
+		this.activeInstances = activeInstances;
+	}
+
+	public String getStatus() {
+		return status;
+	}
+
+	public void setStatus(String status) {
+		this.status = status;
+	}
+
+	public String getIp() {
+		return ip;
+	}
+
+	public void setIp(String ip) {
+		this.ip = ip;
+	}
+
+	public String getPassword() {
+		return password;
+	}
+
+	public void setPassword(String password) {
+		this.password = password;
+	}
+
+	public String getProvider() {
+    	return provider;
+    }
+
+	public void setProvider(String provider) {
+    	this.provider = provider;
+    }
+
+	public String getVersion() {
+    	return version;
+    }
+
+	public void setVersion(String version) {
+    	this.version = version;
+    }
+
+	public boolean isMultiTenant() {
+		return multiTenant;
+	}
+
+	public void setMultiTenant(boolean multiTenant) {
+		this.multiTenant = multiTenant;
+	}
+
+	public String getHostName() {
+    	return hostName;
+    }
+
+	public void setHostName(String hostName) {
+    	this.hostName = hostName;
+    }
+
+	public String getPolicy() {
+		return policy;
+	}
+
+	public void setPolicy(String policy) {
+		this.policy = policy;
+	}
+
+	public String getPolicyDescription() {
+		return policyDescription;
+	}
+
+	public void setPolicyDescription(String policyDescription) {
+		this.policyDescription = policyDescription;
+	}
+
+	public String getRepoURL() {
+    	return repoURL;
+    }
+
+	public void setRepoURL(String repoURL) {
+    	this.repoURL = repoURL;
+    }
+
+	public String getDbUserName() {
+    	return dbUserName;
+    }
+
+	public String[] getAccessURLs() {
+		return accessURLs;
+	}
+
+	public void setAccessURLs(String[] accessURLs) {
+		this.accessURLs = accessURLs;
+	}
+
+	public void setDbUserName(String dbUserName) {
+    	this.dbUserName = dbUserName;
+    }
+
+	public String getMappedDomain() {
+		return mappedDomain;
+	}
+
+	public void setMappedDomain(String mappedDomain) {
+		this.mappedDomain = mappedDomain;
+	}
+
+	@Override
+	public int compareTo(Cartridge o) {
+		int compare = 0;
+		if (cartridgeAlias != null && o.cartridgeAlias != null) {
+			compare = cartridgeAlias.compareTo(o.cartridgeAlias);
+		}
+		if (compare == 0 && cartridgeType != null && o.cartridgeType != null) {
+			compare = cartridgeType.compareTo(o.cartridgeType);
+		}
+		return compare;
+	}
+	
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeDetail.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeDetail.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeDetail.java
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeInformation.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeInformation.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeInformation.java
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeWrapper.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeWrapper.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeWrapper.java
new file mode 100644
index 0000000..d1d640b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/CartridgeWrapper.java
@@ -0,0 +1,49 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed under the Apache License, Version 2.0 (the "License");             
+ * you may not use this file except in compliance with the License.            
+ * You may obtain a copy of the License at                                     
+ *                                                                             
+ *      http://www.apache.org/licenses/LICENSE-2.0                             
+ *                                                                             
+ * Unless required by applicable law or agreed to in writing, software         
+ * distributed under the License is distributed on an "AS IS" BASIS,           
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    
+ * See the License for the specific language governing permissions and         
+ * limitations under the License.                                              
+ */
+package org.wso2.carbon.adc.mgt.dto;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.wso2.carbon.utils.Pageable;
+
+/**
+ * This class holds paginated information about cartridges
+ */
+public final class CartridgeWrapper implements Pageable {
+
+	private Cartridge[] cartridges;
+	private int numberOfPages;
+
+	public CartridgeWrapper() {
+	}
+
+	public int getNumberOfPages() {
+		return numberOfPages;
+	}
+
+	public void setNumberOfPages(int numberOfPages) {
+		this.numberOfPages = numberOfPages;
+	}
+
+	public <T> void set(List<T> items) {
+		this.cartridges = items.toArray(new Cartridge[items.size()]);
+	}
+
+	public Cartridge[] getCartridges() {
+		return cartridges != null ? Arrays.copyOf(cartridges, cartridges.length) : null;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Policy.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Policy.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Policy.java
new file mode 100644
index 0000000..4464787
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/Policy.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.dto;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+public class Policy implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String name;
+	private String description;
+	private boolean defaultPolicy;
+
+	private Integer minAppInstances;
+	private Integer maxAppInstances;
+	private Integer maxRequestsPerSecond;
+	private BigDecimal alarmingUpperRate;
+	private BigDecimal alarmingLowerRate;
+	private BigDecimal scaleDownFactor;
+	private Integer roundsToAverage;
+
+	public Policy() {
+	}
+
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public boolean isDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public void setDefaultPolicy(boolean defaultPolicy) {
+		this.defaultPolicy = defaultPolicy;
+	}
+
+	public Integer getMinAppInstances() {
+		return minAppInstances;
+	}
+
+	public void setMinAppInstances(Integer minAppInstances) {
+		this.minAppInstances = minAppInstances;
+	}
+
+	public Integer getMaxAppInstances() {
+		return maxAppInstances;
+	}
+
+	public void setMaxAppInstances(Integer maxAppInstances) {
+		this.maxAppInstances = maxAppInstances;
+	}
+
+	public Integer getMaxRequestsPerSecond() {
+		return maxRequestsPerSecond;
+	}
+
+	public void setMaxRequestsPerSecond(Integer maxRequestsPerSecond) {
+		this.maxRequestsPerSecond = maxRequestsPerSecond;
+	}
+
+	public BigDecimal getAlarmingUpperRate() {
+		return alarmingUpperRate;
+	}
+
+	public void setAlarmingUpperRate(BigDecimal alarmingUpperRate) {
+		this.alarmingUpperRate = alarmingUpperRate;
+	}
+
+	public BigDecimal getAlarmingLowerRate() {
+		return alarmingLowerRate;
+	}
+
+	public void setAlarmingLowerRate(BigDecimal alarmingLowerRate) {
+		this.alarmingLowerRate = alarmingLowerRate;
+	}
+
+	public BigDecimal getScaleDownFactor() {
+		return scaleDownFactor;
+	}
+
+	public void setScaleDownFactor(BigDecimal scaleDownFactor) {
+		this.scaleDownFactor = scaleDownFactor;
+	}
+
+	public Integer getRoundsToAverage() {
+		return roundsToAverage;
+	}
+
+	public void setRoundsToAverage(Integer roundsToAverage) {
+		this.roundsToAverage = roundsToAverage;
+	}
+
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + ((name == null) ? 0 : name.hashCode());
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (!(obj instanceof Policy))
+			return false;
+		Policy other = (Policy) obj;
+		if (name == null) {
+			if (other.name != null)
+				return false;
+		} else if (!name.equals(other.name))
+			return false;
+		return true;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/PolicyDefinition.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/PolicyDefinition.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/PolicyDefinition.java
new file mode 100644
index 0000000..f4f0936
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/PolicyDefinition.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class PolicyDefinition implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String name;
+	private String description;
+	private boolean defaultPolicy;
+
+	public PolicyDefinition() {
+	}
+
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public String getDescription() {
+		return description;
+	}
+
+	public void setDescription(String description) {
+		this.description = description;
+	}
+
+	public boolean isDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public void setDefaultPolicy(boolean defaultPolicy) {
+		this.defaultPolicy = defaultPolicy;
+	}
+
+	@Override
+	public int hashCode() {
+		final int prime = 31;
+		int result = 1;
+		result = prime * result + ((name == null) ? 0 : name.hashCode());
+		return result;
+	}
+
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj)
+			return true;
+		if (obj == null)
+			return false;
+		if (!(obj instanceof PolicyDefinition))
+			return false;
+		PolicyDefinition other = (PolicyDefinition) obj;
+		if (name == null) {
+			if (other.name != null)
+				return false;
+		} else if (!name.equals(other.name))
+			return false;
+		return true;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/RepositoryInformation.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/RepositoryInformation.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/RepositoryInformation.java
new file mode 100644
index 0000000..ee3ad88
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/RepositoryInformation.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class RepositoryInformation implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String repoURL;
+	private String[] refName;
+
+	public String getRepoURL() {
+		return repoURL;
+	}
+
+	public void setRepoURL(String repoURL) {
+		this.repoURL = repoURL;
+	}
+
+	public String[] getRefName() {
+		return refName;
+	}
+
+	public void setRefName(String[] refName) {
+		this.refName = refName;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/SubscriptionInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/SubscriptionInfo.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/SubscriptionInfo.java
new file mode 100644
index 0000000..f823b28
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/SubscriptionInfo.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.dto;
+
+import java.io.Serializable;
+
+public class SubscriptionInfo implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+
+	private String hostname;
+	private String repositoryURL;
+
+	public String getHostname() {
+		return hostname;
+	}
+
+	public void setHostname(String hostname) {
+		this.hostname = hostname;
+	}
+
+	public String getRepositoryURL() {
+		return repositoryURL;
+	}
+
+	public void setRepositoryURL(String repositoryURL) {
+		this.repositoryURL = repositoryURL;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/ADCException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/ADCException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/ADCException.java
new file mode 100644
index 0000000..17f95fe
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/ADCException.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class ADCException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public ADCException() {
+		super();
+	}
+
+	public ADCException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public ADCException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public ADCException(Throwable cause) {
+		super(cause);
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/AlreadySubscribedException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/AlreadySubscribedException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/AlreadySubscribedException.java
new file mode 100644
index 0000000..97f91ef
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/AlreadySubscribedException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class AlreadySubscribedException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	public AlreadySubscribedException(String message, String cartridgeType, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public AlreadySubscribedException(String message, String cartridgeType) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DomainMappingExistsException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DomainMappingExistsException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DomainMappingExistsException.java
new file mode 100644
index 0000000..406fdce
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DomainMappingExistsException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class DomainMappingExistsException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String domain;
+
+	public DomainMappingExistsException(String message, String domain, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.domain = domain;
+	}
+
+	public DomainMappingExistsException(String message, String domain) {
+		super(message);
+		this.message = message;
+		this.domain = domain;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getDomain() {
+		return domain;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DuplicateCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DuplicateCartridgeAliasException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DuplicateCartridgeAliasException.java
new file mode 100644
index 0000000..9b5ce0d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/DuplicateCartridgeAliasException.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class DuplicateCartridgeAliasException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	private final String cartridgeAlias;
+
+	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public DuplicateCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidCartridgeAliasException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidCartridgeAliasException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidCartridgeAliasException.java
new file mode 100644
index 0000000..3e4e538
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidCartridgeAliasException.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class InvalidCartridgeAliasException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	private final String cartridgeAlias;
+
+	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public InvalidCartridgeAliasException(String message, String cartridgeType, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidRepositoryException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidRepositoryException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidRepositoryException.java
new file mode 100644
index 0000000..b8ea044
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/InvalidRepositoryException.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class InvalidRepositoryException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public InvalidRepositoryException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/NotSubscribedException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/NotSubscribedException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/NotSubscribedException.java
new file mode 100644
index 0000000..4e7a9bd
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/NotSubscribedException.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class NotSubscribedException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeAlias;
+
+	public NotSubscribedException(String message, String cartridgeAlias, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public NotSubscribedException(String message, String cartridgeAlias) {
+		super(message);
+		this.message = message;
+		this.cartridgeAlias = cartridgeAlias;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeAlias() {
+		return cartridgeAlias;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/PolicyException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/PolicyException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/PolicyException.java
new file mode 100644
index 0000000..fcf278e
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/PolicyException.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class PolicyException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	public PolicyException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public PolicyException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryCredentialsRequiredException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryCredentialsRequiredException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryCredentialsRequiredException.java
new file mode 100644
index 0000000..9f990d1
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryCredentialsRequiredException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class RepositoryCredentialsRequiredException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public RepositoryCredentialsRequiredException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryCredentialsRequiredException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryRequiredException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryRequiredException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryRequiredException.java
new file mode 100644
index 0000000..2e5067b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryRequiredException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class RepositoryRequiredException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public RepositoryRequiredException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryRequiredException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryTransportException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryTransportException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryTransportException.java
new file mode 100644
index 0000000..db37fc8
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/RepositoryTransportException.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class RepositoryTransportException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	public RepositoryTransportException(String message, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+	}
+
+	public RepositoryTransportException(String message) {
+		super(message);
+		this.message = message;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/UnregisteredCartridgeException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/UnregisteredCartridgeException.java
new file mode 100644
index 0000000..3362ca6
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/exception/UnregisteredCartridgeException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.exception;
+
+public class UnregisteredCartridgeException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	private final String message;
+
+	private final String cartridgeType;
+
+	public UnregisteredCartridgeException(String message, String cartridgeType, Throwable cause) {
+		super(message, cause);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public UnregisteredCartridgeException(String message, String cartridgeType) {
+		super(message);
+		this.message = message;
+		this.cartridgeType = cartridgeType;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public String getCartridgeType() {
+		return cartridgeType;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/ADCManagementServerComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/ADCManagementServerComponent.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/ADCManagementServerComponent.java
new file mode 100644
index 0000000..f081167
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/ADCManagementServerComponent.java
@@ -0,0 +1,106 @@
+/*
+        * Copyright WSO2, Inc. (http://wso2.com)
+        *
+        * Licensed under the Apache License, Version 2.0 (the "License");
+        * you may not use this file except in compliance with the License.
+        * You may obtain a copy of the License at
+        *
+        * http://www.apache.org/licenses/LICENSE-2.0
+        *
+        * Unless required by applicable law or agreed to in writing, software
+        * distributed under the License is distributed on an "AS IS" BASIS,
+        * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+        * See the License for the specific language governing permissions and
+        * limitations under the License.
+        */
+package org.wso2.carbon.adc.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.adc.mgt.utils.CartridgeConfigFileReader;
+import org.wso2.carbon.adc.mgt.utils.StratosDBUtils;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name=
+ *                "org.wso2.carbon.hosting.mgt.internal.ADCManagementServerComponent"
+ *                immediate="true"
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ * @scr.reference name="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @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="topology.mgt.service"
+ *                interface=
+ *                "org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setTopologyManagementService"
+ *                unbind="unsetTopologyManagementService"
+ */
+
+public class ADCManagementServerComponent {
+    private static final Log log = LogFactory.getLog(ADCManagementServerComponent.class);
+
+	protected void activate(ComponentContext componentContext) throws Exception {
+		if (log.isInfoEnabled()) {
+			log.info("ADC Management Server Component activated");
+		}
+
+		try {
+			CartridgeConfigFileReader.readProperties();
+			StratosDBUtils.initialize();
+		} catch (Exception e) {
+			log.fatal("Error while initializing the ADC Management Server Component", e);
+		}
+	}
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setClientConfigContext(contextService.getClientConfigContext());
+        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
+
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setClientConfigContext(null);
+        DataHolder.setServerConfigContext(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        // keeping the realm service in the DataHolder class
+        DataHolder.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        try {
+            DataHolder.setRegistry(registryService.getGovernanceSystemRegistry());
+        } catch (Exception e) {
+            log.error("Cannot  retrieve governance Registry", e);
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+    }
+
+    protected void setTopologyManagementService(TopologyManagementService topologyMgtService) {
+        DataHolder.setTopologyMgtService(topologyMgtService);
+    }
+
+    protected void unsetTopologyManagementService(TopologyManagementService topologyMgtService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/DataHolder.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/DataHolder.java
new file mode 100644
index 0000000..ed65306
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/DataHolder.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Holds the some of the data required by the webapps component
+ */
+public class DataHolder {
+	private static ConfigurationContext clientConfigContext;
+	private static ConfigurationContext serverConfigContext;
+
+	private static RealmService realmService;
+	private static Registry registry;
+	private static TopologyManagementService topologyMgtService;
+
+	public static RealmService getRealmService() {
+		return realmService;
+	}
+
+	public static void setRealmService(RealmService realmService) {
+		DataHolder.realmService = realmService;
+	}
+
+	public static Registry getRegistry() {
+		return registry;
+	}
+
+	public static ConfigurationContext getClientConfigContext() {
+		CarbonUtils.checkSecurity();
+		return clientConfigContext;
+	}
+
+	public static void setClientConfigContext(ConfigurationContext clientConfigContext) {
+		DataHolder.clientConfigContext = clientConfigContext;
+	}
+
+	public static ConfigurationContext getServerConfigContext() {
+		CarbonUtils.checkSecurity();
+		return serverConfigContext;
+	}
+
+	public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
+		DataHolder.serverConfigContext = serverConfigContext;
+	}
+
+	public static void setRegistry(Registry registry) {
+		DataHolder.registry = registry;
+	}
+
+	public static TopologyManagementService getTopologyMgtService() {
+		return topologyMgtService;
+	}
+
+	public static void setTopologyMgtService(TopologyManagementService topologyMgtService) {
+		DataHolder.topologyMgtService = topologyMgtService;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingConstants.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingConstants.java
new file mode 100644
index 0000000..247946e
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingConstants.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.internal;
+
+/**
+ * Web Application Constants
+ */
+public final class HostingConstants {
+	public static final String WEBAPP_PREFIX = "webapps";
+	public static final String WEBAPP_DEPLOYMENT_FOLDER = "webapps";
+	public static final String WEBAPP_EXTENSION = "war";
+
+	public static final class WebappState {
+		public static final String STARTED = "started";
+		public static final String STOPPED = "stopped";
+
+		private WebappState() {
+		}
+	}
+
+	private HostingConstants() {
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingManagementActivator.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingManagementActivator.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingManagementActivator.java
new file mode 100644
index 0000000..3485cdb
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/internal/HostingManagementActivator.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Activator for the Webapp Management Bundle
+ */
+public class HostingManagementActivator implements BundleActivator {
+	private static final Log log = LogFactory.getLog(HostingManagementActivator.class);
+
+	@Override
+	public void start(final BundleContext bundleContext) {
+
+		// If Carbon is running as a webapp within some other servlet container,
+		// then we should
+		// uninstall this component
+		if (!CarbonUtils.isRunningInStandaloneMode()) {
+			Thread th = new Thread() {
+				@Override
+				public void run() {
+					try {
+						bundleContext.getBundle().uninstall();
+					} catch (Throwable e) {
+						log.warn("Error occurred while uninstalling hosting.mgt UI bundle", e);
+					}
+				}
+			};
+			try {
+				th.join();
+			} catch (InterruptedException ignored) {
+			}
+			th.start();
+		}
+	}
+
+	@Override
+	public void stop(BundleContext bundleContext) {
+		// No implementation required for this method
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/ApplicationManagementService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/ApplicationManagementService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/ApplicationManagementService.java
new file mode 100644
index 0000000..731e83c
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/ApplicationManagementService.java
@@ -0,0 +1,620 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.service;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.custom.domain.RegistryManager;
+import org.wso2.carbon.adc.mgt.dao.CartridgeSubscription;
+import org.wso2.carbon.adc.mgt.dns.DNSManager;
+import org.wso2.carbon.adc.mgt.dto.Cartridge;
+import org.wso2.carbon.adc.mgt.dto.CartridgeWrapper;
+import org.wso2.carbon.adc.mgt.dto.PolicyDefinition;
+import org.wso2.carbon.adc.mgt.dto.RepositoryInformation;
+import org.wso2.carbon.adc.mgt.dto.SubscriptionInfo;
+import org.wso2.carbon.adc.mgt.exception.*;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.adc.mgt.utils.*;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ *
+ *
+ *
+ */
+public class ApplicationManagementService extends AbstractAdmin {
+
+
+    private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
+    RegistryManager registryManager = new RegistryManager();
+
+    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+    String tenantDomain = carbonContext.getTenantDomain();
+    
+    /*
+     * Instantiate RepoNotificationService. Since this service is in the same 
+     * component (org.wso2.carbon.adc.mgt), a new object is created.
+     * TODO: Is there a better way to get this service?
+     */
+    private RepoNotificationService repoNotificationService = new RepoNotificationService();
+
+	/**
+	 * Get Available Cartridges
+	 * 
+	 * @return Available Cartridges
+	 */
+	public Cartridge[] getAvailableCartridges(boolean multiTenant) throws ADCException {
+		List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant);
+		// Following is very important when working with axis2
+		return cartridges.isEmpty() ? new Cartridge[0] : cartridges.toArray(new Cartridge[cartridges.size()]);
+	}
+
+	/**
+	 * Get Subscribed Cartridges
+	 * 
+	 * @return Subscribed Cartridges
+	 */
+	public Cartridge[] getSubscribedCartridges() throws ADCException {
+		checkSuperTenant();
+		List<Cartridge> cartridgeList = getSubscribedCartridges(null);
+		// Following is very important when working with axis2
+		return cartridgeList.isEmpty() ? new Cartridge[0] : cartridgeList.toArray(new Cartridge[cartridgeList.size()]);
+	}
+
+	/**
+	 * Get available cartridges
+	 */
+	public CartridgeWrapper getPagedAvailableCartridges(String cartridgeSearchString, int pageNumber, boolean multiTenant)
+			throws ADCException {
+		checkSuperTenant();
+		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
+		List<Cartridge> cartridges = getAvailableCartridges(cartridgeSearchString, multiTenant);
+    	
+		// TODO Improve pagination
+		if (!cartridges.isEmpty()) {
+			// Paginate only if cartridges are there.
+			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
+		} else {
+			// Must set this value as axis2 stub client will return an array
+			// with length = 1 and null element if cartridges[] is null
+			cartridgeWrapper.set(cartridges);
+		}
+		return cartridgeWrapper;
+	}
+
+	private List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant) throws ADCException {
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
+		
+		if (log.isDebugEnabled()) {
+			log.debug("Getting available cartridges. Search String: " + cartridgeSearchString + ", Multi-Tenant: " + multiTenant);
+		}
+		
+		boolean allowMultipleSubscription = new Boolean(
+				System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED));
+
+		try {
+			Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
+
+			String[] availableCartridges = ApplicationManagementUtil.getServiceClient().getRegisteredCartridges();
+
+			if (availableCartridges != null) {
+				for (String cartridgeType : availableCartridges) {
+					CartridgeInfo cartridgeInfo = null;
+					try {
+						cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(cartridgeType);
+					} catch (Exception e) {
+						if (log.isWarnEnabled()) {
+							log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: "
+									+ e.getMessage());
+						}
+					}
+					if (cartridgeInfo == null) {
+						// This cannot happen. But continue
+						if (log.isDebugEnabled()) {
+							log.debug("Cartridge Info not found: " + cartridgeType);
+						}
+						continue;
+					}
+					
+					if (multiTenant != null && !multiTenant && cartridgeInfo.getMultiTenant()) {
+						// Need only Single-Tenant cartridges
+						continue;
+					} else if (multiTenant != null && multiTenant && !cartridgeInfo.getMultiTenant()) {
+						// Need only Multi-Tenant cartridges
+						continue;
+					}
+					
+					if (!cartridgeMatches(cartridgeInfo, searchPattern)) {
+						continue;
+					}
+					
+					Cartridge cartridge = new Cartridge();
+					cartridge.setCartridgeType(cartridgeType);
+					cartridge.setProvider(cartridgeInfo.getProvider());
+					cartridge.setDisplayName(cartridgeInfo.getDisplayName());
+					cartridge.setDescription(cartridgeInfo.getDescription());
+					cartridge.setVersion(cartridgeInfo.getVersion());
+					cartridge.setMultiTenant(cartridgeInfo.getMultiTenant());
+					cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED);
+					cartridge.setCartridgeAlias("-");
+					cartridge.setActiveInstances(0);
+					cartridges.add(cartridge);
+					
+					if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) {
+						// If the cartridge is multi-tenant. We should not let users
+						// subscribe twice.
+						if (PersistenceManager.isAlreadySubscribed(cartridgeType,
+								ApplicationManagementUtil.getTenantId(getConfigContext()))) {
+							if (log.isDebugEnabled()) {
+								log.debug("Already subscribed to " + cartridgeType
+										+ ". This multi-tenant cartridge will not be available to subscribe");
+							}
+							cartridge.setStatus(CartridgeConstants.SUBSCRIBED);
+						}
+					}
+				}
+			} else {
+				if (log.isDebugEnabled()) {
+					log.debug("There are no available cartridges");
+				}
+			}
+		} catch (Exception e) {
+			String msg = "Error when getting available cartridges. " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("An error occurred getting available cartridges ", e);
+		}
+
+		Collections.sort(cartridges);
+
+		if (log.isDebugEnabled()) {
+			log.debug("Returning available cartridges " + cartridges.size());
+		}
+
+		return cartridges;
+	}
+
+	/**
+	 * Get subscribed cartridges
+	 */
+	public CartridgeWrapper getPagedSubscribedCartridges(String cartridgeSearchString, int pageNumber)
+			throws ADCException {
+		checkSuperTenant();
+		CartridgeWrapper cartridgeWrapper = new CartridgeWrapper();
+		List<Cartridge> cartridges = getSubscribedCartridges(cartridgeSearchString);
+
+		// TODO Improve pagination
+		if (!cartridges.isEmpty()) {
+			// Paginate only if cartridges are there.
+			DataPaginator.doPaging(pageNumber, cartridges, cartridgeWrapper);
+		} else {
+			cartridgeWrapper.set(cartridges);
+		}
+		return cartridgeWrapper;
+	}
+
+	private List<Cartridge> getSubscribedCartridges(String cartridgeSearchString) throws ADCException {
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
+		
+		if (log.isDebugEnabled()) {
+			log.debug("Getting subscribed cartridges. Search String: " + cartridgeSearchString);
+		}
+
+		try {
+			Pattern searchPattern = getSearchStringPattern(cartridgeSearchString);
+
+			List<CartridgeSubscription> subscriptionList = PersistenceManager
+					.retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
+
+			if (subscriptionList != null && !subscriptionList.isEmpty()) {
+				for (CartridgeSubscription subscription : subscriptionList) {
+					CartridgeInfo cartridgeInfo = null;
+					try {
+						cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(
+								subscription.getCartridge());
+					} catch (Exception e) {
+						if (log.isWarnEnabled()) {
+							log.warn("Error when calling getCartridgeInfo for " + subscription.getCartridge()
+									+ ", Error: " + e.getMessage());
+						}
+					}
+					if (cartridgeInfo == null) {
+						// This cannot happen. But continue
+						if (log.isDebugEnabled()) {
+							log.debug("Cartridge Info not found: " + subscription.getCartridge());
+						}
+						continue;
+					}
+					if (!cartridgeMatches(cartridgeInfo, subscription, searchPattern)) {
+						continue;
+					}
+					TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+					String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
+							subscription.getClusterDomain(), subscription.getClusterSubdomain());
+					Cartridge cartridge = ApplicationManagementUtil.populateCartridgeInfo(cartridgeInfo, subscription, ips, tenantDomain);
+					cartridges.add(cartridge);
+				}
+			} else {
+				if (log.isDebugEnabled()) {
+					log.debug("There are no subscribed cartridges");
+				}
+			}
+		} catch (Exception e) {
+			String msg = "Error when getting subscribed cartridges. " + e.getMessage();
+			log.error(msg, e);
+			throw new ADCException("An Error occurred when getting subscribed cartridges.", e);
+		}
+
+		Collections.sort(cartridges);
+
+		if (log.isDebugEnabled()) {
+			log.debug("Returning subscribed cartridges " + cartridges.size());
+		}
+
+		return cartridges;
+	}
+
+    private Pattern getSearchStringPattern(String searchString) {
+        if (log.isDebugEnabled()) {
+            log.debug("Creating search pattern for " + searchString);
+        }
+        if (searchString != null) {
+            // Copied from org.wso2.carbon.webapp.mgt.WebappAdmin.doesWebappSatisfySearchString(WebApplication, String)
+            String regex = searchString.toLowerCase().replace("..?", ".?").replace("..*", ".*").replaceAll("\\?", ".?")
+                    .replaceAll("\\*", ".*?");
+            if (log.isDebugEnabled()) {
+                log.debug("Created regex: " + regex + " for search string " + searchString);
+            }
+
+            Pattern pattern = Pattern.compile(regex);
+            return pattern;
+        }
+        return null;
+    }
+
+    // TODO: Improve search method
+    private boolean cartridgeMatches(CartridgeInfo cartridgeInfo, Pattern pattern) {
+        if (pattern != null) {
+            boolean matches = false;
+            if (cartridgeInfo.getDisplayName() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
+            }
+            if (!matches && cartridgeInfo.getDescription() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
+            }
+            return matches;
+        }
+        return true;
+    }
+
+    private boolean cartridgeMatches(CartridgeInfo cartridgeInfo, CartridgeSubscription cartridgeSubscription, Pattern pattern) {
+        if (pattern != null) {
+            boolean matches = false;
+            if (cartridgeInfo.getDisplayName() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find();
+            }
+            if (!matches && cartridgeInfo.getDescription() != null) {
+                matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find();
+            }
+            if (!matches && cartridgeSubscription.getCartridge() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getCartridge().toLowerCase()).find();
+            }
+            if (!matches && cartridgeSubscription.getAlias() != null) {
+                matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find();
+            }
+            return matches;
+        }
+        return true;
+    }
+    
+    public Cartridge getCartridgeInfo(String alias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+    	return ApplicationManagementUtil.getCartridgeInfo(alias, getTenantDomain());
+    }
+
+    public String[] getSubscribedCartridgeAliases() throws AxisFault {
+        try {
+            List<CartridgeSubscription> subscriptionList = PersistenceManager
+                    .retrieveSubscribedCartridges(ApplicationManagementUtil.getTenantId(getConfigContext()));
+            List<String> subscribedAliases = new ArrayList<String>();
+            for (CartridgeSubscription cartridgeSubscription : subscriptionList) {
+
+                if(cartridgeSubscription.getProvider().equalsIgnoreCase(CartridgeConstants.PROVIDER_NAME_WSO2) &&
+                        getCartridgeInfo(cartridgeSubscription.getAlias()).isMultiTenant()) {
+
+                    subscribedAliases.add(cartridgeSubscription.getCartridge());
+                } else {
+                    subscribedAliases.add(cartridgeSubscription.getAlias());
+                }
+            }
+            if(subscribedAliases.size() == 0) {
+                return new String[]{""};
+            } else {
+                return subscribedAliases.toArray(new String[subscribedAliases.size()]);
+            }
+
+        } catch (Exception e) {
+            String msg = "Exception in getting subscribed cartridge aliases :" + e.getMessage();
+            log.error(msg, e);
+            throw new AxisFault("An error occurred while getting subscribed cartridge aliases", e);
+        }
+    }
+    
+	public PolicyDefinition[] getPolicyDefinitions() {
+		List<PolicyDefinition> policyDefinitions = PolicyHolder.getInstance().getPolicyDefinitions();
+		return policyDefinitions == null || policyDefinitions.isEmpty() ? new PolicyDefinition[0] : policyDefinitions
+				.toArray(new PolicyDefinition[policyDefinitions.size()]);
+	}
+
+	/**
+	 * Subscribe to a cartridge
+	 */
+	public SubscriptionInfo subscribe(String cartridgeType, String alias, String policy, String repoURL,
+			boolean privateRepo, String repoUsername, String repoPassword, String dataCartridgeType,
+			String dataCartridgeAlias) throws ADCException, PolicyException, UnregisteredCartridgeException,
+            InvalidCartridgeAliasException, DuplicateCartridgeAliasException, RepositoryRequiredException,
+            AlreadySubscribedException, RepositoryCredentialsRequiredException, InvalidRepositoryException,
+            RepositoryTransportException {
+
+		checkSuperTenant();
+
+		return ApplicationManagementUtil.doSubscribe(cartridgeType, alias, policy, repoURL, privateRepo, repoUsername,
+				repoPassword, dataCartridgeType, dataCartridgeAlias, getUsername(),
+				ApplicationManagementUtil.getTenantId(getConfigContext()), getTenantDomain());
+
+	}
+
+
+    /**
+     * Unsubscribing the cartridge
+     *
+     * @param alias name of the cartridge to be unsubscribed
+     */
+    public void unsubscribe(String alias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, alias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + alias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+
+        if (subscription == null) {
+            String msg = "Tenant " + tenantDomain + " is not subscribed for " + alias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + alias, alias);
+        }
+        
+        try {
+            String clusterDomain = subscription.getClusterDomain();
+            String clusterSubDomain = subscription.getClusterSubdomain();
+
+            if (log.isDebugEnabled()) {
+                log.debug("Finding cartridge information for " + subscription.getCartridge());
+            }
+            CartridgeInfo cartridgeInfo = ApplicationManagementUtil.getServiceClient().getCartridgeInfo(subscription.getCartridge());
+            if (log.isDebugEnabled()) {
+                log.debug("Found " + cartridgeInfo.getDisplayName() + " for " + subscription.getCartridge());
+            }
+            if (!cartridgeInfo.getMultiTenant()) {
+                log.info("Terminating all instances of " + clusterDomain + " " + clusterSubDomain);
+                ApplicationManagementUtil.getServiceClient().terminateAllInstances(clusterDomain, clusterSubDomain);
+                log.info("All instances terminated.");
+                log.info("Unregistering services...");
+                ApplicationManagementUtil.getServiceClient().unregisterService(clusterDomain, clusterSubDomain);
+                log.info("Successfully terminated instances ..");
+            } else {
+                if (log.isInfoEnabled()) {
+                    log.info("Cartridge "
+                            + subscription.getCartridge()
+                            + " is a multi-tenant cartridge and therefore will not terminate all instances and unregister services");
+                }
+            }
+
+            new RepositoryFactory().destroyRepository(alias, tenantDomain, getUsername());
+            log.info("Repo is destroyed successfully.. ");
+
+            PersistenceManager.updateSubscriptionState(subscription.getSubscriptionId(), "UNSUBSCRIBED");
+            new DNSManager().removeSubDomain(subscription.getHostName());
+            registryManager.removeDomainMappingFromRegistry(subscription.getHostName());
+            TopologyManagementService topologyMgtService = DataHolder.getTopologyMgtService();
+			
+            String[] ips = topologyMgtService.getActiveIPs(subscription.getCartridge(),
+					subscription.getClusterDomain(), subscription.getClusterSubdomain());
+            PersistenceManager.updateInstanceState("INACTIVE", ips, subscription.getClusterDomain(), subscription.getClusterSubdomain(), subscription.getCartridge());
+
+        } catch (ADCException e) {
+        	log.error(e.getMessage(), e);
+        	throw e;
+        } catch (Exception e1) {
+            String msg1 = "Exception occurred :" + e1.getMessage();
+            log.error(msg1);
+            throw new ADCException("Unsubscribe failed for cartridge " + alias, e1);
+        }
+    }
+
+
+    public String addDomainMapping(String mappedDomain, String cartridgeAlias) throws ADCException, DomainMappingExistsException, NotSubscribedException {
+    	checkSuperTenant();
+    	// TODO Following was in CLI. Fix this
+		//		if (domain.indexOf('.') == -1) {
+		//			System.out.println("\nOwn domain should include a '.' ");
+		//		}
+
+        CartridgeSubscription subscription = null;
+        String actualHost = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+
+        try {
+        	actualHost = getActualHost(cartridgeAlias);
+            registryManager.addDomainMappingToRegistry(mappedDomain, actualHost);
+            log.info("Domain mapping is added for " + mappedDomain + " tenant: " + tenantDomain);
+            PersistenceManager.updateDomainMapping(
+                    ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeAlias, mappedDomain);
+        } catch (RegistryException e) {
+            String msg = "Unable to add the mapping due to registry transaction error";
+            log.error(msg, e);
+            throw new ADCException("Unable to add the mapping due to internal error!", e);
+        } catch (DomainMappingExistsException e) {
+            String msg = "Domain mapping already exists.";
+            log.error(msg, e);
+            throw e;
+        } catch (Exception e) {
+            String msg = "Error occurred. Reason : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException(msg, e);
+        }
+        return actualHost;
+    }
+
+	private String getActualHost(String cartridgeName) throws Exception {
+		return PersistenceManager.getHostNameForCartridgeName(
+				ApplicationManagementUtil.getTenantId(getConfigContext()), cartridgeName);
+	}
+
+    public void removeDomainMapping(String cartridgeAlias) throws ADCException, NotSubscribedException {
+    	checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        String actualHost = null;
+        
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+        
+        try {
+        	actualHost = getActualHost(cartridgeAlias);
+            registryManager.removeDomainMappingFromRegistry(actualHost);
+            log.info("Domain mapping is removed for " + actualHost + " tenant: " + tenantDomain);
+            PersistenceManager.updateDomainMapping(ApplicationManagementUtil.getTenantId(getConfigContext()),
+                    cartridgeAlias, null);
+        } catch (RegistryException e) {
+            String msg = "Unable to remove the mapping due to registry transaction error";
+            log.error(msg, e);
+            throw new ADCException("Unable to remove the mapping due to internal error!", e);
+        } catch (Exception e) {
+            String msg = "Error occurred. Reason : " + e.getMessage();
+            log.error(msg, e);
+            throw new ADCException(msg, e);
+        }
+    }
+
+	public void synchronizeRepository(String cartridgeAlias) throws ADCException, NotSubscribedException {
+		checkSuperTenant();
+        CartridgeSubscription subscription = null;
+        
+        // Validating subscription
+        try {
+			subscription = PersistenceManager.getSubscription(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			String msg = "Failed to get subscription for " + tenantDomain + " and alias " + cartridgeAlias;
+            log.error(msg, e);
+			throw new ADCException(msg, e);
+		}
+        if (subscription == null) {
+        	String msg = "Tenant " + tenantDomain + " is not subscribed for " + cartridgeAlias;
+            log.error(msg);
+            throw new NotSubscribedException("You have not subscribed for " + cartridgeAlias, cartridgeAlias);
+        }
+		
+		try {
+			repoNotificationService.notifyRepoUpdate(tenantDomain, cartridgeAlias);
+		} catch (Exception e) {
+			throw new ADCException(e.getMessage() != null ? e.getMessage() : "Failed to synchronize repository", e);
+		}
+	}
+
+    /**
+     * Validate authentication.
+     * First call of cli tool in the prompt mode after log in.
+     *
+     * @return The tenant domain
+     */
+	public String getTenantDomain() {
+		if (tenantDomain != null) {
+			// This means, authentication is successful
+			log.info("Tenant " + tenantDomain + " is authorized to access Application Management Service!");
+		}
+		return tenantDomain;
+	}
+    
+	/**
+	 * Allow to check whether features are enabled in the back-end
+	 * 
+	 * @param key
+	 *            The propery key
+	 * @return {@code true} if feature is enabled
+	 */
+	public boolean isFeatureEnabled(String key) {
+		if (key != null && key.startsWith("feature.")) {
+			return new Boolean(System.getProperty(key));
+		}
+		return false;
+	}
+
+	
+	public RepositoryInformation testRepositoryConnection(String repoURL, String repoUsername, String repoPassword, boolean privateRepo)
+			throws RepositoryRequiredException, ADCException, RepositoryCredentialsRequiredException,
+			InvalidRepositoryException, RepositoryTransportException {
+		return ApplicationManagementUtil.validateRepository(repoURL, repoUsername, repoPassword, privateRepo, true);
+	}
+	
+	// TODO Remove following when we support cartridge subscription for Super-tenant
+	private void checkSuperTenant() throws ADCException {
+		if (log.isDebugEnabled()) {
+			log.debug("Checking whether super tenant accesses the service methods. Tenant ID: "
+					+ ApplicationManagementUtil.getTenantId(getConfigContext()) + ", Tenant Domain: " + carbonContext.getTenantDomain());
+		}
+		if (MultitenantConstants.SUPER_TENANT_ID == ApplicationManagementUtil.getTenantId(getConfigContext())) {
+			throw new ADCException("Super Tenant is not allowed to complete requested operation");
+		}
+	}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/InstanceInformationManagementService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/InstanceInformationManagementService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/InstanceInformationManagementService.java
new file mode 100644
index 0000000..0ae3b4f
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/service/InstanceInformationManagementService.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.utils.PersistenceManager;
+
+public class InstanceInformationManagementService {
+
+	
+    private static final Log log = LogFactory.getLog(InstanceInformationManagementService.class);
+
+    /**
+    * Everytime an instance is started up, this operation is invoked
+    *            (by the AgentService)
+    * @param instanceIp
+    * @param tenantId
+    * @param clusterDomain
+    * @param clusterSubDomain
+    * @param cartridge
+    * @param state
+    *
+    */
+    public void updateInstanceState(String instanceIp,
+                                  int tenantId,
+                                  String clusterDomain,
+                                  String clusterSubDomain,
+                                  String cartridge,
+                                  String state) {
+
+      log.info("Message receieved in Instance Info Service.." + instanceIp + tenantId + clusterDomain + clusterSubDomain
+               + cartridge + state);
+
+      try {
+        PersistenceManager.persistCartridgeInstanceInfo(instanceIp, clusterDomain, clusterSubDomain, cartridge, state);
+    } catch (Exception e) {
+       log.error("Exception is occurred in updating instance state. Reason, " + e.getMessage());
+    }
+    }
+}


[16/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/search.gif
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/search.gif b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/search.gif
new file mode 100644
index 0000000..86f81ed
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/search.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/subscribe.gif
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/subscribe.gif b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/subscribe.gif
new file mode 100644
index 0000000..3b0b695
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/subscribe.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/unsubscribe.png
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/unsubscribe.png b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/unsubscribe.png
new file mode 100644
index 0000000..0c71c3c
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/unsubscribe.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/common.js
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/common.js b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/common.js
new file mode 100644
index 0000000..76910b2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/common.js
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+function setStratosFormSubmitFunction(form, validateFunction,
+		ajaxprocessorPage, successPage, commandButton) {
+	jQuery(form).submit(
+			function(event) {
+				if (validateFunction && typeof validateFunction == "function"
+						&& !validateFunction()) {
+					return false;
+				}
+
+				postToBEService(ajaxprocessorPage, jQuery(form).serialize(), successPage, commandButton);
+				return false;
+			});
+}
+
+function postToBEService(ajaxprocessorPage, data, successPage, commandButton, validateFunction) {
+	if (validateFunction && typeof validateFunction == "function"
+		&& !validateFunction()) {
+		return;
+	}
+	showWait(commandButton);
+	jQuery.post(ajaxprocessorPage, data).done(
+			function(data, textStatus, jqXHR) {
+				stopWait(commandButton);
+				var msg = jQuery(jqXHR.responseText).filter('#responseMsg')
+						.text();
+				if (successPage) {
+					CARBON.showInfoDialog(msg, function() {
+						location.href = successPage;
+					});
+				} else {
+					CARBON.showInfoDialog(msg);
+				}
+			}).fail(function(jqXHR, textStatus, errorThrown) {
+		var msg = jQuery(jqXHR.responseText).filter('#responseMsg').text();
+		if (msg && msg.length > 0) {
+			CARBON.showErrorDialog(msg);
+		} else {
+			// Ignore
+			// Refer SPI-310
+		}
+	}).complete(function() {
+		stopWait(commandButton);
+	});
+}
+
+function showWait(commandButton) {
+	jQuery.blockUI('Please wait...');
+	if (commandButton) {
+		jQuery(commandButton).attr("disabled", "disabled");
+	}
+	//jQuery("body").css("cursor", "wait");
+}
+
+function stopWait(commandButton) {
+	jQuery.unblockUI();
+	if (commandButton) {
+		jQuery(commandButton).removeAttr("disabled");
+	}
+	//jQuery("body").css("cursor", "auto");
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/jquery.blockUI-1.33.js
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/jquery.blockUI-1.33.js b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/jquery.blockUI-1.33.js
new file mode 100644
index 0000000..2b0a360
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/js/jquery.blockUI-1.33.js
@@ -0,0 +1,361 @@
+/*
+ * jQuery blockUI plugin
+ * Version 1.33  (09/14/2007)
+ * @requires jQuery v1.1.1
+ *
+ * $Id$
+ *
+ * Examples at: http://malsup.com/jquery/block/
+ * Copyright (c) 2007 M. Alsup
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ */
+ (function($) {
+/**
+ * blockUI provides a mechanism for blocking user interaction with a page (or parts of a page).
+ * This can be an effective way to simulate synchronous behavior during ajax operations without
+ * locking the browser.  It will prevent user operations for the current page while it is
+ * active ane will return the page to normal when it is deactivate.  blockUI accepts the following
+ * two optional arguments:
+ *
+ *   message (String|Element|jQuery): The message to be displayed while the UI is blocked. The message
+ *              argument can be a plain text string like "Processing...", an HTML string like
+ *              "<h1><img src="busy.gif" /> Please wait...</h1>", a DOM element, or a jQuery object.
+ *              The default message is "<h1>Please wait...</h1>"
+ *
+ *   css (Object):  Object which contains css property/values to override the default styles of
+ *              the message.  Use this argument if you wish to override the default
+ *              styles.  The css Object should be in a format suitable for the jQuery.css
+ *              function.  For example:
+ *              $.blockUI({
+ *                    backgroundColor: '#ff8',
+ *                    border: '5px solid #f00,
+ *                    fontWeight: 'bold'
+ *              });
+ *
+ * The default blocking message used when blocking the entire page is "<h1>Please wait...</h1>"
+ * but this can be overridden by assigning a value to $.blockUI.defaults.pageMessage in your
+ * own code.  For example:
+ *
+ *      $.blockUI.defaults.pageMessage = "<h1>Bitte Wartezeit</h1>";
+ *
+ * The default message styling can also be overridden.  For example:
+ *
+ *      $.extend($.blockUI.defaults.pageMessageCSS, { color: '#00a', backgroundColor: '#0f0' });
+ *
+ * The default styles work well for simple messages like "Please wait", but for longer messages
+ * style overrides may be necessary.
+ *
+ * @example  $.blockUI();
+ * @desc prevent user interaction with the page (and show the default message of 'Please wait...')
+ *
+ * @example  $.blockUI( { backgroundColor: '#f00', color: '#fff'} );
+ * @desc prevent user interaction and override the default styles of the message to use a white on red color scheme
+ *
+ * @example  $.blockUI('Processing...');
+ * @desc prevent user interaction and display the message "Processing..." instead of the default message
+ *
+ * @name blockUI
+ * @param String|jQuery|Element message Message to display while the UI is blocked
+ * @param Object css Style object to control look of the message
+ * @cat Plugins/blockUI
+ */
+$.blockUI = function(msg, css, opts) {
+    $.blockUI.impl.install(window, msg, css, opts);
+};
+
+// expose version number so other plugins can interogate
+$.blockUI.version = 1.33;
+
+/**
+ * unblockUI removes the UI block that was put in place by blockUI
+ *
+ * @example  $.unblockUI();
+ * @desc unblocks the page
+ *
+ * @name unblockUI
+ * @cat Plugins/blockUI
+ */
+$.unblockUI = function(opts) {
+    $.blockUI.impl.remove(window, opts);
+};
+
+/**
+ * Blocks user interaction with the selected elements.  (Hat tip: Much of
+ * this logic comes from Brandon Aaron's bgiframe plugin.  Thanks, Brandon!)
+ * By default, no message is displayed when blocking elements.
+ *
+ * @example  $('div.special').block();
+ * @desc prevent user interaction with all div elements with the 'special' class.
+ *
+ * @example  $('div.special').block('Please wait');
+ * @desc prevent user interaction with all div elements with the 'special' class
+ * and show a message over the blocked content.
+ *
+ * @name block
+ * @type jQuery
+ * @param String|jQuery|Element message Message to display while the element is blocked
+ * @param Object css Style object to control look of the message
+ * @cat Plugins/blockUI
+ */
+$.fn.block = function(msg, css, opts) {
+    return this.each(function() {
+		if (!this.$pos_checked) {
+            if ($.css(this,"position") == 'static')
+                this.style.position = 'relative';
+            if ($.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
+            this.$pos_checked = 1;
+        }
+        $.blockUI.impl.install(this, msg, css, opts);
+    });
+};
+
+/**
+ * Unblocks content that was blocked by "block()"
+ *
+ * @example  $('div.special').unblock();
+ * @desc unblocks all div elements with the 'special' class.
+ *
+ * @name unblock
+ * @type jQuery
+ * @cat Plugins/blockUI
+ */
+$.fn.unblock = function(opts) {
+    return this.each(function() {
+        $.blockUI.impl.remove(this, opts);
+    });
+};
+
+/**
+ * displays the first matched element in a "display box" above a page overlay.
+ *
+ * @example  $('#myImage').displayBox();
+ * @desc displays "myImage" element in a box
+ *
+ * @name displayBox
+ * @type jQuery
+ * @cat Plugins/blockUI
+ */
+$.fn.displayBox = function(css, fn, isFlash) {
+    var msg = this[0];
+    if (!msg) return;
+    var $msg = $(msg);
+    css = css || {};
+
+    var w = $msg.width()  || $msg.attr('width')  || css.width  || $.blockUI.defaults.displayBoxCSS.width;
+    var h = $msg.height() || $msg.attr('height') || css.height || $.blockUI.defaults.displayBoxCSS.height ;
+    if (w[w.length-1] == '%') {
+        var ww = document.documentElement.clientWidth || document.body.clientWidth;
+        w = parseInt(w) || 100;
+        w = (w * ww) / 100;
+    }
+    if (h[h.length-1] == '%') {
+        var hh = document.documentElement.clientHeight || document.body.clientHeight;
+        h = parseInt(h) || 100;
+        h = (h * hh) / 100;
+    }
+
+    var ml = '-' + parseInt(w)/2 + 'px';
+    var mt = '-' + parseInt(h)/2 + 'px';
+
+    // supress opacity on overlay if displaying flash content on mac/ff platform
+    var ua = navigator.userAgent.toLowerCase();
+    var opts = {
+        displayMode: fn || 1,
+        noalpha: isFlash && /mac/.test(ua) && /firefox/.test(ua)
+    };
+
+    $.blockUI.impl.install(window, msg, { width: w, height: h, marginTop: mt, marginLeft: ml }, opts);
+};
+
+
+// override these in your code to change the default messages and styles
+$.blockUI.defaults = {
+    // the message displayed when blocking the entire page
+    pageMessage:    '<h1>Please wait...</h1>',
+    // the message displayed when blocking an element
+    elementMessage: '', // none
+    // styles for the overlay iframe
+    overlayCSS:  { backgroundColor: '#fff', opacity: '0.5' },
+    // styles for the message when blocking the entire page
+    pageMessageCSS:    { width:'250px', margin:'-50px 0 0 -125px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'3px solid #aaa' },
+    // styles for the message when blocking an element
+    elementMessageCSS: { width:'250px', padding:'10px', textAlign:'center', backgroundColor:'#fff'},
+    // styles for the displayBox
+    displayBoxCSS: { width: '400px', height: '400px', top:'50%', left:'50%' },
+    // allow body element to be stetched in ie6
+    ie6Stretch: 1,
+    // supress tab nav from leaving blocking content?
+    allowTabToLeave: 0,
+    // Title attribute for overlay when using displayBox
+    closeMessage: 'Click to close',
+    // use fadeOut effect when unblocking (can be overridden on unblock call)
+    fadeOut:  1,
+    // fadeOut transition time in millis
+    fadeTime: 400
+};
+
+// the gory details
+$.blockUI.impl = {
+    box: null,
+    boxCallback: null,
+    pageBlock: null,
+    pageBlockEls: [],
+    op8: window.opera && window.opera.version() < 9,
+    ie6: $.browser.msie && /MSIE 6.0/.test(navigator.userAgent),
+    install: function(el, msg, css, opts) {
+        opts = opts || {};
+        this.boxCallback = typeof opts.displayMode == 'function' ? opts.displayMode : null;
+        this.box = opts.displayMode ? msg : null;
+        var full = (el == window);
+
+        // use logical settings for opacity support based on browser but allow overrides via opts arg
+        var noalpha = this.op8 || $.browser.mozilla && /Linux/.test(navigator.platform);
+        if (typeof opts.alphaOverride != 'undefined')
+            noalpha = opts.alphaOverride == 0 ? 1 : 0;
+
+        if (full && this.pageBlock) this.remove(window, {fadeOut:0});
+        // check to see if we were only passed the css object (a literal)
+        if (msg && typeof msg == 'object' && !msg.jquery && !msg.nodeType) {
+            css = msg;
+            msg = null;
+        }
+        msg = msg ? (msg.nodeType ? $(msg) : msg) : full ? $.blockUI.defaults.pageMessage : $.blockUI.defaults.elementMessage;
+        if (opts.displayMode)
+            var basecss = jQuery.extend({}, $.blockUI.defaults.displayBoxCSS);
+        else
+            var basecss = jQuery.extend({}, full ? $.blockUI.defaults.pageMessageCSS : $.blockUI.defaults.elementMessageCSS);
+        css = jQuery.extend(basecss, css || {});
+        var f = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:1000;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
+                                 : $('<div class="blockUI" style="display:none"></div>');
+        var w = $('<div class="blockUI" style="z-index:1001;cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
+        var m = full ? $('<div class="blockUI blockMsg" style="z-index:1002;cursor:wait;padding:0;position:fixed"></div>')
+                     : $('<div class="blockUI" style="display:none;z-index:1002;cursor:wait;position:absolute"></div>');
+        w.css('position', full ? 'fixed' : 'absolute');
+        if (msg) m.css(css);
+        if (!noalpha) w.css($.blockUI.defaults.overlayCSS);
+        if (this.op8) w.css({ width:''+el.clientWidth,height:''+el.clientHeight }); // lame
+        if ($.browser.msie) f.css('opacity','0.0');
+
+        $([f[0],w[0],m[0]]).appendTo(full ? 'body' : el);
+
+        // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
+        var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
+        if (this.ie6 || expr) {
+            // stretch content area if it's short
+            if (full && $.blockUI.defaults.ie6Stretch && $.boxModel)
+                $('html,body').css('height','100%');
+
+            // fix ie6 problem when blocked element has a border width
+            if ((this.ie6 || !$.boxModel) && !full) {
+                var t = this.sz(el,'borderTopWidth'), l = this.sz(el,'borderLeftWidth');
+                var fixT = t ? '(0 - '+t+')' : 0;
+                var fixL = l ? '(0 - '+l+')' : 0;
+            }
+
+            // simulate fixed position
+            $.each([f,w,m], function(i,o) {
+                var s = o[0].style;
+                s.position = 'absolute';
+                if (i < 2) {
+                    full ? s.setExpression('height','document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"')
+                         : s.setExpression('height','this.parentNode.offsetHeight + "px"');
+                    full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
+                         : s.setExpression('width','this.parentNode.offsetWidth + "px"');
+                    if (fixL) s.setExpression('left', fixL);
+                    if (fixT) s.setExpression('top', fixT);
+                }
+                else {
+                    if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
+                    s.marginTop = 0;
+                }
+            });
+        }
+        if (opts.displayMode) {
+            w.css('cursor','default').attr('title', $.blockUI.defaults.closeMessage);
+            m.css('cursor','default');
+            $([f[0],w[0],m[0]]).removeClass('blockUI').addClass('displayBox');
+            $().click($.blockUI.impl.boxHandler).bind('keypress', $.blockUI.impl.boxHandler);
+        }
+        else
+            this.bind(1, el);
+        m.append(msg).show();
+        if (msg.jquery) msg.show();
+        if (opts.displayMode) return;
+        if (full) {
+            this.pageBlock = m[0];
+            this.pageBlockEls = $(':input:enabled:visible',this.pageBlock);
+            setTimeout(this.focus, 20);
+        }
+        else this.center(m[0]);
+    },
+    remove: function(el, opts) {
+        var o = $.extend({}, $.blockUI.defaults, opts);
+        this.bind(0, el);
+        var full = el == window;
+        var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);
+        if (full) this.pageBlock = this.pageBlockEls = null;
+
+        if (o.fadeOut) {
+            els.fadeOut(o.fadeTime, function() {
+                if (this.parentNode) this.parentNode.removeChild(this);
+            });
+        }
+        else els.remove();
+    },
+    boxRemove: function(el) {
+        $().unbind('click',$.blockUI.impl.boxHandler).unbind('keypress', $.blockUI.impl.boxHandler);
+        if (this.boxCallback)
+            this.boxCallback(this.box);
+        $('body .displayBox').hide().remove();
+    },
+    // event handler to suppress keyboard/mouse events when blocking
+    handler: function(e) {
+        if (e.keyCode && e.keyCode == 9) {
+            if ($.blockUI.impl.pageBlock && !$.blockUI.defaults.allowTabToLeave) {
+                var els = $.blockUI.impl.pageBlockEls;
+                var fwd = !e.shiftKey && e.target == els[els.length-1];
+                var back = e.shiftKey && e.target == els[0];
+                if (fwd || back) {
+                    setTimeout(function(){$.blockUI.impl.focus(back)},10);
+                    return false;
+                }
+            }
+        }
+        if ($(e.target).parents('div.blockMsg').length > 0)
+            return true;
+        return $(e.target).parents().children().filter('div.blockUI').length == 0;
+    },
+    boxHandler: function(e) {
+        if ((e.keyCode && e.keyCode == 27) || (e.type == 'click' && $(e.target).parents('div.blockMsg').length == 0))
+            $.blockUI.impl.boxRemove();
+        return true;
+    },
+    // bind/unbind the handler
+    bind: function(b, el) {
+        var full = el == window;
+        // don't bother unbinding if there is nothing to unbind
+        if (!b && (full && !this.pageBlock || !full && !el.$blocked)) return;
+        if (!full) el.$blocked = b;
+        var $e = $(el).find('a,:input');
+        $.each(['mousedown','mouseup','keydown','keypress','click'], function(i,o) {
+            $e[b?'bind':'unbind'](o, $.blockUI.impl.handler);
+        });
+    },
+    focus: function(back) {
+        if (!$.blockUI.impl.pageBlockEls) return;
+        var e = $.blockUI.impl.pageBlockEls[back===true ? $.blockUI.impl.pageBlockEls.length-1 : 0];
+        if (e) e.focus();
+    },
+    center: function(el) {
+		var p = el.parentNode, s = el.style;
+        var l = ((p.offsetWidth - el.offsetWidth)/2) - this.sz(p,'borderLeftWidth');
+        var t = ((p.offsetHeight - el.offsetHeight)/2) - this.sz(p,'borderTopWidth');
+        s.left = l > 0 ? (l+'px') : '0';
+        s.top  = t > 0 ? (t+'px') : '0';
+    },
+    sz: function(el, p) { return parseInt($.css(el,p))||0; }
+};
+
+})(jQuery);

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/list.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/list.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/list.jsp
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain.jsp
new file mode 100644
index 0000000..37c096f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain.jsp
@@ -0,0 +1,118 @@
+<!--
+ ~ Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<jsp:include page="../dialog/display_messages.jsp" />
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+	String cartridgeAlias = request.getParameter("cartridge_alias");
+	String domain = request.getParameter("domain");
+
+	if (cartridgeAlias == null || cartridgeAlias.trim().length() == 0) {
+		response.setStatus(500);
+		CarbonUIMessage uiMsg = new CarbonUIMessage(
+				CarbonUIMessage.ERROR, "Cartridge Alias Not Specified");
+		session.setAttribute(CarbonUIMessage.ID, uiMsg);
+%>
+<jsp:include page="../admin/error.jsp" />
+<%
+	return;
+	}
+%>
+<fmt:bundle basename="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources">
+	<carbon:breadcrumb label="mapdomain" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources" topPage="true"
+		request="<%=request%>" />
+	<div id="middle">
+		<h2>
+			<fmt:message key="mapdomain.to" />
+			<%=cartridgeAlias%></h2>
+		<div id="workArea">
+			<form id="mapDomainForm" name="mapDomain">
+				<input name="cartridge_alias" type="hidden" value="<%=cartridgeAlias%>" />
+				<table id="tblMapDomain" width="100%" class="styledLeft">
+					<thead>
+						<tr>
+							<th><fmt:message key="mapdomain.information" /></th>
+						</tr>
+					</thead>
+					<tbody>
+						<tr>
+							<td class="nopadding">
+								<table class="normal-nopadding" cellspacing="0">
+									<tbody>
+										<tr>
+											<td style="width: 30%"><label>Cartridge Alias</label><span
+												class="required">*</span></td>
+											<td><span><%=cartridgeAlias%></span></td>
+										</tr>
+										<tr>
+											<td><label for="domain">Domain</label><span
+												class="required">*</span></td>
+											<td><input id="domain" name="domain" type="text"
+												style="width: 250px" maxlength="300"
+												value="<%=(domain != null ? domain : "")%>" /></td>
+										</tr>
+									</tbody>
+								</table>
+							</td>
+						</tr>
+						<tr id="buttonRow">
+							<td class="buttonRow"><input id="mapDomainSave"
+								type="submit" class="button" value="Save"> <input
+								id="mapDomainCancelButton" type="button" class="button"
+								value="Cancel" onclick="cancelMapDomain();"></td>
+						</tr>
+					</tbody>
+				</table>
+			</form>
+		</div>
+	</div>
+
+	<script type="text/javascript">
+		jQuery(document).ready(
+				function() {
+					setStratosFormSubmitFunction("#mapDomainForm", validate,
+							"map_domain_ajaxprocessor.jsp",
+							"subscribed_cartridges.jsp", "#mapDomainSave");
+				});
+
+		function validate() {
+			if (jQuery("#domain").val().length == 0) {
+				CARBON.showErrorDialog('Please enter a value for domain.');
+				return false;
+			}
+			return true;
+		}
+		
+		function cancelMapDomain() {
+			location.href = "subscribed_cartridges.jsp";
+		}
+	</script>
+	<script type="text/javascript" src="js/jquery.blockUI-1.33.js"></script>
+	<script type="text/javascript" src="js/common.js"></script>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain_ajaxprocessor.jsp
new file mode 100644
index 0000000..0543dcf
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/map_domain_ajaxprocessor.jsp
@@ -0,0 +1,67 @@
+<!--
+ ~ Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<jsp:include page="../dialog/display_messages.jsp" />
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle.getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+	String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+	ConfigurationContext configContext = (ConfigurationContext) config.getServletContext().getAttribute(
+			CarbonConstants.CONFIGURATION_CONTEXT);
+
+	String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+	CartridgeAdminClient client;
+
+	String cartridgeAlias = request.getParameter("cartridge_alias");
+	String mappedDomain = request.getParameter("domain");
+	try {
+		client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+		String host = client.addDomainMapping(mappedDomain, cartridgeAlias);
+		String message = "";
+		if (host != null) {
+			//CarbonUIMessage.sendCarbonUIMessage
+			message = "Your own domain is successfully added. Please CNAME it to system's domain: " + host + ".";
+		} //else {
+			//TODO: Handle this scenario
+			//CarbonUIMessage.sendCarbonUIMessage("Your own domain is added", CarbonUIMessage.WARNING, request);
+		//}
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+	} catch (Exception e) {
+    	//CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request);
+		response.setStatus(500);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/remove_domain_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/remove_domain_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/remove_domain_ajaxprocessor.jsp
new file mode 100644
index 0000000..c210447
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/remove_domain_ajaxprocessor.jsp
@@ -0,0 +1,60 @@
+<!--
+ ~ Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<jsp:include page="../dialog/display_messages.jsp" />
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle.getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+	String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+	ConfigurationContext configContext = (ConfigurationContext) config.getServletContext().getAttribute(
+			CarbonConstants.CONFIGURATION_CONTEXT);
+
+	String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+	CartridgeAdminClient client;
+
+	String cartridgeAlias = request.getParameter("cartridge_alias");
+	try {
+		client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+		client.removeDomainMapping(cartridgeAlias);
+		//CarbonUIMessage.sendCarbonUIMessage("Domain removed.", CarbonUIMessage.INFO, request);
+		String message = "Domain removed.";
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+	} catch (Exception e) {
+		//CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request);
+		response.setStatus(500);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+	}
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.dtd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.dtd b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.dtd
new file mode 100644
index 0000000..562ad3e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/XMLSchema.dtd
@@ -0,0 +1,418 @@
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<!-- DTD for XML Schemas: Part 1: Structures
+     Public Identifier: "-//W3C//DTD XMLSCHEMA 200102//EN"
+     Official Location: http://www.w3.org/2001/XMLSchema.dtd -->
+<!-- $Id: XMLSchema.dtd,v 1.31 2001/10/24 15:50:16 ht Exp $ -->
+<!-- Note this DTD is NOT normative, or even definitive. -->           <!--d-->
+<!-- prose copy in the structures REC is the definitive version -->    <!--d-->
+<!-- (which shouldn't differ from this one except for this -->         <!--d-->
+<!-- comment and entity expansions, but just in case) -->              <!--d-->
+<!-- With the exception of cases with multiple namespace
+     prefixes for the XML Schema namespace, any XML document which is
+     not valid per this DTD given redefinitions in its internal subset of the
+     'p' and 's' parameter entities below appropriate to its namespace
+     declaration of the XML Schema namespace is almost certainly not
+     a valid schema. -->
+
+<!-- The simpleType element and its constituent parts
+     are defined in XML Schema: Part 2: Datatypes -->
+<!ENTITY % xs-datatypes PUBLIC 'datatypes' 'datatypes.dtd' >
+
+<!ENTITY % p 'xs:'> <!-- can be overriden in the internal subset of a
+                         schema document to establish a different
+                         namespace prefix -->
+<!ENTITY % s ':xs'> <!-- if %p is defined (e.g. as foo:) then you must
+                         also define %s as the suffix for the appropriate
+                         namespace declaration (e.g. :foo) -->
+<!ENTITY % nds 'xmlns%s;'>
+
+<!-- Define all the element names, with optional prefix -->
+<!ENTITY % schema "%p;schema">
+<!ENTITY % complexType "%p;complexType">
+<!ENTITY % complexContent "%p;complexContent">
+<!ENTITY % simpleContent "%p;simpleContent">
+<!ENTITY % extension "%p;extension">
+<!ENTITY % element "%p;element">
+<!ENTITY % unique "%p;unique">
+<!ENTITY % key "%p;key">
+<!ENTITY % keyref "%p;keyref">
+<!ENTITY % selector "%p;selector">
+<!ENTITY % field "%p;field">
+<!ENTITY % group "%p;group">
+<!ENTITY % all "%p;all">
+<!ENTITY % choice "%p;choice">
+<!ENTITY % sequence "%p;sequence">
+<!ENTITY % any "%p;any">
+<!ENTITY % anyAttribute "%p;anyAttribute">
+<!ENTITY % attribute "%p;attribute">
+<!ENTITY % attributeGroup "%p;attributeGroup">
+<!ENTITY % include "%p;include">
+<!ENTITY % import "%p;import">
+<!ENTITY % redefine "%p;redefine">
+<!ENTITY % notation "%p;notation">
+
+<!-- annotation elements -->
+<!ENTITY % annotation "%p;annotation">
+<!ENTITY % appinfo "%p;appinfo">
+<!ENTITY % documentation "%p;documentation">
+
+<!-- Customisation entities for the ATTLIST of each element type.
+     Define one of these if your schema takes advantage of the
+     anyAttribute='##other' in the schema for schemas -->
+
+<!ENTITY % schemaAttrs ''>
+<!ENTITY % complexTypeAttrs ''>
+<!ENTITY % complexContentAttrs ''>
+<!ENTITY % simpleContentAttrs ''>
+<!ENTITY % extensionAttrs ''>
+<!ENTITY % elementAttrs ''>
+<!ENTITY % groupAttrs ''>
+<!ENTITY % allAttrs ''>
+<!ENTITY % choiceAttrs ''>
+<!ENTITY % sequenceAttrs ''>
+<!ENTITY % anyAttrs ''>
+<!ENTITY % anyAttributeAttrs ''>
+<!ENTITY % attributeAttrs ''>
+<!ENTITY % attributeGroupAttrs ''>
+<!ENTITY % uniqueAttrs ''>
+<!ENTITY % keyAttrs ''>
+<!ENTITY % keyrefAttrs ''>
+<!ENTITY % selectorAttrs ''>
+<!ENTITY % fieldAttrs ''>
+<!ENTITY % includeAttrs ''>
+<!ENTITY % importAttrs ''>
+<!ENTITY % redefineAttrs ''>
+<!ENTITY % notationAttrs ''>
+<!ENTITY % annotationAttrs ''>
+<!ENTITY % appinfoAttrs ''>
+<!ENTITY % documentationAttrs ''>
+
+<!ENTITY % complexDerivationSet "CDATA">
+      <!-- #all or space-separated list drawn from derivationChoice -->
+<!ENTITY % blockSet "CDATA">
+      <!-- #all or space-separated list drawn from
+                      derivationChoice + 'substitution' -->
+
+<!ENTITY % mgs '%all; | %choice; | %sequence;'>
+<!ENTITY % cs '%choice; | %sequence;'>
+<!ENTITY % formValues '(qualified|unqualified)'>
+
+
+<!ENTITY % attrDecls    '((%attribute;| %attributeGroup;)*,(%anyAttribute;)?)'>
+
+<!ENTITY % particleAndAttrs '((%mgs; | %group;)?, %attrDecls;)'>
+
+<!-- This is used in part2 -->
+<!ENTITY % restriction1 '((%mgs; | %group;)?)'>
+
+%xs-datatypes;
+
+<!-- the duplication below is to produce an unambiguous content model
+     which allows annotation everywhere -->
+<!ELEMENT %schema; ((%include; | %import; | %redefine; | %annotation;)*,
+                    ((%simpleType; | %complexType;
+                      | %element; | %attribute;
+                      | %attributeGroup; | %group;
+                      | %notation; ),
+                     (%annotation;)*)* )>
+<!ATTLIST %schema;
+   targetNamespace      %URIref;               #IMPLIED
+   version              CDATA                  #IMPLIED
+   %nds;                %URIref;               #FIXED 'http://www.w3.org/2001/XMLSchema'
+   xmlns                CDATA                  #IMPLIED
+   finalDefault         %complexDerivationSet; ''
+   blockDefault         %blockSet;             ''
+   id                   ID                     #IMPLIED
+   elementFormDefault   %formValues;           'unqualified'
+   attributeFormDefault %formValues;           'unqualified'
+   xml:lang             CDATA                  #IMPLIED
+   %schemaAttrs;>
+<!-- Note the xmlns declaration is NOT in the Schema for Schemas,
+     because at the Infoset level where schemas operate,
+     xmlns(:prefix) is NOT an attribute! -->
+<!-- The declaration of xmlns is a convenience for schema authors -->
+ 
+<!-- The id attribute here and below is for use in external references
+     from non-schemas using simple fragment identifiers.
+     It is NOT used for schema-to-schema reference, internal or
+     external. -->
+
+<!-- a type is a named content type specification which allows attribute
+     declarations-->
+<!-- -->
+
+<!ELEMENT %complexType; ((%annotation;)?,
+                         (%simpleContent;|%complexContent;|
+                          %particleAndAttrs;))>
+
+<!ATTLIST %complexType;
+          name      %NCName;                        #IMPLIED
+          id        ID                              #IMPLIED
+          abstract  %boolean;                       #IMPLIED
+          final     %complexDerivationSet;          #IMPLIED
+          block     %complexDerivationSet;          #IMPLIED
+          mixed (true|false) 'false'
+          %complexTypeAttrs;>
+
+<!-- particleAndAttrs is shorthand for a root type -->
+<!-- mixed is disallowed if simpleContent, overriden if complexContent
+     has one too. -->
+
+<!-- If anyAttribute appears in one or more referenced attributeGroups
+     and/or explicitly, the intersection of the permissions is used -->
+
+<!ELEMENT %complexContent; ((%annotation;)?, (%restriction;|%extension;))>
+<!ATTLIST %complexContent;
+          mixed (true|false) #IMPLIED
+          id    ID           #IMPLIED
+          %complexContentAttrs;>
+
+<!-- restriction should use the branch defined above, not the simple
+     one from part2; extension should use the full model  -->
+
+<!ELEMENT %simpleContent; ((%annotation;)?, (%restriction;|%extension;))>
+<!ATTLIST %simpleContent;
+          id    ID           #IMPLIED
+          %simpleContentAttrs;>
+
+<!-- restriction should use the simple branch from part2, not the 
+     one defined above; extension should have no particle  -->
+
+<!ELEMENT %extension; ((%annotation;)?, (%particleAndAttrs;))>
+<!ATTLIST %extension;
+          base  %QName;      #REQUIRED
+          id    ID           #IMPLIED
+          %extensionAttrs;>
+
+<!-- an element is declared by either:
+ a name and a type (either nested or referenced via the type attribute)
+ or a ref to an existing element declaration -->
+
+<!ELEMENT %element; ((%annotation;)?, (%complexType;| %simpleType;)?,
+                     (%unique; | %key; | %keyref;)*)>
+<!-- simpleType or complexType only if no type|ref attribute -->
+<!-- ref not allowed at top level -->
+<!ATTLIST %element;
+            name               %NCName;               #IMPLIED
+            id                 ID                     #IMPLIED
+            ref                %QName;                #IMPLIED
+            type               %QName;                #IMPLIED
+            minOccurs          %nonNegativeInteger;   #IMPLIED
+            maxOccurs          CDATA                  #IMPLIED
+            nillable           %boolean;              #IMPLIED
+            substitutionGroup  %QName;                #IMPLIED
+            abstract           %boolean;              #IMPLIED
+            final              %complexDerivationSet; #IMPLIED
+            block              %blockSet;             #IMPLIED
+            default            CDATA                  #IMPLIED
+            fixed              CDATA                  #IMPLIED
+            form               %formValues;           #IMPLIED
+            %elementAttrs;>
+<!-- type and ref are mutually exclusive.
+     name and ref are mutually exclusive, one is required -->
+<!-- In the absence of type AND ref, type defaults to type of
+     substitutionGroup, if any, else the ur-type, i.e. unconstrained -->
+<!-- default and fixed are mutually exclusive -->
+
+<!ELEMENT %group; ((%annotation;)?,(%mgs;)?)>
+<!ATTLIST %group; 
+          name        %NCName;               #IMPLIED
+          ref         %QName;                #IMPLIED
+          minOccurs   %nonNegativeInteger;   #IMPLIED
+          maxOccurs   CDATA                  #IMPLIED
+          id          ID                     #IMPLIED
+          %groupAttrs;>
+
+<!ELEMENT %all; ((%annotation;)?, (%element;)*)>
+<!ATTLIST %all;
+          minOccurs   (1)                    #IMPLIED
+          maxOccurs   (1)                    #IMPLIED
+          id          ID                     #IMPLIED
+          %allAttrs;>
+
+<!ELEMENT %choice; ((%annotation;)?, (%element;| %group;| %cs; | %any;)*)>
+<!ATTLIST %choice;
+          minOccurs   %nonNegativeInteger;   #IMPLIED
+          maxOccurs   CDATA                  #IMPLIED
+          id          ID                     #IMPLIED
+          %choiceAttrs;>
+
+<!ELEMENT %sequence; ((%annotation;)?, (%element;| %group;| %cs; | %any;)*)>
+<!ATTLIST %sequence;
+          minOccurs   %nonNegativeInteger;   #IMPLIED
+          maxOccurs   CDATA                  #IMPLIED
+          id          ID                     #IMPLIED
+          %sequenceAttrs;>
+
+<!-- an anonymous grouping in a model, or
+     a top-level named group definition, or a reference to same -->
+
+<!-- Note that if order is 'all', group is not allowed inside.
+     If order is 'all' THIS group must be alone (or referenced alone) at
+     the top level of a content model -->
+<!-- If order is 'all', minOccurs==maxOccurs==1 on element/any inside -->
+<!-- Should allow minOccurs=0 inside order='all' . . . -->
+
+<!ELEMENT %any; (%annotation;)?>
+<!ATTLIST %any;
+            namespace       CDATA                  '##any'
+            processContents (skip|lax|strict)      'strict'
+            minOccurs       %nonNegativeInteger;   '1'
+            maxOccurs       CDATA                  '1'
+            id              ID                     #IMPLIED
+            %anyAttrs;>
+
+<!-- namespace is interpreted as follows:
+                  ##any      - - any non-conflicting WFXML at all
+
+                  ##other    - - any non-conflicting WFXML from namespace other
+                                  than targetNamespace
+
+                  ##local    - - any unqualified non-conflicting WFXML/attribute
+                  one or     - - any non-conflicting WFXML from
+                  more URI        the listed namespaces
+                  references
+
+                  ##targetNamespace ##local may appear in the above list,
+                    with the obvious meaning -->
+
+<!ELEMENT %anyAttribute; (%annotation;)?>
+<!ATTLIST %anyAttribute;
+            namespace       CDATA              '##any'
+            processContents (skip|lax|strict)  'strict'
+            id              ID                 #IMPLIED
+            %anyAttributeAttrs;>
+<!-- namespace is interpreted as for 'any' above -->
+
+<!-- simpleType only if no type|ref attribute -->
+<!-- ref not allowed at top level, name iff at top level -->
+<!ELEMENT %attribute; ((%annotation;)?, (%simpleType;)?)>
+<!ATTLIST %attribute;
+          name      %NCName;      #IMPLIED
+          id        ID            #IMPLIED
+          ref       %QName;       #IMPLIED
+          type      %QName;       #IMPLIED
+          use       (prohibited|optional|required) #IMPLIED
+          default   CDATA         #IMPLIED
+          fixed     CDATA         #IMPLIED
+          form      %formValues;  #IMPLIED
+          %attributeAttrs;>
+<!-- type and ref are mutually exclusive.
+     name and ref are mutually exclusive, one is required -->
+<!-- default for use is optional when nested, none otherwise -->
+<!-- default and fixed are mutually exclusive -->
+<!-- type attr and simpleType content are mutually exclusive -->
+
+<!-- an attributeGroup is a named collection of attribute decls, or a
+     reference thereto -->
+<!ELEMENT %attributeGroup; ((%annotation;)?,
+                       (%attribute; | %attributeGroup;)*,
+                       (%anyAttribute;)?) >
+<!ATTLIST %attributeGroup;
+                 name       %NCName;       #IMPLIED
+                 id         ID             #IMPLIED
+                 ref        %QName;        #IMPLIED
+                 %attributeGroupAttrs;>
+
+<!-- ref iff no content, no name.  ref iff not top level -->
+
+<!-- better reference mechanisms -->
+<!ELEMENT %unique; ((%annotation;)?, %selector;, (%field;)+)>
+<!ATTLIST %unique;
+          name     %NCName;       #REQUIRED
+	  id       ID             #IMPLIED
+	  %uniqueAttrs;>
+
+<!ELEMENT %key;    ((%annotation;)?, %selector;, (%field;)+)>
+<!ATTLIST %key;
+          name     %NCName;       #REQUIRED
+	  id       ID             #IMPLIED
+	  %keyAttrs;>
+
+<!ELEMENT %keyref; ((%annotation;)?, %selector;, (%field;)+)>
+<!ATTLIST %keyref;
+          name     %NCName;       #REQUIRED
+	  refer    %QName;        #REQUIRED
+	  id       ID             #IMPLIED
+	  %keyrefAttrs;>
+
+<!ELEMENT %selector; ((%annotation;)?)>
+<!ATTLIST %selector;
+          xpath %XPathExpr; #REQUIRED
+          id    ID          #IMPLIED
+          %selectorAttrs;>
+<!ELEMENT %field; ((%annotation;)?)>
+<!ATTLIST %field;
+          xpath %XPathExpr; #REQUIRED
+          id    ID          #IMPLIED
+          %fieldAttrs;>
+
+<!-- Schema combination mechanisms -->
+<!ELEMENT %include; (%annotation;)?>
+<!ATTLIST %include;
+          schemaLocation %URIref; #REQUIRED
+          id             ID       #IMPLIED
+          %includeAttrs;>
+
+<!ELEMENT %import; (%annotation;)?>
+<!ATTLIST %import;
+          namespace      %URIref; #IMPLIED
+          schemaLocation %URIref; #IMPLIED
+          id             ID       #IMPLIED
+          %importAttrs;>
+
+<!ELEMENT %redefine; (%annotation; | %simpleType; | %complexType; |
+                      %attributeGroup; | %group;)*>
+<!ATTLIST %redefine;
+          schemaLocation %URIref; #REQUIRED
+          id             ID       #IMPLIED
+          %redefineAttrs;>
+
+<!ELEMENT %notation; (%annotation;)?>
+<!ATTLIST %notation;
+	  name        %NCName;    #REQUIRED
+	  id          ID          #IMPLIED
+	  public      CDATA       #REQUIRED
+	  system      %URIref;    #IMPLIED
+	  %notationAttrs;>
+
+<!-- Annotation is either application information or documentation -->
+<!-- By having these here they are available for datatypes as well
+     as all the structures elements -->
+
+<!ELEMENT %annotation; (%appinfo; | %documentation;)*>
+<!ATTLIST %annotation; %annotationAttrs;>
+
+<!-- User must define annotation elements in internal subset for this
+     to work -->
+<!ELEMENT %appinfo; ANY>   <!-- too restrictive -->
+<!ATTLIST %appinfo;
+          source     %URIref;      #IMPLIED
+          id         ID         #IMPLIED
+          %appinfoAttrs;>
+<!ELEMENT %documentation; ANY>   <!-- too restrictive -->
+<!ATTLIST %documentation;
+          source     %URIref;   #IMPLIED
+          id         ID         #IMPLIED
+          xml:lang   CDATA      #IMPLIED
+          %documentationAttrs;>
+
+<!NOTATION XMLSchemaStructures PUBLIC
+           'structures' 'http://www.w3.org/2001/XMLSchema.xsd' >
+<!NOTATION XML PUBLIC
+           'REC-xml-1998-0210' 'http://www.w3.org/TR/1998/REC-xml-19980210' >


[43/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
new file mode 100644
index 0000000..cdde5e6
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainRangeContext.java
@@ -0,0 +1,149 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.lb.common.conf.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+//public class TenantDomainRangeContext {
+//    
+//    private static final Log log = LogFactory.getLog(TenantDomainRangeContext.class);
+//    
+//    /**
+//     * Map is used instead of using a list, in order to minimize the lookup time.
+//     * key - host name
+//     * Value - A map with tenant id as key and TenantDomainContext object as value
+//     */
+//    private Map<String, Map<Integer, TenantDomainContext>> tenantDomainContextMap = new HashMap<String, Map<Integer, TenantDomainContext>>();
+//
+//    /**
+//     * This method will populate the {@link #tenantDomainContextMap} with <code>TenantDomainContext</code>
+//     * objects created for all the tenants covered by the given range.
+//     */
+//    public void addTenantDomain(String domain, String subDomain, String tenantRange) {
+//        
+//        String msg = "Invalid tenant range is specified for domain " + domain+" - sub domain "+subDomain;
+//
+//        String[] parsedLine = tenantRange.trim().split("-");
+//        
+//        if (parsedLine[0].equalsIgnoreCase("*")) {
+//            
+//            tenantDomainContextMap.put(0, new TenantDomainContext(0, domain, subDomain));
+//
+//        } else if (parsedLine.length == 1) {
+//            
+//            try {
+//                
+//                int tenantId = Integer.parseInt(tenantRange);
+//                
+//                tenantDomainContextMap.put(tenantId, new TenantDomainContext(tenantId, domain, subDomain));
+//                
+//            } catch (NumberFormatException e) {
+//                
+//                log.error(msg, e);
+//                throw new RuntimeException(msg, e);
+//            }
+//
+//        } 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++) {
+//                    
+//                    tenantDomainContextMap.put(tenantId, new TenantDomainContext(tenantId, domain, subDomain));
+//                    
+//                }
+//            } catch (NumberFormatException e) {
+//                log.error(msg, e);
+//                throw new RuntimeException(msg, e);
+//            }
+//            
+//        } else {
+//            log.error(msg);
+//            throw new RuntimeException(msg);
+//        }
+//
+//    }
+//
+////    private void addToTenantDomainRangeContextMap(
+////                                                  String domain, String subDomain,
+////                                                  String tenantRange) {
+////
+////        Map<String, String> map ;
+////        
+////        if(tenantDomainRangeContextMap.containsKey(domain)){
+////            map = tenantDomainRangeContextMap.get(domain);
+////        }
+////        else{
+////            map = new HashMap<String, String>();
+////        }
+////        // put this tenant range
+////        map.put(subDomain, tenantRange);
+////        
+////        // update the parent map
+////        tenantDomainRangeContextMap.put(domain, map);
+////    }
+////
+////    public Map<Integer, String> getTenantIDClusterDomainMap() {
+////        return this.tenantIDClusterDomainMap;
+////    }
+////    
+////    public Map<Integer, String> getTenantIDClusterSubDomainMap() {
+////        return this.tenantIDClusterSubDomainMap;
+////    }
+//
+//    /**
+//     * Given a tenant id, this will return its domain.
+//     * @param id tenant id
+//     * @return domain which this tenant belongs to.
+//     */
+//    public String getClusterDomainFromTenantId(int id) {
+//        
+//        if(tenantDomainContextMap.get(id) == null){
+//            // if there's no specific domain for this tenant, we will redirect it to the default cluster
+//            return tenantDomainContextMap.get(0).getDomain();
+//        }
+//        
+//        return tenantDomainContextMap.get(id).getDomain();
+//        
+//    }
+//    
+//    /**
+//     * Given a tenant id, this will return its sub domain.
+//     * @param id tenant id
+//     * @return sub domain which this tenant belongs to.
+//     */
+//    public String getClusterSubDomainFromTenantId(int id) {
+//        
+//        if(tenantDomainContextMap.get(id) == null){
+//            // if there's no specific domain for this tenant, we will redirect it to the default cluster
+//            return tenantDomainContextMap.get(0).getSubDomain();
+//        }
+//        
+//        return tenantDomainContextMap.get(id).getSubDomain();
+//    }
+//
+//    public Map<Integer, TenantDomainContext> getTenantDomainContextMap() {
+//        return tenantDomainContextMap;
+//    }
+//}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
new file mode 100644
index 0000000..570a5d7
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/group/mgt/SubDomainAwareGroupManagementAgent.java
@@ -0,0 +1,57 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.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.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
new file mode 100644
index 0000000..24562f5
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/replication/RequestTokenReplicationCommand.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
new file mode 100644
index 0000000..9499b20
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/LoadBalancerConfigurationService.java
@@ -0,0 +1,79 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.lb.common.service;
+
+import java.util.Map;
+
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+
+/**
+ * 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 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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
new file mode 100644
index 0000000..532c94d
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/service/impl/LoadBalancerConfigurationServiceImpl.java
@@ -0,0 +1,61 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.lb.common.service.impl;
+
+import java.util.Map;
+
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.Maps;
+
+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);
+		
+        Map<String, HostContext> oldMap = LoadBalancerConfiguration.getInstance().getHostContextMap();
+        LoadBalancerConfiguration.getInstance().createServicesConfig(rootNode);
+        
+//        MapDifference<String, HostContext> diff = Maps.difference(LoadBalancerConfiguration.getInstance().getHostContextMap(),
+//                                                             oldMap );
+//		
+//		return diff.entriesOnlyOnLeft();
+        return LoadBalancerConfiguration.getInstance().getHostContextMap();
+    }
+
+//	@Override
+//    public Object getHostContext(String config) {
+//	    return null;
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
new file mode 100644
index 0000000..d543b05
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/util/DomainMapping.java
@@ -0,0 +1,22 @@
+package org.wso2.carbon.lb.common.util;
+
+/**
+ *
+ */
+public class DomainMapping {
+    private String mapping;
+    private String actualHost;
+
+    public DomainMapping(String mapping) {
+        this.mapping = mapping;
+    }
+
+    public String getActualHost() {
+        return actualHost;
+    }
+
+    public void setActualHost(String actualHost) {
+        this.actualHost = actualHost;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..b50b721
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="LoadBalancerConfigurationService" scope="application">
+        <parameter name="ServiceClass">org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
new file mode 100644
index 0000000..c49cf37
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/AgentPersistenceManagerTest.java
@@ -0,0 +1,267 @@
+//package org.wso2.carbon.lb.common.test;
+//
+//import java.sql.SQLException;
+//
+//import org.testng.Assert;
+//import org.testng.annotations.Test;
+//import org.testng.annotations.BeforeMethod;
+//import org.testng.annotations.AfterMethod;
+//import org.testng.annotations.DataProvider;
+//import org.testng.annotations.BeforeClass;
+//import org.testng.annotations.AfterClass;
+//import org.testng.annotations.BeforeTest;
+//import org.testng.annotations.AfterTest;
+//import org.testng.annotations.BeforeSuite;
+//import org.testng.annotations.AfterSuite;
+//import org.wso2.carbon.lb.common.dto.Bridge;
+//import org.wso2.carbon.lb.common.dto.HostMachine;
+//import org.wso2.carbon.lb.common.dto.Zone;
+//
+//import org.apache.commons.logging.Log;
+//import org.apache.commons.logging.LogFactory;
+//import org.wso2.carbon.lb.common.persistence.AgentPersistenceManager;
+//
+///**
+// * This test class is there to test the database access methods. There is a testng.xml to run these
+// * tests as a suit. It's located at test/resources. Currently it is disabled by commenting the class
+// * element at the xml file. Mysql driver dependancy at pom.xml is also disabled and it should be
+// * uncommented to support database activities.
+// */
+//public class AgentPersistenceManagerTest {
+//	
+//	private static final Log log = LogFactory.getLog(AgentPersistenceManagerTest.class);;
+//	
+////  @Test(dataProvider = "dp")
+////  public void f(Integer n, String s) {
+////  }
+//  @BeforeMethod
+//  public void beforeMethod() {
+//  }
+//
+//  @AfterMethod
+//  public void afterMethod() {
+//  }
+//
+//
+//  @DataProvider
+//  public Object[][] dataProviderForDAO() {
+//  
+//	  String epr = "epr4";
+//	  String zoneName = "zone1";
+//      Bridge[] bridges = new Bridge[3];
+//      bridges[0] = new Bridge();
+//      bridges[1] = new Bridge();
+//      bridges[2] = new Bridge();
+//
+//      bridges[0].setBridgeIp("168.192.1.0");
+//      bridges[0].setAvailable(true);
+//      bridges[0].setCurrentCountIps(0);
+//      bridges[0].setMaximumCountIps(100);
+//      bridges[0].setNetGateway("net_gateway");
+//      bridges[0].setNetMask("net_mask");
+//      bridges[0].setHostMachine(epr);
+//
+//      bridges[1].setBridgeIp("168.192.2.0");
+//      bridges[1].setAvailable(true);
+//      bridges[1].setCurrentCountIps(0);
+//      bridges[1].setMaximumCountIps(100);
+//      bridges[1].setNetGateway("net_gateway");
+//      bridges[1].setNetMask("net_mask");
+//      bridges[1].setHostMachine(epr);
+//
+//      bridges[2].setBridgeIp("168.192.3.0");
+//      bridges[2].setAvailable(true);
+//      bridges[2].setCurrentCountIps(0);
+//      bridges[2].setMaximumCountIps(100);
+//      bridges[2].setNetGateway("net_gateway");
+//      bridges[2].setNetMask("net_mask");
+//      bridges[2].setHostMachine(epr);
+//
+//
+//      HostMachine hostMachine = new HostMachine();
+//      hostMachine.setAvailable(true);
+//      hostMachine.setContainerRoot("ContainerRoot");
+//      hostMachine.setIp("ip");
+//      hostMachine.setZone(zoneName);
+//      hostMachine.setBridges(bridges);
+//      hostMachine.setEpr(epr);
+//      
+//      String[] domains = new String[2];
+//      domains[0] = "domian1";
+//      domains[1] = "domain2";
+//      
+//      
+//    return new Object[][] {
+//      new Object[] { hostMachine, domains },
+//    };
+//  }
+//  @BeforeClass
+//  public void beforeClass() {
+//  }
+//
+//  @AfterClass
+//  public void afterClass() {
+//  }
+//
+//  @BeforeTest
+//  public void beforeTest() {
+//  }
+//
+//  @AfterTest
+//  public void afterTest() {
+//  }
+//
+//  @BeforeSuite
+//  public void beforeSuite() {
+//  }
+//
+//  @AfterSuite
+//  public void afterSuite() {
+//  }
+//
+//
+////  @Test
+////  public void addContainer() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+//  
+//  @Test(dataProvider="dataProviderForDAO")
+//  public void addZone(HostMachine hostMachine, String[] domains)  {
+//	  AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
+//	  boolean isAdded = false;
+//	  boolean zoneExists = false;
+//      try {
+//    	  zoneExists = agentPersistenceManager.isZoneExist(hostMachine.getZone());
+//		if (!zoneExists) {
+//		      String msg = "Zone does not exists ";
+//		      System.out.println(msg);
+//		      Zone zone = new Zone();
+//		      zone.setName(hostMachine.getZone());
+//		      zone.setAvailable(true);
+//		      isAdded = agentPersistenceManager.addZone(zone, domains);
+//		  } else {
+//		      String msg = "Zone exist";
+//		      System.out.println(msg);
+//		  }
+//	} catch (SQLException e) {
+//		  String msg = "Test failure while adding zone";
+//		  log.error(msg);
+//	}
+//      System.out.println("zone added " + isAdded);
+//      if(!zoneExists){
+//    	  Assert.assertEquals(isAdded, true);
+//      }else{
+//    	  Assert.assertEquals(isAdded, false );
+//      }
+//  }
+//  
+//  @Test(dataProvider="dataProviderForDAO")
+//  public void addHostMachine(HostMachine hostMachine, String[] domains)  {
+//
+//
+//
+//	  AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
+//      boolean isAdded = false;
+//	  try {
+//		  isAdded = agentPersistenceManager.addHostMachine(hostMachine, domains);
+//	  } catch (SQLException e) {
+//		  String msg = "Test failure while adding host machine";
+//		  log.error(msg);
+//	  }
+//      System.out.println(" HM added " + isAdded);
+//      Assert.assertEquals(isAdded, true);
+//
+//  }
+//
+//    @Test(dataProvider="dataProviderForDAO")
+//    public void deleteHostMachine(HostMachine hostMachine) {
+//        AgentPersistenceManager agentPersistenceManager = AgentPersistenceManager.getPersistenceManager();
+//        boolean isDeleted = false;
+//
+//        try {
+//            isDeleted = agentPersistenceManager.deleteHostMachine(hostMachine.getEpr());
+//        } catch (SQLException e) {
+//            String msg = "Test failure while deleting host machine";
+//            log.error(msg);
+//        }
+//
+//    }
+////
+////  @Test
+////  public void addInstance() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+//  
+////
+////  @Test
+////  public void changeContainerState() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void changeHostMachineAvailability() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void deleteContainer() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+//
+////
+////  @Test
+////  public void getPersistenceManager() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void isDomainExist() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void isHostMachineExist() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void isHostMachinesAvailableInDomain() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void isZoneExist() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void retrieveAgentToContainerRootMap() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void retrieveAvailableContainerInformation() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void retrieveContainerIdToAgentMap() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void retrieveDomainToInstanceIdsMap() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void retrieveInstanceIdToAdapterMap() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+////
+////  @Test
+////  public void updateDomainConfigs() {
+////    throw new RuntimeException("Test not implemented");
+////  }
+//}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
new file mode 100644
index 0000000..124d552
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/LoadBalancerConfigurationTest.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.lb.common.test;
+
+import java.io.File;
+import java.util.List;
+
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
new file mode 100644
index 0000000..a75484b
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/java/org/wso2/carbon/lb/common/test/NodeBuilderTest.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.lb.common.test;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.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);
+
+        Assert.assertEquals("loadbalancer", a.getName());
+        Assert.assertEquals("stratos-appserver-lb", a.getProperty("securityGroups"));
+        Assert.assertEquals("${ELASTIC_IP}", a.getProperty("elasticIP"));
+        Assert.assertEquals("/mnt/payload.zip", a.getProperty("payload"));
+        Assert.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);
+
+        Assert.assertEquals("appserver", a.getName());
+        Assert.assertEquals(1, a.getChildNodes().size());
+        Assert.assertEquals("domains", a.getChildNodes().get(0).getName());
+        Assert.assertEquals("appserver.cloud-test.wso2.com,as.cloud-test.wso2.com",
+                            a.getProperty("hosts"));
+        Assert.assertEquals("resources/cluster_node.zip", a.getProperty("payload"));
+        Assert.assertEquals(null, a.getProperty("payloader"));
+
+        Node b = a.getChildNodes().get(0);
+
+        Assert.assertEquals(3, b.getChildNodes().size());
+        Assert.assertEquals(null, b.getProperty("payload"));
+
+        Node c = b.getChildNodes().get(0);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.assertEquals("1-100", c.getProperty("tenant_range"));
+
+        c = b.getChildNodes().get(2);
+
+        Assert.assertEquals(0, c.getChildNodes().size());
+        Assert.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..b2fd44f
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer.conf
@@ -0,0 +1,64 @@
+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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
new file mode 100644
index 0000000..8b87a32
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer1.conf
@@ -0,0 +1,39 @@
+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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
new file mode 100644
index 0000000..718d881
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/loadbalancer2.conf
@@ -0,0 +1,30 @@
+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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
new file mode 100644
index 0000000..44b9822
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/test/resources/testng.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!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/c1efa393/components/load-balancer/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/pom.xml b/components/load-balancer/pom.xml
new file mode 100644
index 0000000..4c60b77
--- /dev/null
+++ b/components/load-balancer/pom.xml
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<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.wso2.carbon</groupId>
+        <artifactId>carbon-components</artifactId>
+        <version>4.1.0</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>loadbalancer-components</artifactId>
+    <packaging>pom</packaging>
+    <version>4.1.0</version>
+    <name>WSO2 Carbon Loadbalancer Components</name>
+    <description>Carbon Components specifically used in Loadbalancer</description>
+    <url>http://wso2.com</url>
+
+    <modules>
+        <module>org.wso2.carbon.lb.common/4.1.0</module>
+        <!--module>lb-endpoint</module-->
+        <module>autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0</module>
+        <!--module>jvm-autoscaler-agent</module-->
+        <module>autoscaler/org.wso2.carbon.mediator.autoscale/4.1.0</module>
+        <!--module>autoscaler-service/jvmagentmgtservice/4.1.0</module>
+        <module>autoscaler-service/autoscalerservice/4.1.0</module>
+        <module>jvm-autoscaler-agent/jvmagentclient/4.1.0</module>
+        <module>jvm-autoscaler-agent/jvmagent</module-->
+    </modules>
+
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.wso2.carbon</groupId>
+                <artifactId>org.wso2.carbon.utils</artifactId>
+                <version>${wso2carbon.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.wso2.carbon</groupId>
+                <artifactId>org.wso2.carbon.core</artifactId>
+                <version>${wso2carbon.version}</version>
+            </dependency>
+            <dependency>
+              <groupId>junit</groupId>
+              <artifactId>junit</artifactId>
+              <version>${junit.version}</version>
+              <scope>test</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/pom.xml b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..b48a810
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/pom.xml
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>account-mgt-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.account.mgt.ui</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Account Managment - User Interface</name>
+
+    <build>
+
+        <plugins>
+
+            <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.wso2.carbon.account.mgt.ui.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.tenant.mgt.stub.*; version="${carbon.platform.package.import.version.range}",
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.wso2.carbon.account.mgt.stub.*; version="${carbon.platform.package.import.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Carbon-Component>UIBundle</Carbon-Component>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.account.mgt.stub</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.tenant.mgt.stub</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.json.wso2</groupId>
+          <artifactId>json</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common.stub</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/AccountMgtClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/AccountMgtClient.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/AccountMgtClient.java
new file mode 100644
index 0000000..7f944df
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/AccountMgtClient.java
@@ -0,0 +1,176 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.account.mgt.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.account.mgt.stub.beans.xsd.AccountInfoBean;
+import org.wso2.carbon.account.mgt.stub.services.AccountMgtServiceStub;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class AccountMgtClient {
+    private static final Log log = LogFactory.getLog(AccountMgtClient.class);
+
+    private AccountMgtServiceStub stub;
+    private String epr;
+
+    public AccountMgtClient(String cookie, String backendServerURL,
+            ConfigurationContext configContext) throws RegistryException {
+
+        epr = backendServerURL + "AccountMgtService";
+
+        try {
+            stub = new AccountMgtServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate AccountMgt service client.";
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public AccountMgtClient(ServletConfig config, HttpSession session) throws RegistryException {
+
+        String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext =
+                (ConfigurationContext) config.getServletContext().getAttribute(
+                        CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "AccountMgtService";
+
+        try {
+            stub = new AccountMgtServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate AccountMgt service client.";
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public void updateContact(String contactEmail) throws RegistryException {
+        try {
+            stub.updateContact(contactEmail);
+        } catch (Exception e) {
+            String msg = "Failed to update contact.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public String getContact() throws RegistryException {
+        try {
+            return stub.getContact();
+        } catch (Exception e) {
+            String msg = "Failed to get contact.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+   public boolean updateFullname(AccountInfoBean fullname) throws RegistryException {
+        try {
+            return stub.updateFullname(fullname);
+        } catch (Exception e) {
+            String msg = "Failed to update Fullname.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public AccountInfoBean getFullname() throws RegistryException {
+        try {
+            return stub.getFullname();
+        } catch (Exception e) {
+            String msg = "Failed to get administrator full name.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public void deactivate() throws RegistryException {
+        try {
+            stub.deactivate();
+        } catch (Exception e) {
+            String msg = "Failed to deactivate.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public boolean isDomainValidated() throws RegistryException {
+        try {
+            return stub.isDomainValidated();
+        } catch (Exception e) {
+            String msg = "Failed to check the domain validation.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public boolean finishedDomainValidation(String validatedDomain, String successKey)
+            throws RegistryException {
+        try {
+            return stub.finishedDomainValidation(validatedDomain, successKey);
+        } catch (Exception e) {
+            String msg = "Failed to finish the domain validation.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public boolean checkDomainAvailability(String domainName) throws RegistryException {
+        try {
+            return stub.checkDomainAvailability(domainName);
+        } catch (Exception e) {
+            String msg = "Failed to finish the domain availability.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public boolean isEmailValidated() throws RegistryException {
+        try {
+            return stub.isEmailValidated();
+        } catch (Exception e) {
+            String msg = "Failed to check the email validation.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/EmailValidationClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/EmailValidationClient.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/EmailValidationClient.java
new file mode 100644
index 0000000..20aeb8d
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/EmailValidationClient.java
@@ -0,0 +1,95 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.account.mgt.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.account.mgt.stub.services.EmailValidationServiceStub;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class EmailValidationClient {
+     private static final Log log = LogFactory.getLog(EmailValidationClient.class);
+
+    private EmailValidationServiceStub stub;
+    private String epr;
+
+    public EmailValidationClient(
+            String cookie, String backendServerURL, ConfigurationContext configContext)
+            throws RegistryException {
+
+        epr = backendServerURL + "EmailValidationService";
+
+        try {
+            stub = new EmailValidationServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate EmailValidationService service client.";
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public EmailValidationClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+
+        String cookie = (String)session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "EmailValidationService";
+
+        try {
+            stub = new EmailValidationServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate EmailValidationService service client.";
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public void proceedUpdateContact(String domain, String email, String confirmationKey) throws RegistryException {
+        try {
+            stub.proceedUpdateContact(domain, email, confirmationKey);
+        } catch (Exception e) {
+            String msg = "Failed to proceed update contacts.";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/PackageInfoServiceClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/PackageInfoServiceClient.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/PackageInfoServiceClient.java
new file mode 100644
index 0000000..adc1576
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/PackageInfoServiceClient.java
@@ -0,0 +1,97 @@
+/*<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->*/
+package org.wso2.carbon.account.mgt.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.common.packages.stub.PackageInfoServiceStub;
+import org.wso2.carbon.stratos.common.packages.stub.PackageInfo;
+
+/**
+ * PackageInfoService client
+ */
+public class PackageInfoServiceClient {
+
+    private static Log log = LogFactory.getLog(PackageInfoServiceClient.class);
+
+    private PackageInfoServiceStub stub;
+    private String epr;
+
+    public PackageInfoServiceClient(
+            String cookie, String backendServerURL, ConfigurationContext configContext)
+            throws Exception {
+
+        epr = backendServerURL + "PackageInfoService";
+
+        try {
+            stub = new PackageInfoServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate PackageInfoService client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public PackageInfo[] getBillingPackages() throws Exception {
+
+        try {
+            return stub.getPackageInfos();
+        } catch (Exception e) {
+            String msg = "Failed to get package information: " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    public JSONArray getBillingPackagesJsonArray() throws Exception {
+
+        try {
+            PackageInfo[] packageInfoArray = stub.getPackageInfos();
+            JSONArray jsonPackageInfoArray = new JSONArray();
+            for (PackageInfo packageInfo : packageInfoArray) {
+                JSONObject packageInfoObj = new JSONObject();
+                packageInfoObj.put("name", packageInfo.getName());
+                int subscriptionCharge = packageInfo.getSubscriptionCharge();
+                //TODO https://wso2.org/jira/browse/STRATOS-1819
+                StringBuffer charge = new StringBuffer("$" + subscriptionCharge);
+                packageInfoObj.put("subscriptionCharge", charge.toString());
+                jsonPackageInfoArray.put(packageInfoObj);
+            }
+            return jsonPackageInfoArray;
+        } catch (Exception e) {
+            String msg = "Failed to get package information: " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/UsagePlanClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/UsagePlanClient.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/UsagePlanClient.java
new file mode 100644
index 0000000..f5970ca
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/clients/UsagePlanClient.java
@@ -0,0 +1,104 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.account.mgt.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.account.mgt.stub.services.BillingDataAccessServiceStub;
+import org.wso2.carbon.account.mgt.stub.services.beans.xsd.Subscription;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class UsagePlanClient {
+    private BillingDataAccessServiceStub stub;
+    private static final Log log = LogFactory.getLog(UsagePlanClient.class);
+
+    public UsagePlanClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+
+        String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        String epr = backendServerURL + "BillingDataAccessService";
+
+        try {
+            stub = new BillingDataAccessServiceStub(configContext, epr);
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate Add Services service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+
+    public boolean updateUsagePlan(String usagePlanName) {
+        try {
+            stub.changeSubscriptionByTenant(usagePlanName);
+        } catch (Exception e) {
+            return false;
+        }
+        return true;
+    }
+
+    public String getUsagePlanName(String tenantDomain) throws Exception{
+        Subscription subscription;
+        try {
+            subscription=stub.getActiveSubscriptionOfCustomerByTenant();
+            if(subscription!=null){
+                return subscription.getSubscriptionPlan();
+            } else {
+                return "";
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while getting the usage plan for tenant: " + tenantDomain;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    public boolean deactivateActiveUsagePlan(String tenantDomain){
+        log.info("Deactivating tenant domain: " + tenantDomain);
+        boolean deactivated = false;
+        try{
+            deactivated = stub.deactivateActiveSubscriptionByTenant();
+            if(deactivated){
+                log.info("Active subscription deactivated after deactivating the tenant: " + tenantDomain);
+            }
+        }catch (Exception e){
+            log.error("Error occurred while deactivating active subscription of: " +
+                        tenantDomain + " " + e.getMessage(), e);
+        }
+
+        return deactivated;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/utils/Util.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/utils/Util.java
new file mode 100644
index 0000000..6c263ae
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/account/mgt/ui/utils/Util.java
@@ -0,0 +1,117 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.account.mgt.ui.utils;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.account.mgt.stub.beans.xsd.AccountInfoBean;
+import org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient;
+import org.wso2.carbon.account.mgt.ui.clients.UsagePlanClient;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import java.io.StringReader;
+import java.util.Iterator;
+
+public class Util {
+    private static final Log log = LogFactory.getLog(Util.class);
+    
+    public static HttpServletRequest readIntermediateData(HttpServletRequest request,String data){
+        try{
+            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(data));
+            StAXOMBuilder builder = new StAXOMBuilder(parser);
+            OMElement documentElement =  builder.getDocumentElement();
+            Iterator it = documentElement.getChildElements();
+            while(it.hasNext()){
+                OMElement element = (OMElement)it.next();
+                if ("admin".equals(element.getLocalName())) {
+                    request.setAttribute("admin",element.getText());
+                } else if ("email".equals(element.getLocalName())) {
+                    request.setAttribute("email",element.getText());
+                } else if ("tenantDomain".equals(element.getLocalName())
+                           && request.getAttribute("tenantDomain") == null) {
+                    request.setAttribute("tenantDomain",element.getText());
+                } else if ("confirmationKey".equals(element.getLocalName())) {
+                    request.setAttribute("confirmationKey",element.getText());
+                }
+            }
+        }catch(Exception e){
+            log.error("Error parsing xml",e);
+        }
+        return request;
+    }
+
+    public static boolean updateFullname(
+            HttpServletRequest request,
+            ServletConfig config,
+            HttpSession session) throws Exception {
+
+        AccountInfoBean accountInfoBean = new AccountInfoBean();
+        String firstname = "", lastname = "";
+        try {
+            firstname = request.getParameter("firstname");
+            lastname = request.getParameter("lastname");
+            accountInfoBean.setFirstname(firstname);
+            accountInfoBean.setLastname(lastname);
+            AccountMgtClient client = new AccountMgtClient(config, session);
+            return client.updateFullname(accountInfoBean);
+        } catch (Exception e) {
+            String msg = "Failed to update tenant with firstname: " + firstname;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+    public static String getUsagePlanName(ServletConfig config,
+                                           HttpSession session) throws Exception {
+        try{
+            String tenantDomain=(String)session.getAttribute("tenantDomain");
+            UsagePlanClient client=new UsagePlanClient(config, session);
+            return client.getUsagePlanName(tenantDomain);         
+        }
+        catch (Exception e){
+            String msg = "Failed to get usage plan for tenant";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+    }
+
+    public static boolean updateUsagePlan( HttpServletRequest request, ServletConfig config,
+                                           HttpSession session) throws Exception {
+        boolean updated = false;
+        String tenantDomain="";
+        try{
+            tenantDomain=(String)session.getAttribute("tenantDomain");
+            String usagePlanName=(String)request.getParameter("selectedUsagePlan");
+            UsagePlanClient client=new UsagePlanClient(config, session);
+            updated = client.updateUsagePlan(usagePlanName);
+        }
+       catch (Exception e){
+            String msg = "Failed to update the usage plan for tenant: " + tenantDomain;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return updated;
+    }
+    
+}


[40/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandContext.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandContext.java
new file mode 100644
index 0000000..59364ff
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandContext.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Observable;
+
+public class CommandContext extends Observable {
+
+	/**
+	 * Properties for the context.
+	 */
+	private Map<String, Object> properties;
+
+	/**
+	 * The application
+	 */
+	private final CommandLineApplication<? extends CommandContext> application;
+
+	public CommandContext(CommandLineApplication<? extends CommandContext> application) {
+		properties = new HashMap<String, Object>();
+		this.application = application;
+	}
+
+	public final CommandLineApplication<? extends CommandContext> getApplication() {
+		return application;
+	}
+
+	/**
+	 * Set property in the context
+	 * 
+	 * @param key
+	 *            The key
+	 * @param o
+	 *            The value for the key
+	 * @return The previous value or null
+	 */
+	public Object put(String key, Object o) {
+		Object previous = properties.put(key, o);
+		setChanged();
+		notifyObservers();
+		return previous;
+	}
+
+	/**
+	 * Get property value from the context
+	 * 
+	 * @param key
+	 *            The key
+	 * @return The value
+	 */
+	public Object getObject(String key) {
+		return properties.get(key);
+	}
+
+	/**
+	 * Get the string value, or null
+	 * 
+	 * @param key
+	 *            The key
+	 * @return The string value, or null.
+	 */
+	public String getString(String key) {
+		Object o = getObject(key);
+		if (o instanceof String) {
+			return (String) o;
+		}
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineApplication.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineApplication.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineApplication.java
new file mode 100644
index 0000000..bafc14d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineApplication.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import java.io.File;
+import java.io.IOException;
+
+import jline.console.ConsoleReader;
+import jline.console.history.FileHistory;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public abstract class CommandLineApplication<T extends CommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(CommandLineApplication.class);
+
+	protected final ConsoleReader reader;
+	protected FileHistory history;
+
+	public CommandLineApplication() {
+		reader = createConsoleReader();
+	}
+
+	/**
+	 * Creates new jline ConsoleReader.
+	 * 
+	 * @return a jline ConsoleReader instance
+	 */
+	protected ConsoleReader createConsoleReader() {
+		ConsoleReader consoleReader = null;
+		try {
+			consoleReader = new ConsoleReader();
+			consoleReader.setPrompt(getPrompt());
+			history = new FileHistory(getHistoryFile());
+			consoleReader.setHistory(history);
+		} catch (IOException e) {
+			throw new IllegalStateException("Cannot create jline console reader", e);
+		}
+		return consoleReader;
+	}
+
+	public ConsoleReader getConsoleReader() {
+		return reader;
+	}
+
+	protected abstract String getPrompt();
+
+	/**
+	 * Get the history file for the Console Reader.
+	 * 
+	 * @return File for storing history
+	 */
+	protected abstract File getHistoryFile();
+
+	public final void start(String[] args) {
+		Thread shutdownHookThread = new Thread("CLI Shutdown Hook") {
+			@Override
+			public void run() {
+				performDestroy();
+			}
+		};
+		Runtime.getRuntime().addShutdownHook(shutdownHookThread);
+		int returnCode = run(args);
+		if (logger.isDebugEnabled()) {
+			logger.debug("Exiting with error code {}", returnCode);
+		}
+		System.exit(returnCode);
+	}
+
+	protected abstract int run(String[] args);
+
+	protected void promptLoop() {
+		String line = null;
+		boolean exit = false;
+
+		try {
+			while (!exit && (reader != null && ((line = reader.readLine()) != null))) {
+				if ("".equals(line)) {
+					continue;
+				}
+				if (StringUtils.isNotBlank(line)) {
+					execute(line);
+					exit = CliConstants.EXIT_ACTION.equals(line.trim());
+				}
+			}
+		} catch (IOException e) {
+			throw new IllegalStateException("Error in reading line", e);
+		}
+	}
+
+	private int execute(String line) {
+		try {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Executing command line: \"{}\"", line);
+			}
+			int returnCode = executeCommand(line);
+			if (logger.isDebugEnabled()) {
+				logger.debug("Command line executed \"{}\". Return code: {}", line, returnCode);
+			}
+			return returnCode;
+		} catch (RuntimeException e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error executing command line: " + line, e);
+			}
+			return 1;
+		}
+	}
+
+	protected abstract int executeCommand(String line);
+
+	private void performDestroy() {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Shutting down application... Invoking destroy methods");
+		}
+		if (history != null) {
+			try {
+				history.flush();
+			} catch (IOException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error flushing history.", e);
+				}
+			}
+		}
+		destroy();
+	}
+
+	/**
+	 * May override to perform action before destroying
+	 */
+	protected void destroy() {
+	};
+
+	public String getInput(String prompt) {
+		return getInput(prompt, null);
+	}
+
+	public String getInput(String prompt, Character mask) {
+		String line = null;
+		try {
+			reader.setPrompt(prompt + ": ");
+			while ((line = reader.readLine(mask)) != null) {
+				if ("".equals(line)) {
+					continue;
+				}
+				return line;
+			}
+		} catch (IOException e) {
+			throw new IllegalStateException("Error in reading line", e);
+		} finally {
+			reader.setPrompt(CliConstants.STRATOS_SHELL_PROMPT);
+		}
+		return line;
+	}
+	
+	/**
+	 * @return {@code true if user confirmed}
+	 */
+	public boolean getConfirmation(String prompt) {
+		prompt = prompt + " [yes/no]";
+
+		String input = "";
+		int tries = 0;
+		do {
+			tries++;
+			input = getInput(prompt);
+		} while (!"y".equals(input) && !"yes".equals(input) && !"n".equals(input) && !"no".equals(input) && tries < 3);
+
+		return "y".equals(input) || "yes".equals(input);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineService.java
new file mode 100644
index 0000000..a640600
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CommandLineService.java
@@ -0,0 +1,553 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import java.rmi.RemoteException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.description.TransportOutDescription;
+import org.apache.axis2.transport.http.HttpTransportProperties;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CommandLineUtils;
+import org.wso2.carbon.adc.mgt.cli.utils.RowMapper;
+import org.wso2.carbon.adc.mgt.dto.xsd.Cartridge;
+import org.wso2.carbon.adc.mgt.dto.xsd.PolicyDefinition;
+import org.wso2.carbon.adc.mgt.dto.xsd.SubscriptionInfo;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceADCExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceAlreadySubscribedExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceDomainMappingExistsExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceDuplicateCartridgeAliasExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceInvalidCartridgeAliasExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceInvalidRepositoryExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceNotSubscribedExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServicePolicyExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryRequiredExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryTransportExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceStub;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceUnregisteredCartridgeExceptionException;
+
+import com.google.gson.Gson;
+
+public class CommandLineService {
+
+	private static final Logger logger = LoggerFactory.getLogger(CommandLineService.class);
+
+	private ApplicationManagementServiceStub stub;
+
+	private CommandLineService() {
+	}
+
+	private static class SingletonHolder {
+		private final static CommandLineService INSTANCE = new CommandLineService();
+	}
+
+	public static CommandLineService getInstance() {
+		return SingletonHolder.INSTANCE;
+	}
+	
+	private void initializeApplicationManagementStub(String serverURL, String username, String password) throws AxisFault {
+		HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator();
+        authenticator.setUsername(username);
+        authenticator.setPassword(password);
+        authenticator.setPreemptiveAuthentication(true);
+		
+        ApplicationManagementServiceStub stub;
+        ConfigurationContext configurationContext = null;
+        try {
+            configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
+        } catch (Exception e) {
+            String msg = "Backend error occurred. Please contact the service admins!";
+            throw new AxisFault(msg, e);
+        }
+        HashMap<String, TransportOutDescription> transportsOut = configurationContext
+                .getAxisConfiguration().getTransportsOut();
+        for (TransportOutDescription transportOutDescription : transportsOut.values()) {
+            transportOutDescription.getSender().init(configurationContext, transportOutDescription);
+        }
+        stub = new ApplicationManagementServiceStub(configurationContext, serverURL + "/services/ApplicationManagementService");
+        ServiceClient client = stub._getServiceClient();
+        Options option = client.getOptions();
+        option.setManageSession(true);
+        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
+        option.setTimeOutInMilliSeconds(300000);
+        this.stub = stub;
+    }
+
+	public boolean login(String serverURL, String username, String password, boolean validateLogin) throws CommandException {
+		try {
+			// Following code will avoid validating certificate
+			SSLContext sc;
+			// Get SSL context
+			sc = SSLContext.getInstance("SSL");
+			// Create empty HostnameVerifier
+			HostnameVerifier hv = new HostnameVerifier() {
+				public boolean verify(String urlHostName, SSLSession session) {
+					return true;
+				}
+			};
+			// Create a trust manager that does not validate certificate
+			// chains
+			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+					return null;
+				}
+
+				public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
+				}
+
+				public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
+				}
+			} };
+			sc.init(null, trustAllCerts, new java.security.SecureRandom());
+			SSLContext.setDefault(sc);
+			HttpsURLConnection.setDefaultHostnameVerifier(hv);
+		} catch (Exception e) {
+			throw new RuntimeException("Error while authentication process!", e);
+		}
+
+		// Initialize Service Stub
+		try {
+			initializeApplicationManagementStub(serverURL, username, password);
+		} catch (AxisFault e) {
+			System.out.println("Error connecting to the back-end");
+			throw new CommandException(e);
+		}
+		
+		try {
+			if (validateLogin) {
+				String tenantDomain = stub.getTenantDomain();
+				if (logger.isDebugEnabled()) {
+					logger.debug("Tenant Domain {}", tenantDomain);
+				}
+				return (tenantDomain != null);
+			} else {
+				// Just return true as we don't need to validate
+				return true;
+			}
+		} catch (RemoteException e) {
+			System.out.println("Authentication failed!");
+			throw new CommandException(e);
+		}
+	}
+
+	public void listSubscribedCartridges(final boolean full) throws CommandException {
+		try {
+			Cartridge[] cartridges = stub.getSubscribedCartridges();
+
+			if (cartridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No subscribed cartridges found");
+				}
+				System.out.println("There are no subscribed cartridges");
+				return;
+			}
+
+			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
+
+				@Override
+				public String[] getData(Cartridge cartridge) {
+					String[] data = full ? new String[9] : new String[7];
+					data[0] = cartridge.getCartridgeType();
+					data[1] = cartridge.getDisplayName();
+					data[2] = cartridge.getVersion();
+					data[3] = cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant";
+					data[4] = cartridge.getCartridgeAlias();
+					data[5] = cartridge.getStatus();
+					data[6] = cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances());
+					if (full) {
+						data[7] = getAccessURLs(cartridge);
+						data[8] = cartridge.getRepoURL() != null ? cartridge.getRepoURL() : "";
+					}
+					return data;
+				}
+			};
+			
+			List<String> headers = new ArrayList<String>();
+			headers.add("Type");
+			headers.add("Name");
+			headers.add("Version");
+			headers.add("Tenancy Model");
+			headers.add("Alias");
+			headers.add("Status");
+			headers.add("Running Instances");
+			if (full) {
+				headers.add("Access URL(s)");
+				headers.add("Repo URL");
+			}
+
+			System.out.println("Subscribed Cartridges:");
+			CommandLineUtils.printTable(cartridges, cartridgeMapper, headers.toArray(new String[headers.size()]));
+
+			System.out.println();
+
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.subscribed.cartridges", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+
+	public void listAvailableCartridges() throws CommandException {
+		try {
+			Cartridge[] multiTenantCatridges = stub.getAvailableCartridges(true);
+
+			if (multiTenantCatridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No multi-tenant cartridges available");
+				}
+				System.out.println("There are no multi-tenant cartridges available");
+			}
+
+			RowMapper<Cartridge> cartridgeMapper = new RowMapper<Cartridge>() {
+
+				@Override
+				public String[] getData(Cartridge cartridge) {
+					String[] data = new String[3];
+					data[0] = cartridge.getCartridgeType();
+					data[1] = cartridge.getDisplayName();
+					data[2] = cartridge.getVersion();
+					return data;
+				}
+			};
+
+			System.out.println("Available Multi-Tenant Cartridges:");
+			CommandLineUtils.printTable(multiTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
+			System.out.println();
+			
+			Cartridge[] singleTenantCatridges = stub.getAvailableCartridges(false);
+
+			if (multiTenantCatridges == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No single-tenant cartridges available");
+				}
+				System.out.println("There are no single-tenant cartridges available");
+			}
+			
+			System.out.println("Available Single-Tenant Cartridges:");
+			CommandLineUtils.printTable(singleTenantCatridges, cartridgeMapper, "Type", "Name", "Version");
+			System.out.println();
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.available.cartridges", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+	
+	public void listAvailablePolicies() throws CommandException {
+		try {
+			PolicyDefinition[] policies = stub.getPolicyDefinitions();
+
+			if (policies == null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("No policies available");
+				}
+				System.out.println("There are no policies available");
+			}
+
+			RowMapper<PolicyDefinition> policyMapper = new RowMapper<PolicyDefinition>() {
+
+				@Override
+				public String[] getData(PolicyDefinition policyDefinition) {
+					String[] data = new String[3];
+					data[0] = policyDefinition.getName();
+					data[1] = policyDefinition.getDescription();
+					data[2] = policyDefinition.getDefaultPolicy() ? "Yes" : "No";
+					return data;
+				}
+			};
+
+			CommandLineUtils.printTable(policies, policyMapper, "Policy Name", "Description", "Default");
+			System.out.println();
+		} catch (RemoteException e) {
+			handleException(e);
+		}
+	}
+
+	public void info(String alias) throws CommandException {
+		try {
+            Cartridge cartridge = null;
+            try {
+                cartridge = stub.getCartridgeInfo(alias);
+            } catch (ApplicationManagementServiceADCExceptionException e) {
+            	handleException(e);
+                return;
+            } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+            	handleException("notsubscribed.error", e, alias);
+			}
+			if (logger.isDebugEnabled()) {
+				logger.debug("Cartridge Info: {}", new Gson().toJson(cartridge));
+			}
+			final String FORMAT = "%-20s: %s%n";
+			System.out.println();
+			System.out.println("Cartridge Information");
+			System.out.println("---------------------");
+			System.out.format(FORMAT, "Cartridge", cartridge.getCartridgeType());
+			System.out.format(FORMAT, "Name", cartridge.getDisplayName());
+			System.out.format(FORMAT, "Description", cartridge.getDescription());
+			System.out.format(FORMAT, "Version", cartridge.getVersion());
+			System.out.format(FORMAT, "Tenancy Model", cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant");
+			System.out.format(FORMAT, "Alias", cartridge.getCartridgeAlias());
+			if (StringUtils.isNotBlank(cartridge.getPolicyDescription())) {
+				System.out.format(FORMAT, "Policy", cartridge.getPolicyDescription());
+			}
+			System.out.format(FORMAT, "Access URL(s)", getAccessURLs(cartridge));
+			if (StringUtils.isNotBlank(cartridge.getIp())) {
+				System.out.format(FORMAT, "Host", cartridge.getIp());
+			}
+			if (StringUtils.isNotBlank(cartridge.getDbUserName())) {
+				System.out.format(FORMAT, "Database Username", cartridge.getDbUserName());
+			}
+			if (StringUtils.isNotBlank(cartridge.getPassword())) {
+				System.out.format(FORMAT, "Password", cartridge.getPassword());
+			}
+			if (StringUtils.isNotBlank(cartridge.getRepoURL())) {
+				System.out.format(FORMAT, "Repository URL", cartridge.getRepoURL());
+			}
+			System.out.format(FORMAT, "Status", cartridge.getStatus());
+			System.out.format(FORMAT, "Running Instances",
+					cartridge.getMultiTenant() ? "N/A" : String.valueOf(cartridge.getActiveInstances()));
+			System.out.println();
+
+        } catch (RemoteException e) {
+        	handleException(e);
+        }
+	}
+
+	public void unsubscribe(String alias) throws CommandException {
+		try {
+			stub.unsubscribe(alias);
+			System.out.println("You have successfully unsubscribed " + alias);
+        } catch (ApplicationManagementServiceADCExceptionException e) {
+        	handleException("cannot.unsubscribe", e);
+        } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+        } catch (RemoteException e) {
+        	handleException(e);
+        }
+	}
+
+	public void sync(String alias) throws CommandException {
+		try {
+			System.out.format("Synchronizing repository for alias: %s%n", alias);
+			stub.synchronizeRepository(alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.syncrepo", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	public String addDomainMapping(String domain, String alias) throws CommandException {
+		try {
+			return stub.addDomainMapping(domain, alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.mapdomain", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		} catch (ApplicationManagementServiceDomainMappingExistsExceptionException e) {
+			handleException("domainmapping.exists.error", e, domain, alias);
+		}
+		return null;
+	}
+
+	public void removeDomainMapping(String alias) throws CommandException {
+		try {
+			stub.removeDomainMapping(alias);
+			System.out.format("Domain mapping removed for alias: %s.%n", alias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.removedomain", e);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	public void subscribe(String cartridgeType, String alias, String policy, String externalRepoURL,
+			boolean privateRepo, String username, String password, String dataCartridgeType, String dataCartridgeAlias)
+			throws CommandException {
+		
+		SubscriptionInfo subcriptionConnectInfo = null;
+		if (StringUtils.isNotBlank(dataCartridgeType) && StringUtils.isNotBlank(dataCartridgeAlias)) {
+			System.out.format("Subscribing to data cartridge %s with alias %s.%n", dataCartridgeType,
+					dataCartridgeAlias);
+			try {
+				subcriptionConnectInfo = stub.subscribe(dataCartridgeType, dataCartridgeAlias, null, null, false, null,
+						null, null, null);
+				System.out.format("You have successfully subscribed to %s cartridge with alias %s.%n",
+						dataCartridgeType, dataCartridgeAlias);
+				System.out.format("%nSubscribing to %s cartridge and connecting with %s data cartridge.%n", alias,
+						dataCartridgeAlias);
+			} catch (RemoteException e) {
+				handleException(e);
+			} catch (ApplicationManagementServiceADCExceptionException e) {
+				handleException("cannot.subscribe", e);
+			} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+				handleException("repository.required", e);
+			} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+				handleException("cartridge.notregistered", e, dataCartridgeType);
+			} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+				handleException("cartridge.invalid.alias", e);
+			} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+				handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+						.getCartridgeType());
+			} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+				handleException("cartridge.alias.duplicate", e, dataCartridgeAlias);
+			} catch (ApplicationManagementServicePolicyExceptionException e) {
+				handleException("policy.error", e);
+			} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+				handleException("repository.transport.error", e, externalRepoURL);
+			} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+				handleException("repository.credentials.required", e, externalRepoURL);
+			} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+				handleException("repository.invalid.error", e, externalRepoURL);
+			}
+		}
+		
+		
+		try {
+			SubscriptionInfo subcriptionInfo = stub.subscribe(cartridgeType, alias, policy, externalRepoURL,
+					privateRepo, username, password, dataCartridgeType, dataCartridgeAlias);
+
+			System.out
+					.format("You have successfully subscribed to %s cartridge with alias %s.%n", cartridgeType, alias);
+
+			String repoURL = null;
+			String hostnames = null;
+			String hostnamesLabel = null;
+			if (subcriptionInfo != null) {
+				repoURL = subcriptionInfo.getRepositoryURL();
+				hostnames = subcriptionInfo.getHostname();
+				hostnamesLabel = "host name";
+
+				if (repoURL != null) {
+					System.out.println("GIT Repository URL: " + repoURL);
+				}
+
+				Cartridge cart = stub.getCartridgeInfo(alias);
+				System.out.format("Your application is being published here. %s%n", getAccessURLs(cart));
+			}
+			if (subcriptionConnectInfo != null) {
+				hostnames += ", " + subcriptionConnectInfo.getHostname();
+				hostnamesLabel = "host names";
+
+				Cartridge cart = stub.getCartridgeInfo(alias);
+				System.out.format("Your data application is being published here. %s%n", getAccessURLs(cart));
+			}
+			if (externalRepoURL != null) {
+				String takeTimeMsg = "(this might take few minutes... depending on repo size)\n";
+				System.out.println(takeTimeMsg);
+			}
+
+			System.out.format("Please map the %s \"%s\" to ELB IP%n", hostnamesLabel, hostnames);
+		} catch (RemoteException e) {
+			handleException(e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.subscribe", e);
+		} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+			handleException("repository.required", e);
+		} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+			handleException("cartridge.notregistered", e, cartridgeType);
+		} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+			handleException("cartridge.invalid.alias", e);
+		} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+			handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+					.getCartridgeType());
+		} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+			handleException("cartridge.alias.duplicate", e, alias);
+		} catch (ApplicationManagementServicePolicyExceptionException e) {
+			handleException("policy.error", e);
+		} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+			handleException("repository.transport.error", e, externalRepoURL);
+		} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+			handleException("repository.credentials.required", e, externalRepoURL);
+		} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+			handleException("repository.invalid.error", e, externalRepoURL);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, alias);
+		}
+	}
+
+	private String getAccessURLs(Cartridge cartridge) {
+		String[] accessURLs = cartridge.getAccessURLs();
+		StringBuilder urlBuilder = new StringBuilder();
+		if (accessURLs != null) {
+			for (int i = 0; i < accessURLs.length; i++) {
+				String url = accessURLs[i];
+				if (url != null) {
+					if (i > 0) {
+						urlBuilder.append(", ");
+					}
+					urlBuilder.append(url);
+				}
+			}
+		}
+		return urlBuilder.toString();
+	}
+
+	private void handleException(Exception e) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Displaying message from Exception {}\n{}", e.getClass(), e.getMessage());
+		}
+		// TODO: Fix handling error message.
+		// Sometimes the Axis2 stub throws only the RemoteException (an
+		// AxisFault)
+		// So, other exceptions won't come here.
+		String message = e.getMessage();
+		if (message == null || (message != null && message.contains("Exception"))) {
+			message = "Error executing command!";
+		}
+		if (logger.isErrorEnabled()) {
+			logger.error(message);
+		}
+		System.out.println(message);
+		throw new CommandException(message, e);
+	}
+    
+    private void handleException(String key, Exception e, Object... args) throws CommandException {
+    	if (logger.isDebugEnabled()) {
+    		logger.debug("Displaying message for {}. Exception thrown is {}", key, e.getClass());
+    	}
+    	String message = CommandLineUtils.getMessage(key, args);
+        if (logger.isErrorEnabled()) {
+        	logger.error(message);
+        }
+        System.out.println(message);
+        throw new CommandException(message, e);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosApplication.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosApplication.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosApplication.java
new file mode 100644
index 0000000..4e6522b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosApplication.java
@@ -0,0 +1,501 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import static org.wso2.carbon.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
+import static org.wso2.carbon.adc.mgt.cli.utils.CliConstants.STRATOS_HISTORY_DIR;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.text.StrTokenizer;
+import org.apache.commons.validator.routines.UrlValidator;
+import org.apache.log4j.Level;
+import org.apache.log4j.LogManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.commands.AddDomainMappingCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.CartridgesCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.ExitCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.HelpCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.InfoCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.ListCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.PoliciesCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.RemoveDomainMappingCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.SubscribeCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.SyncCommand;
+import org.wso2.carbon.adc.mgt.cli.commands.UnsubscribeCommand;
+import org.wso2.carbon.adc.mgt.cli.completer.CommandCompleter;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class StratosApplication extends CommandLineApplication<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
+
+	private final Map<String, Command<StratosCommandContext>> commands;
+	private final StratosCommandContext context;
+
+	private final Options options;
+
+	public StratosApplication() {
+		commands = new HashMap<String, Command<StratosCommandContext>>();
+		context = new StratosCommandContext(this);
+
+		options = constructOptions();
+
+		createCommands();
+		createAutocomplete();
+	}
+
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
+				"Username");
+		usernameOption.setArgName("username");
+		options.addOption(usernameOption);
+
+		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
+				"Password");
+		passwordOption.setArgName("password");
+		passwordOption.setOptionalArg(true);
+		options.addOption(passwordOption);
+		options.addOption(CliConstants.HELP_OPTION, CliConstants.HELP_LONG_OPTION, false, "Display this help");
+		options.addOption(CliConstants.TRACE_OPTION, false, "Enable trace logging");
+		options.addOption(CliConstants.DEBUG_OPTION, false, "Enable debug logging");
+		return options;
+	}
+
+	private void createCommands() {
+		Command<StratosCommandContext> command = new HelpCommand();
+		commands.put(command.getName(), command);
+
+		command = new ExitCommand();
+		commands.put(command.getName(), command);
+
+		command = new SubscribeCommand();
+		commands.put(command.getName(), command);
+
+		command = new UnsubscribeCommand();
+		commands.put(command.getName(), command);
+		
+		command = new CartridgesCommand();
+		commands.put(command.getName(), command);
+		
+		command = new ListCommand();
+		commands.put(command.getName(), command);
+		
+		command = new InfoCommand();
+		commands.put(command.getName(), command);
+		
+		command = new AddDomainMappingCommand();
+		commands.put(command.getName(), command);
+		
+		command = new RemoveDomainMappingCommand();
+		commands.put(command.getName(), command);
+		
+		command = new SyncCommand();
+		commands.put(command.getName(), command);
+		
+		command = new PoliciesCommand();
+		commands.put(command.getName(), command);
+
+		if (logger.isDebugEnabled()) {
+			logger.debug("Created {} commands for the application. {}", commands.size(), commands.keySet());
+		}
+	}
+
+	private void createAutocomplete() {
+		reader.addCompleter(new CommandCompleter(commands));
+	}
+
+	@Override
+	protected String getPrompt() {
+		return CliConstants.STRATOS_SHELL_PROMPT;
+	}
+
+	@Override
+	protected File getHistoryFile() {
+		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
+		File historyFile = new File(stratosFile, STRATOS_HISTORY_DIR);
+		return historyFile;
+	}
+
+	@Override
+	public int run(String[] args) {
+		boolean loaded = loadRequiredProperties();
+		if (!loaded) {
+			return CliConstants.ERROR_CODE;
+		}
+
+		// To get the command action from arguments
+		String[] remainingArgs = null;
+
+		// Command action
+		String action = null;
+
+		String usernameInput = null;
+		String passwordInput = null;
+
+		if (args != null && args.length > 0) {
+			// Arguments are passed.
+			if (logger.isDebugEnabled()) {
+				logger.debug("Arguments:");
+				for (String arg : args) {
+					logger.debug(arg);
+				}
+			}
+
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				// Must add all options. Otherwise actions cannot be performed directly by command line.
+				Options allCommandOptions = new Options();
+				for (Command<StratosCommandContext> command : commands.values()) {
+					Options commandOptions = command.getOptions();
+					if (commandOptions != null) {
+						Collection<?> allOptions = commandOptions.getOptions();
+						for (Object o : allOptions) {
+							allCommandOptions.addOption((Option) o);
+						}
+					}
+				}
+				// Add options in this application
+				Collection<?> allOptions = options.getOptions();
+				for (Object o : allOptions) {
+					allCommandOptions.addOption((Option) o);
+				}
+				
+				commandLine = parser.parse(allCommandOptions, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length > 0) {
+					// Get command action
+					action = remainingArgs[0];
+				}
+
+				// Set logger levels from this point onwards
+				setLoggerLevel(commandLine.hasOption(CliConstants.TRACE_OPTION),
+						commandLine.hasOption(CliConstants.DEBUG_OPTION));
+
+				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Username option is passed");
+					}
+					usernameInput = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Password option is passed");
+					}
+					passwordInput = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.HELP_ACTION)) {
+					printHelp();
+					return CliConstants.SUCCESSFUL_CODE;
+				}
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments when trying to login", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE; 
+			}
+
+		}
+
+		if (StringUtils.isNotBlank(action)) {
+			// User is executing an action
+			if (logger.isDebugEnabled()) {
+				logger.debug("Action: {}", action);
+			}
+			Command<StratosCommandContext> command = commands.get(action);
+			if (command == null) {
+				printHelp();
+				return CliConstants.BAD_ARGS_CODE;
+			}
+
+			boolean loginRequired = !CliConstants.HELP_ACTION.equals(action);
+			
+			if (loginRequired && logger.isDebugEnabled()) {
+				logger.debug("Trying to login...");
+			}
+
+			if (loginRequired && !login(usernameInput, passwordInput, false)) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Exiting from CLI. Login required but login might have failed: {}", action);
+				}
+				// Exit
+				return CliConstants.ERROR_CODE;
+			}
+
+			try {
+				String[] actionArgs = Arrays.copyOfRange(remainingArgs, 1, remainingArgs.length);
+				if (logger.isDebugEnabled()) {
+					logger.debug("Executing Action: {} {}", action, Arrays.asList(actionArgs));
+				}
+				int returnCode = command.execute(context, actionArgs);
+				if (logger.isDebugEnabled()) {
+					logger.debug("Exiting with error code {} after executing action {}", returnCode, action);
+				}
+				System.exit(returnCode);
+			} catch (CommandException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error executing command: " + action, e);
+				}
+				return CliConstants.ERROR_CODE;
+			}
+		} else {
+			if (login(usernameInput, passwordInput, true)) {
+				System.out.println("Successfully Authenticated.");
+			} else {
+				// Exit
+				return CliConstants.ERROR_CODE;
+			}
+
+			promptLoop();
+		}
+		return CliConstants.SUCCESSFUL_CODE;
+	}
+
+	private boolean login(String usernameInput, String passwordInput, boolean validateLogin) {
+		// TODO Previous CLI version uses a keystore. Here we are not using it.
+		// Check whether user has passed username and password
+		if (StringUtils.isBlank(usernameInput) && StringUtils.isBlank(passwordInput)) {
+			// User has not passed any arguments.
+			// Try authenticating from the values found
+			usernameInput = context.getString(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
+			passwordInput = context.getString(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
+
+			if (logger.isDebugEnabled()) {
+				if (StringUtils.isNotBlank(usernameInput) && StringUtils.isNotBlank(passwordInput)) {
+					logger.debug("Found authentication details for {} from context", usernameInput);
+				}
+			}
+
+		}
+		// Get user input if not passed as args
+		if (StringUtils.isBlank(usernameInput)) {
+			usernameInput = getInput("Username");
+		} else {
+			System.out.format("Username: %s%n", usernameInput);
+		}
+		if (StringUtils.isBlank(passwordInput)) {
+			passwordInput = getInput("Password", '*');
+		}
+
+		boolean success = false;
+		String stratosURL = null;
+		stratosURL = context.getString(CliConstants.STRATOS_URL_ENV_PROPERTY);
+
+		try {
+			success = CommandLineService.getInstance().login(stratosURL, usernameInput, passwordInput, validateLogin);
+		} catch (Exception e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error when trying to login", e);
+			}
+		}
+		if (success) {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Successfully Authenticated.");
+			}
+		} else {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Authentication failed.");
+			}
+		}
+		return success;
+	}
+
+	@Override
+	protected int executeCommand(String line) {
+		String[] tokens = new StrTokenizer(line).getTokenArray();
+		String action = tokens[0];
+		String[] actionArgs = Arrays.copyOfRange(tokens, 1, tokens.length);
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing command action: {}, Tokens: {}", action, tokens.length);
+		}
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			System.out.println(action + ": command not found.");
+			return CliConstants.BAD_ARGS_CODE;
+		}
+		try {
+			return command.execute(context, actionArgs);
+		} catch (CommandException e) {
+			if (logger.isErrorEnabled()) {
+				logger.error("Error executing command: " + action, e);
+			}
+			return CliConstants.ERROR_CODE;
+		}
+	}
+
+	/**
+	 * @return {@code true} if required properties are loaded
+	 */
+	private boolean loadRequiredProperties() {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Loading properties...");
+		}
+		// Load properties
+		String stratosURL = null;
+		String username = null;
+		String password = null;
+
+		stratosURL = System.getenv(CliConstants.STRATOS_URL_ENV_PROPERTY);
+		username = System.getenv(CliConstants.STRATOS_USERNAME_ENV_PROPERTY);
+		password = System.getenv(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY);
+
+		if (StringUtils.isBlank(stratosURL)) {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Required configuration not found.");
+			}
+			// Stratos Controller details are not set.
+			System.out.format("Could not find required \"%s\" variable in your environment.%n",
+					CliConstants.STRATOS_URL_ENV_PROPERTY);
+			return false;
+		} else {
+			if (logger.isDebugEnabled()) {
+				logger.debug("Required configuration found. Validating {}", stratosURL);
+			}
+			UrlValidator urlValidator = new UrlValidator(new String[] { "https" });
+			if (!urlValidator.isValid(stratosURL)) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Stratos Controller URL {} is not valid", stratosURL);
+				}
+				System.out.format(
+						"The \"%s\" variable in your environment is not a valid URL. You have provided \"%s\".%n"
+								+ "Please provide the Stratos Controller URL as follows%nhttps://<host>:<port>%n",
+						CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
+				return false;
+			}
+			if (logger.isDebugEnabled()) {
+				logger.debug("Stratos Controller URL {} is valid.", stratosURL);
+				logger.debug("Adding the values to context.");
+			}
+			context.put(CliConstants.STRATOS_URL_ENV_PROPERTY, stratosURL);
+			context.put(CliConstants.STRATOS_USERNAME_ENV_PROPERTY, username);
+			context.put(CliConstants.STRATOS_PASSWORD_ENV_PROPERTY, password);
+			return true;
+		}
+	}
+	
+	private void setLoggerLevel(boolean trace, boolean debug) {
+		// We are using Log4j. So, get the logger and set log levels.
+		org.apache.log4j.Logger logger = LogManager.getLogger(StratosApplication.class.getPackage().getName());
+		if (logger != null && trace) {
+			logger.setLevel(Level.TRACE);
+			LogManager.getRootLogger().setLevel(Level.TRACE);
+		} else if (logger != null && debug) {
+			logger.setLevel(Level.DEBUG);
+			LogManager.getRootLogger().setLevel(Level.DEBUG);
+		}
+	}
+
+	public void printHelp(final String action) {
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			System.out.println(action + ": command not found. Help not available.");
+			return;
+		}
+		System.out.println(command.getDescription());
+		Options options = command.getOptions();
+		if (options != null) {
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				printHelp(command.getName() + " " + command.getArgumentSyntax(), options);
+			} else {
+				printHelp(command.getName(), options);
+			}
+		} else {
+			// No options. Just print the usage.
+			printUsage(command);
+		}
+	}
+
+	public void printHelp() {
+		printHelp(CliConstants.STRATOS_APPLICATION_NAME, options);
+		System.out.println("\n\nAvailable Commands: ");
+		for (String action : commands.keySet()) {
+			Command<StratosCommandContext> command = commands.get(action);
+			if (command != null) {
+				System.out.format("%-25s %s%n", command.getName(), command.getDescription());
+			}
+		}
+
+		System.out.println("\nFor help on a specific command type:\nhelp [command]");
+	}
+
+	/**
+	 * Print "help" with usage
+	 */
+	private void printHelp(final String commandLineSyntax, final Options options) {
+		final HelpFormatter helpFormatter = new HelpFormatter();
+		helpFormatter.printHelp(commandLineSyntax, options, true);
+	}
+	
+	public void printUsage(final String action) {
+		Command<StratosCommandContext> command = commands.get(action);
+		if (command == null) {
+			return;
+		}
+		printUsage(command);
+	}
+	
+	private void printUsage(Command<StratosCommandContext> command) {
+		Options options = command.getOptions();
+		if (options != null) {
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				printUsage(command.getName() + " " + command.getArgumentSyntax(), options);
+			} else {
+				printUsage(command.getName(), options);
+			}
+		} else {
+			System.out.print("usage: ");
+			if (StringUtils.isNotBlank(command.getArgumentSyntax())) {
+				System.out.println(command.getName() + " " + command.getArgumentSyntax());
+			} else {
+				System.out.println(command.getName());
+			}
+		}
+	}
+	
+	/**
+	 * Print "usage"
+	 */
+	private void printUsage(final String commandLineSyntax, final Options options) {
+		final PrintWriter writer = new PrintWriter(System.out);
+		final HelpFormatter usageFormatter = new HelpFormatter();
+		usageFormatter.printUsage(writer, 80, commandLineSyntax, options);
+		writer.flush();
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosCommandContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosCommandContext.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosCommandContext.java
new file mode 100644
index 0000000..4ffb8e4
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/StratosCommandContext.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+public class StratosCommandContext extends CommandContext {
+
+	public StratosCommandContext(StratosApplication application) {
+		super(application);
+	}
+
+	public StratosApplication getStratosApplication() {
+		return (StratosApplication) getApplication();
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/AddDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/AddDomainMappingCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/AddDomainMappingCommand.java
new file mode 100644
index 0000000..b6029e3
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/AddDomainMappingCommand.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class AddDomainMappingCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(AddDomainMappingCommand.class);
+
+	public AddDomainMappingCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.ADD_DOMAIN_MAPPING_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Map domain for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias] [Domain]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 2) {
+			String alias = args[0];
+			String domain = args[1];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Adding domain mapping {} for alias {}", domain, alias);
+			}
+
+			String domainToDisplay = null;
+
+			domainToDisplay = CommandLineService.getInstance().addDomainMapping(domain, alias);
+
+			if (StringUtils.isBlank(domainToDisplay)) {
+				System.out.println("Error adding domain mapping.");
+				return CliConstants.BAD_ARGS_CODE;
+			} else {
+				System.out.format("Your own domain is added. Please CNAME it to systems domain %s.%n", domainToDisplay);
+				return CliConstants.SUCCESSFUL_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/CartridgesCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/CartridgesCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/CartridgesCommand.java
new file mode 100644
index 0000000..07cc8ce
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/CartridgesCommand.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class CartridgesCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(CartridgesCommand.class);
+
+	public CartridgesCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.CARTRIDGES_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List available cartridges";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listAvailableCartridges();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ExitCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ExitCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ExitCommand.java
new file mode 100644
index 0000000..8123eee
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ExitCommand.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class ExitCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ExitCommand.class);
+
+	public ExitCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.EXIT_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Exit from Stratos Client Tool";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		// Nothing to execute here. This is a special command.
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/HelpCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/HelpCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/HelpCommand.java
new file mode 100644
index 0000000..1afcf70
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/HelpCommand.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class HelpCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(HelpCommand.class);
+
+	public HelpCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.HELP_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Help for commands";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[command]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			context.getStratosApplication().printHelp();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else if (args != null && args.length == 1) {
+			context.getStratosApplication().printHelp(args[0]);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/InfoCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/InfoCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/InfoCommand.java
new file mode 100644
index 0000000..a596f16
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/InfoCommand.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class InfoCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(InfoCommand.class);
+
+	public InfoCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.INFO_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Get information about a subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Getting info {}", alias);
+			}
+			CommandLineService.getInstance().info(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ListCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ListCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ListCommand.java
new file mode 100644
index 0000000..4227107
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/ListCommand.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class ListCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
+	
+	private final Options options;
+
+	public ListCommand() {
+		options = constructOptions();
+	}
+	
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option fullOption = new Option(CliConstants.FULL_OPTION, CliConstants.FULL_LONG_OPTION, false,
+				"Display extra details");
+		options.addOption(fullOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.LIST_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List subscribed cartridges with details";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listSubscribedCartridges(false);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			boolean full = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (!(remainingArgs == null || remainingArgs.length == 0)) {
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (commandLine.hasOption(CliConstants.FULL_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Full option is passed");
+					}
+					full = true;
+				}
+				if (logger.isDebugEnabled()) {
+					logger.debug("Listing subscribed cartridges, Full Option: {}", full);
+				}
+				CommandLineService.getInstance().listSubscribedCartridges(full);
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/PoliciesCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/PoliciesCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/PoliciesCommand.java
new file mode 100644
index 0000000..0c67066
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/PoliciesCommand.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class PoliciesCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(PoliciesCommand.class);
+
+	public PoliciesCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.POLICIES_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "List available policies";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return null;
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args == null || args.length == 0) {
+			CommandLineService.getInstance().listAvailablePolicies();
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/RemoveDomainMappingCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
new file mode 100644
index 0000000..c394421
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/RemoveDomainMappingCommand.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class RemoveDomainMappingCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(RemoveDomainMappingCommand.class);
+
+	public RemoveDomainMappingCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.REMOVE_DOMAIN_MAPPING_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Remove domain mapping for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Removing domain mapping for {}", alias);
+			}
+			CommandLineService.getInstance().removeDomainMapping(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SubscribeCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SubscribeCommand.java
new file mode 100644
index 0000000..be49e2a
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SubscribeCommand.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class SubscribeCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(ListCommand.class);
+
+	private final Options options;;
+
+	public SubscribeCommand() {
+		options = constructOptions();
+	}
+
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option policyOption = new Option(CliConstants.POLICY_OPTION, CliConstants.POLICY_LONG_OPTION, true,
+				"Auto-scaling policy.\nPlease use \"" + CliConstants.POLICIES_ACTION
+						+ "\" command to view the available policies.");
+		policyOption.setArgName("policy name");
+		options.addOption(policyOption);
+
+		Option connectOption = new Option(CliConstants.CONNECT_OPTION, CliConstants.CONNECT_LONG_OPTION, true,
+				"Data cartridge type");
+		connectOption.setArgName("data cartridge type");
+		options.addOption(connectOption);
+
+		Option aliasOption = new Option(CliConstants.DATA_ALIAS_OPTION, CliConstants.DATA_ALIAS_LONG_OPTION, true,
+				"Data cartridge alias");
+		aliasOption.setArgName("alias");
+		options.addOption(aliasOption);
+
+		Option urlOption = new Option(CliConstants.REPO_URL_OPTION, CliConstants.REPO_URL_LONG_OPTION, true,
+				"GIT repository URL");
+		urlOption.setArgName("url");
+		options.addOption(urlOption);
+
+		options.addOption(CliConstants.PRIVATE_REPO_OPTION, CliConstants.PRIVATE_REPO_LONG_OPTION, false,
+				"Private repository");
+
+		Option usernameOption = new Option(CliConstants.USERNAME_OPTION, CliConstants.USERNAME_LONG_OPTION, true,
+				"GIT repository username");
+		usernameOption.setArgName("username");
+		options.addOption(usernameOption);
+
+		Option passwordOption = new Option(CliConstants.PASSWORD_OPTION, CliConstants.PASSWORD_LONG_OPTION, true,
+				"GIT repository password");
+		passwordOption.setArgName("password");
+		passwordOption.setOptionalArg(true);
+		options.addOption(passwordOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.SUBSCRIBE_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Subscribe to a cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge type] [Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			String type = null;
+			String alias = null;
+			String policy = null;
+			String repoURL = null, dataCartridgeType = null, dataCartridgeAlias = null, username = "", password = "";
+			boolean privateRepo = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length == 2) {
+					// Get type
+					type = remainingArgs[0];
+					alias = remainingArgs[1];
+				} else {
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (logger.isDebugEnabled()) {
+					logger.debug("Subscribing to {} cartridge with alias {}", type, alias);
+				}
+
+				if (commandLine.hasOption(CliConstants.POLICY_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Policy option is passed");
+					}
+					policy = commandLine.getOptionValue(CliConstants.POLICY_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.REPO_URL_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("RepoURL option is passed");
+					}
+					repoURL = commandLine.getOptionValue(CliConstants.REPO_URL_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PRIVATE_REPO_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("privateRepo option is passed");
+					}
+					privateRepo = true;
+				}
+				if (commandLine.hasOption(CliConstants.USERNAME_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Username option is passed");
+					}
+					username = commandLine.getOptionValue(CliConstants.USERNAME_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.PASSWORD_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Password option is passed");
+					}
+					password = commandLine.getOptionValue(CliConstants.PASSWORD_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.CONNECT_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Connect option is passed");
+					}
+					dataCartridgeType = commandLine.getOptionValue(CliConstants.CONNECT_OPTION);
+				}
+				if (commandLine.hasOption(CliConstants.DATA_ALIAS_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Data alias option is passed");
+					}
+					dataCartridgeAlias = commandLine.getOptionValue(CliConstants.DATA_ALIAS_OPTION);
+				}
+				
+				if (StringUtils.isNotBlank(username) && StringUtils.isBlank(password)) {
+					password = context.getApplication().getInput("GIT Repository Password", '*');
+				}
+
+				if (StringUtils.isNotBlank(dataCartridgeType) && !StringUtils.isNotBlank(dataCartridgeAlias)) {
+					System.out.println("Data cartridge alias is required.");
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+				CommandLineService.getInstance().subscribe(type, alias, policy, repoURL, privateRepo, username,
+						password, dataCartridgeType, dataCartridgeAlias);
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SyncCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SyncCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SyncCommand.java
new file mode 100644
index 0000000..f8e8518
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/SyncCommand.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.Options;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class SyncCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(SyncCommand.class);
+
+	public SyncCommand() {
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.SYNC_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Synchronize GIT repository for the subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length == 1) {
+			String alias = args[0];
+			if (logger.isDebugEnabled()) {
+				logger.debug("Synchronizing repository for alias {}", alias);
+			}
+
+			CommandLineService.getInstance().sync(alias);
+			return CliConstants.SUCCESSFUL_CODE;
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return null;
+	}
+
+}


[08/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
new file mode 100644
index 0000000..d6c722c
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/axiom/AxiomXpathParser.java
@@ -0,0 +1,1263 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.axiom;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
+import org.apache.axiom.om.impl.dom.ElementImpl;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.w3c.dom.Element;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.exception.MalformedConfigurationFileException;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.AppType;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.stratos.cloud.controller.util.PortMapping;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * This class is parsing configuration files using Axiom Xpath.
+ */
+public class AxiomXpathParser {
+
+	private static final Log log = LogFactory.getLog(AxiomXpathParser.class);
+	private OMElement documentElement;
+	private final File xmlSource;
+
+	public AxiomXpathParser(final File xmlFile) {
+		xmlSource = xmlFile;
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link Cartridge} instance.
+     * @param appTypesNodes nodes of App types.
+     */
+    private void getAppTypes(String cartridgeElementString, Cartridge aCartridge,
+                             List<?> appTypesNodes) {
+	    Object nodeObj;
+	    if (!appTypesNodes.isEmpty()) {
+	    	if ((nodeObj = appTypesNodes.get(0)) instanceof OMNode) {
+	    		OMNode appTypeNode = (OMNode) nodeObj;
+
+	    		if (appTypeNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement appTypesElt = (OMElement) appTypeNode;
+
+	    			for (Iterator<?> iterator =
+	    			                            appTypesElt.getChildrenWithName(new QName(
+	    			                                                                      CloudControllerConstants.APP_TYPE_ELEMENT)); iterator.hasNext();) {
+	    				OMElement appElt = (OMElement) iterator.next();
+
+	    				String name =
+	    				              appElt.getAttributeValue(new QName(
+	    				                                                 CloudControllerConstants.NAME_ATTR));
+	    				String appSpecificMapping =
+	    				                            appElt.getAttributeValue(new QName(
+	    				                                                               CloudControllerConstants.APP_SPECIFIC_MAPPING_ATTR));
+
+	    				AppType appType;
+
+	    				if (appSpecificMapping == null) {
+	    					appType = new AppType(name);
+	    				} else {
+	    					appType =
+	    					          new AppType(name,
+	    					                      Boolean.valueOf(appSpecificMapping));
+	    				}
+
+	    				aCartridge.addAppType(appType);
+	    			}
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" + CloudControllerConstants.APP_TYPE_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	/**
+	 * @return a List of {@link Cartridge}s.
+	 */
+	public List<Cartridge> getCartridgesList() {
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+
+		List<IaasProvider> iaasProviders = dataHolder.getIaasProviders();
+
+		if (iaasProviders == null) {
+			dataHolder.setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
+		}
+
+		List<Cartridge> cartridges = new ArrayList<Cartridge>();
+
+		String xpath = CloudControllerConstants.CARTRIDGES_ELEMENT_XPATH;
+		
+		// cartridges can be found from this XPATH
+		List<?> cartridgeNodes = getMatchingNodes(xpath, documentElement);
+
+		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
+			// or from this XPATH
+			xpath = CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH;
+			cartridgeNodes = getMatchingNodes(xpath, documentElement);
+		}
+
+		if (cartridgeNodes == null || cartridgeNodes.isEmpty()) {
+			log.warn("No cartridge found in this configuration file : " + xmlSource.getPath());
+			return cartridges;
+		}
+
+		for (Object obj : cartridgeNodes) {
+
+			if (obj instanceof OMNode) {
+				OMNode cartridgeNode = (OMNode) obj;
+
+				if (cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
+
+					OMElement cartridgeElement = (OMElement) cartridgeNode;
+
+					// retrieve Attributes of a Cartridge definition
+					String type = cartridgeElement.getAttributeValue(new QName(
+					                                                           CloudControllerConstants.TYPE_ATTR));
+					String host = cartridgeElement.getAttributeValue(new QName(
+					                                                           CloudControllerConstants.HOST_ATTR));
+					String provider = cartridgeElement.getAttributeValue(new QName(
+					                                                               CloudControllerConstants.PROVIDER_ATTR));
+					
+					String version =
+			                  cartridgeElement.getAttributeValue(new QName(
+			                                                               CloudControllerConstants.VERSION_ATTR));
+
+					boolean multiTenant = Boolean.valueOf(cartridgeElement.getAttributeValue(new QName(
+							CloudControllerConstants.MULTI_TENANT_ATTR)));
+
+					Cartridge aCartridge;
+
+					if ((aCartridge = dataHolder.getCartridge(type)) == null) {
+
+						aCartridge = new Cartridge(type, host, provider, version, multiTenant);
+					}
+					
+					// read displayName
+					Iterator<?> itName =
+					                 cartridgeElement.getChildrenWithName(new QName(
+					                                                                CloudControllerConstants.DISPLAY_NAME_ELEMENT));
+
+					if (itName.hasNext()) {
+						OMElement name = (OMElement) itName.next();
+
+						aCartridge.setDisplayName(name.getText());
+					}
+					
+					// read description
+					Iterator<?> it =
+					                 cartridgeElement.getChildrenWithName(new QName(
+					                                                                CloudControllerConstants.DESCRIPTION_ELEMENT));
+
+					if (it.hasNext()) {
+						OMElement desc = (OMElement) it.next();
+
+						aCartridge.setDescription(desc.getText());
+					}
+
+					// load properties of this cartridge
+					loadProperties(cartridgeElement, aCartridge.getProperties());
+
+					// retrieve the list of IaaS providers
+					List<?> iaasProviderNodes = getMatchingNodes(xpath + CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH,
+					                                             cartridgeElement);
+
+					getIaasProviders(iaasProviders, cartridgeElement.toString(), aCartridge, iaasProviderNodes);
+
+					// load dirs
+					List<?> deploymentNodes = getMatchingNodes(xpath + CloudControllerConstants.DEPLOYMENT_ELEMENT_XPATH,
+					                                           cartridgeElement);
+                    setDeploymentDirs(cartridgeElement.toString(), aCartridge, deploymentNodes);
+
+					// load port mappings
+					List<?> portMappingNodes =
+					                           getMatchingNodes(xpath +
+					                                                    CloudControllerConstants.PORT_MAPPING_ELEMENT_XPATH,
+					                                            cartridgeElement);
+					getPortMappings(cartridgeElement.toString(), aCartridge, portMappingNodes);
+
+					// load appTypes
+					List<?> appTypesNodes =
+					                        getMatchingNodes(xpath +
+					                                                 CloudControllerConstants.APP_TYPES_ELEMENT_XPATH,
+					                                         cartridgeElement);
+					getAppTypes(cartridgeElement.toString(), aCartridge, appTypesNodes);
+
+					cartridges.add(aCartridge);
+
+					if (dataHolder.getCartridge(type) == null) {
+						dataHolder.addCartridge(aCartridge);
+					}
+				}
+			}
+		}
+
+		return cartridges;
+
+	}
+
+	/**
+     * @param iaasProviders
+     * @param cartridgeElementString
+     * @param aCartridge
+     * @param iaasProviderNodes
+     */
+    private void getIaasProviders(List<IaasProvider> iaasProviders,
+                                  String cartridgeElementString, Cartridge aCartridge,
+                                  List<?> iaasProviderNodes) {
+	    for (Object nodeObj : iaasProviderNodes) {
+	    	if (nodeObj instanceof OMNode) {
+	    		OMNode iaasProviderNode = (OMNode) nodeObj;
+
+	    		if (iaasProviderNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement iaasElt = (OMElement) iaasProviderNode;
+
+	    			// add the IaasProvider to this cartridge
+	    			aCartridge.addIaasProvider(getIaasProvider(iaasElt, iaasProviders));
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" +
+	    			                     CloudControllerConstants.IAAS_PROVIDER_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	private Element getDOMElement(final OMElement omElement) {
+
+		// Get the StAX reader from the created element
+		XMLStreamReader llomReader = omElement.getXMLStreamReader();
+
+		// Create the DOOM OMFactory
+		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
+
+		// Create the new builder
+		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
+
+		// Get the document element
+		OMElement newElem = doomBuilder.getDocumentElement();
+
+		return newElem instanceof Element ? (Element) newElem : null;
+	}
+
+	private OMElement getElement(final Object obj) {
+		OMNode node;
+		if ((obj instanceof OMNode) && (node = (OMNode) obj).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement element = (OMElement) node;
+
+			return element;
+
+		}
+
+		return null;
+	}
+
+	private OMElement getElement(final OMElement rootElt, final String eltStr, final String xpath) {
+		List<?> nodes = getMatchingNodes(xpath, rootElt);
+		neglectingWarn(eltStr, nodes.size());
+		OMElement element = getElement(nodes.get(0));
+		return element;
+	}
+
+	private OMElement getFirstChildElement(final OMElement root, final String childName) {
+		Iterator<?> it = root.getChildrenWithName(new QName(childName));
+		if (it.hasNext()) {
+			return (OMElement) it.next();
+		}
+
+		return null;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @param elt
+	 *            OMElement to be used for the search.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public OMNode getFirstMatchingNode(final String xpath, final OMElement elt) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(elt);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList != null ? nodeList.get(0) : null;
+	}
+
+	private IaasProvider getIaasProvider(final OMNode item, List<IaasProvider> iaases) {
+
+		IaasProvider iaas = null;
+
+		if (item.getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement iaasElt = (OMElement) item;
+
+			if (iaases != null) {
+				// check whether this is a reference to a predefined IaaS.
+				for (IaasProvider iaasProvider : iaases) {
+					if (iaasProvider.getType()
+					                .equals(iaasElt.getAttribute(new QName(
+					                                                       CloudControllerConstants.TYPE_ATTR))
+					                               .getAttributeValue())) {
+						iaas = new IaasProvider(iaasProvider);
+						break;
+					}
+				}
+			}
+
+			if (iaas == null) {
+				iaas = new IaasProvider();
+			}
+
+			if (iaas.getType() == null) {
+				iaas.setType(iaasElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
+				                    .getAttributeValue());
+			}
+
+			if ("".equals(iaas.getType())) {
+				String msg =
+				             "'" + CloudControllerConstants.IAAS_PROVIDER_ELEMENT + "' element's '" +
+				                     CloudControllerConstants.TYPE_ATTR +
+				                     "' attribute should be specified!";
+
+				handleException(msg);
+
+			}
+
+			// this is not mandatory
+			String name =
+			              (iaasElt.getAttribute(new QName(CloudControllerConstants.NAME_ATTR)) == null)
+			                                                                                     ? iaas.getName()
+			                                                                                     : iaasElt.getAttributeValue(new QName(
+			                                                                                                                           CloudControllerConstants.NAME_ATTR));
+
+			iaas.setName(name);
+
+			String xpath = CloudControllerConstants.IAAS_PROVIDER_ELEMENT_XPATH;
+
+			// load other elements
+			loadClassName(iaas, iaasElt);
+			loadMaxInstanceLimit(iaas, iaasElt);
+			loadProperties(iaasElt, iaas.getProperties());
+			loadTemplate(iaas, iaasElt);
+			loadScalingOrders(iaas, iaasElt);
+			loadProvider(iaas, iaasElt);
+			loadIdentity(iaas, iaasElt);
+			loadCredentials(iaas, iaasElt, xpath);
+		}
+
+		return iaas;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public List<OMNode> getMatchingNodes(final String xpath) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(documentElement);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList;
+	}
+
+	/**
+	 * 
+	 * @param xpath
+	 *            XPATH expression to be read.
+	 * @param elt
+	 *            OMElement to be used for the search.
+	 * @return List matching OMNode list
+	 */
+	@SuppressWarnings("unchecked")
+	public List<OMNode> getMatchingNodes(final String xpath, final OMElement elt) {
+
+		AXIOMXPath axiomXpath;
+		List<OMNode> nodeList = null;
+		try {
+			axiomXpath = new AXIOMXPath(xpath);
+			nodeList = axiomXpath.selectNodes(elt);
+		} catch (JaxenException e) {
+			String msg = "Error occurred while reading the Xpath (" + xpath + ")";
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		return nodeList;
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link Cartridge} instance.
+     * @param portMappingNodes nodes of port mapping elements
+     */
+    private void getPortMappings(String cartridgeElementString, Cartridge aCartridge,
+                                 List<?> portMappingNodes) {
+	    Object nodeObj;
+	    if (!portMappingNodes.isEmpty()) {
+	    	if ((nodeObj = portMappingNodes.get(0)) instanceof OMNode) {
+	    		OMNode portMappingNode = (OMNode) nodeObj;
+
+	    		if (portMappingNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    			OMElement portMappingElt = (OMElement) portMappingNode;
+
+	    			for (Iterator<?> iterator =
+	    			                            portMappingElt.getChildrenWithName(new QName(
+	    			                                                                         CloudControllerConstants.HTTP_ELEMENT)); iterator.hasNext();) {
+	    				OMElement httpElt = (OMElement) iterator.next();
+
+	    				String port =
+	    				              httpElt.getAttributeValue(new QName(
+	    				                                                  CloudControllerConstants.PORT_ATTR));
+	    				String proxyPort =
+	    				                   httpElt.getAttributeValue(new QName(
+	    				                                                       CloudControllerConstants.PROXY_PORT_ATTR));
+
+	    				PortMapping mapping =
+	    				                      new PortMapping(
+	    				                                      CloudControllerConstants.HTTP_ELEMENT,
+	    				                                      port, proxyPort);
+
+	    				aCartridge.addPortMapping(mapping);
+	    			}
+
+	    			for (Iterator<?> iterator =
+	    			                            portMappingElt.getChildrenWithName(new QName(
+	    			                                                                         CloudControllerConstants.HTTPS_ELEMENT)); iterator.hasNext();) {
+	    				OMElement httpsElt = (OMElement) iterator.next();
+
+	    				String port =
+	    				              httpsElt.getAttributeValue(new QName(
+	    				                                                   CloudControllerConstants.PORT_ATTR));
+	    				String proxyPort =
+	    				                   httpsElt.getAttributeValue(new QName(
+	    				                                                        CloudControllerConstants.PROXY_PORT_ATTR));
+
+	    				PortMapping mapping =
+	    				                      new PortMapping(
+	    				                                      CloudControllerConstants.HTTPS_ELEMENT,
+	    				                                      port, proxyPort);
+
+	    				aCartridge.addPortMapping(mapping);
+	    			}
+
+	    		} else {
+	    			String msg =
+	    			             "Essential '" +
+	    			                     CloudControllerConstants.PORT_MAPPING_ELEMENT +
+	    			                     "' element cannot" + " be found in " +
+	    			                     cartridgeElementString + " of " +
+	    			                     xmlSource;
+	    			handleException(msg);
+	    		}
+
+	    	}
+	    }
+    }
+
+	public List<ServiceContext> getServiceContexts() {
+
+		List<ServiceContext> serviceContextList = new ArrayList<ServiceContext>();
+
+		// services can be found from this XPATH
+		String xpath = CloudControllerConstants.SERVICES_ELEMENT_XPATH;
+		List<?> serviceNodes = getMatchingNodes(xpath, documentElement);
+
+		if (serviceNodes == null || serviceNodes.isEmpty()) {
+			// or from this XPATH
+			xpath = CloudControllerConstants.SERVICE_ELEMENT_XPATH;
+			serviceNodes = getMatchingNodes(xpath, documentElement);
+		}
+
+		if (serviceNodes == null || serviceNodes.isEmpty()) {
+			log.warn("No service found in this configuration file : " + xmlSource.getPath());
+			return serviceContextList;
+		}
+
+		for (Object obj : serviceNodes) {
+			ServiceContext serviceCtxt = new ServiceContext();
+
+			// set the definition file
+			serviceCtxt.setFile(xmlSource);
+			
+			if (obj instanceof OMNode) {
+				OMNode serviceNode = (OMNode) obj;
+
+				if (serviceNode.getType() == OMNode.ELEMENT_NODE) {
+
+					OMElement node = (OMElement) serviceNode;
+
+					if (node.getAttribute(new QName(CloudControllerConstants.SERVICE_DOMAIN_ATTR)) == null) {
+						String msg =
+						             "Essential '" + CloudControllerConstants.SERVICE_DOMAIN_ATTR + "' " +
+						                     "attribute of '" + CloudControllerConstants.SERVICE_ELEMENT +
+						                     "' element cannot be found in " + xmlSource;
+
+						handleException(msg);
+					}
+
+					// set domain name
+					serviceCtxt.setDomainName(node.getAttribute(new QName(
+					                                                      CloudControllerConstants.SERVICE_DOMAIN_ATTR))
+					                              .getAttributeValue());
+
+					// set sub domain
+					serviceCtxt.setSubDomainName(node.getAttribute(new QName(
+					                                                         CloudControllerConstants.SERVICE_SUB_DOMAIN_ATTR))
+					                                 .getAttributeValue());
+
+					// set tenant range
+					serviceCtxt.setTenantRange(node.getAttribute(new QName(
+					                                                       CloudControllerConstants.SERVICE_TENANT_RANGE_ATTR))
+					                               .getAttributeValue());
+
+					OMNode cartridgeNode =
+					                       getFirstMatchingNode(xpath +
+					                                                    CloudControllerConstants.CARTRIDGE_ELEMENT_XPATH,
+					                                            node);
+
+					if (cartridgeNode != null && cartridgeNode.getType() == OMNode.ELEMENT_NODE) {
+
+						OMElement cartridgeElt = (OMElement) cartridgeNode;
+
+						String type =
+								cartridgeElt.getAttribute(new QName(CloudControllerConstants.TYPE_ATTR))
+						                  .getAttributeValue();
+
+						if ("".equals(type)) {
+							String msg =
+							             "Essential '" + CloudControllerConstants.TYPE_ATTR + "' " +
+							                     " attribute of '" +
+							                     CloudControllerConstants.CARTRIDGE_ELEMENT + "' of '" +
+							                     CloudControllerConstants.SERVICE_ELEMENT +
+							                     "' element cannot be found in " + xmlSource;
+
+							handleException(msg);
+						}
+						
+						// set Cartridge type
+						serviceCtxt.setCartridgeType(type);
+
+					}
+					if (serviceCtxt.getCartridgeType() == null) {
+						String msg =
+						             "Essential '" + CloudControllerConstants.CARTRIDGE_ELEMENT +
+						                     "' element" + " has not specified in " + xmlSource;
+						handleException(msg);
+					}
+
+					// load payload
+					loadPayload(getMatchingNodes(xpath + CloudControllerConstants.PAYLOAD_ELEMENT_XPATH,
+					                             node), serviceCtxt);
+
+					// load host name
+					loadHostName(getMatchingNodes(xpath + CloudControllerConstants.HOST_ELEMENT_XPATH,
+					                              node), serviceCtxt);
+
+					// load properties
+					loadProperties(node, serviceCtxt.getProperties());
+
+				}
+			}
+
+			FasterLookUpDataHolder.getInstance().addServiceContext(serviceCtxt);
+			// add each domain specific template to list
+			serviceContextList.add(serviceCtxt);
+		}
+
+		return serviceContextList;
+
+	}
+
+	public File getXmlSource() {
+		return xmlSource;
+	}
+
+	private void handleException(final String msg) {
+		log.error(msg);
+		throw new MalformedConfigurationFileException(msg);
+	}
+
+	private void handleException(final String msg, final Exception e) {
+		log.error(msg, e);
+		throw new MalformedConfigurationFileException(msg, e);
+	}
+
+	private void loadClassName(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.CLASS_NAME_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement classNameElt = (OMElement) it.next();
+			iaas.setClassName(classNameElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.CLASS_NAME_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getClassName() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.CLASS_NAME_ELEMENT + "' element " +
+			                     "has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadCredentials(final IaasProvider iaas, final OMElement iaasElt,
+	                             final String xpath) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.CREDENTIAL_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement credentialElt = (OMElement) it.next();
+
+			// retrieve the value using secure vault
+			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+			String alias =
+			               credentialElt.getAttributeValue(new QName(
+			                                                         CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+			// retrieve the secured password
+			if (secretResolver != null && secretResolver.isInitialized() &&
+			    secretResolver.isTokenProtected(alias)) {
+
+				iaas.setCredential(secretResolver.resolve(alias));
+
+			}
+
+			// if we still cannot find a value, we try to assign the value which
+			// is specified
+			// in the element, if any
+			if (iaas.getCredential() == null) {
+				log.warn("Unable to find a value for " + CloudControllerConstants.CREDENTIAL_ELEMENT +
+				         " element from Secure Vault." +
+				         "Hence we will try to assign the plain text value (if specified).");
+				iaas.setCredential(credentialElt.getText());
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.CREDENTIAL_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getCredential() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.CREDENTIAL_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+	
+	private void loadHostName(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
+
+		if (nodes == null || nodes.isEmpty()) {
+			return;
+		}
+
+		// read host element
+		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement node = (OMElement) nodes.get(0);
+
+			if (node.getText() != null) {
+				serviceCtxt.setHostName(node.getText());
+			}
+
+		}
+	}
+
+	private void loadIdentity(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IDENTITY_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement identityElt = (OMElement) it.next();
+
+			// retrieve the value using secure vault
+			SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+			String alias =
+			               identityElt.getAttributeValue(new QName(
+			                                                       CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+			// retrieve the secured password
+			if (secretResolver != null && secretResolver.isInitialized() &&
+			    secretResolver.isTokenProtected(alias)) {
+
+				iaas.setIdentity(secretResolver.resolve(alias));
+
+			}
+
+			// if we still cannot find a value, we try to assign the value which
+			// is specified
+			// in the element, if any
+			if (iaas.getIdentity() == null) {
+				log.warn("Unable to find a value for " + CloudControllerConstants.IDENTITY_ELEMENT +
+				         " element from Secure Vault." +
+				         "Hence we will try to assign the plain text value (if specified).");
+				iaas.setIdentity(identityElt.getText());
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IDENTITY_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getIdentity() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.IDENTITY_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadMaxInstanceLimit(IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement maxInstanceLimitElt = (OMElement) it.next();
+
+			try {
+				iaas.setMaxInstanceLimit(Integer.parseInt(maxInstanceLimitElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT +
+				                     " element contained" + " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.MAX_INSTANCE_LIMIT_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+	}
+
+	private void loadPayload(final List<OMNode> nodes, final ServiceContext serviceCtxt) {
+
+		if (nodes == null || nodes.isEmpty()) {
+			return;
+		}
+
+		// read payload element
+		if (nodes.get(0).getType() == OMNode.ELEMENT_NODE) {
+
+			OMElement node = (OMElement) nodes.get(0);
+
+			if (node.getText() != null) {
+				byte[] payload = CloudControllerUtil.getBytesFromFile(node.getText());
+				serviceCtxt.setPayload(payload);
+
+			}
+
+		}
+
+	}
+
+	private void loadProperties(final OMElement iaasElt, final Map<String, String> propertyMap) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROPERTY_ELEMENT));
+
+		while (it.hasNext()) {
+			OMElement prop = (OMElement) it.next();
+
+			if (prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR)) == null ||
+			    prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR)) == null) {
+
+				String msg =
+				             "Property element's, name and value attributes should be specified " +
+				                     "in " + xmlSource;
+
+				handleException(msg);
+			}
+
+			propertyMap.put(prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_NAME_ATTR))
+			                    .getAttributeValue(),
+			                prop.getAttribute(new QName(CloudControllerConstants.PROPERTY_VALUE_ATTR))
+			                    .getAttributeValue());
+		}
+
+	}
+
+	private void loadProvider(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.PROVIDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement providerElt = (OMElement) it.next();
+			iaas.setProvider(providerElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.PROVIDER_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getProvider() == null) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.PROVIDER_ELEMENT + "' element " +
+			                     "has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadScalingOrders(final IaasProvider iaas, final OMElement iaasElt) {
+		// set scale up order
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(
+		                                                       CloudControllerConstants.SCALE_UP_ORDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement scaleUpOrderElt = (OMElement) it.next();
+
+			try {
+				iaas.setScaleUpOrder(Integer.parseInt(scaleUpOrderElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " element contained" +
+				                     " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getScaleUpOrder() == -1) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.SCALE_UP_ORDER_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+		// set scale down order
+		it = iaasElt.getChildrenWithName(new QName(CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement scaleDownElt = (OMElement) it.next();
+
+			try {
+				iaas.setScaleDownOrder(Integer.parseInt(scaleDownElt.getText()));
+			} catch (NumberFormatException e) {
+				String msg =
+				             CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " element contained" +
+				                     " in " + xmlSource + "" +
+				                     " has a value which is not an Integer value.";
+				handleException(msg, e);
+			}
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " +
+			         CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+
+		if (iaas.getScaleDownOrder() == -1) {
+			String msg =
+			             "Essential '" + CloudControllerConstants.SCALE_DOWN_ORDER_ELEMENT + "' element" +
+			                     " has not specified in " + xmlSource;
+			handleException(msg);
+		}
+
+	}
+
+	private void loadTemplate(final IaasProvider iaas, final OMElement iaasElt) {
+
+		Iterator<?> it =
+		                 iaasElt.getChildrenWithName(new QName(CloudControllerConstants.IMAGE_ID_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement imageElt = (OMElement) it.next();
+			iaas.setImage(imageElt.getText());
+		}
+
+		if (it.hasNext()) {
+			log.warn(xmlSource + " contains more than one " + CloudControllerConstants.IMAGE_ID_ELEMENT +
+			         " elements!" + " Elements other than the first will be neglected.");
+		}
+
+	}
+
+	private void neglectingWarn(final String elt, final int size) {
+		if (size > 1) {
+			log.warn(xmlSource + " contains more than one " + elt + " elements!" +
+			         " Elements other than the first will be neglected.");
+		}
+	}
+
+	public void parse() {
+
+		if (xmlSource.exists()) {
+			try {
+				documentElement = new StAXOMBuilder(xmlSource.getPath()).getDocumentElement();
+
+			} catch (Exception ex) {
+				String msg = "Error occurred when parsing the " + xmlSource.getPath() + ".";
+				handleException(msg, ex);
+			}
+		} else {
+			String msg = "Configuration file cannot be found : " + xmlSource.getPath();
+			handleException(msg);
+		}
+	}
+
+	private void plainTextWarn(final String elt) {
+		log.warn("Unable to find a value for " + elt + " element from Secure Vault." +
+		         "Hence we will try to assign the plain text value (if specified).");
+	}
+
+	private String resolveSecret(final OMElement elt) {
+		// retrieve the value using secure vault
+		SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+
+		String alias = elt.getAttributeValue(new QName(CloudControllerConstants.ALIAS_ATTRIBUTE));
+
+		// retrieve the secured password
+		if (secretResolver != null && secretResolver.isInitialized() &&
+		    secretResolver.isTokenProtected(alias)) {
+
+			return secretResolver.resolve(alias);
+
+		}
+
+		return null;
+	}
+
+	public void setDataPublisherRelatedData() {
+
+		String eltStr = CloudControllerConstants.DATA_PUBLISHER_ELEMENT;
+		// get dataPublisher element
+		OMElement element =
+		                    getElement(documentElement, eltStr,
+		                               CloudControllerConstants.DATA_PUBLISHER_XPATH);
+
+		if (element == null) {
+			return;
+		}
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+		// get enable attribute
+		boolean isEnable =
+		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
+		                                                                            CloudControllerConstants.ENABLE_ATTR)));
+		dataHolder.setEnableBAMDataPublisher(isEnable);
+
+		if (isEnable) {
+			// get bam server info
+			OMElement childElement =
+			                         getFirstChildElement(element,
+			                                              CloudControllerConstants.BAM_SERVER_ELEMENT);
+			OMElement elt;
+
+			if (childElement != null) {
+				// set bam user name
+				elt =
+				      getFirstChildElement(childElement,
+				                           CloudControllerConstants.BAM_SERVER_ADMIN_USERNAME_ELEMENT);
+				if (elt != null) {
+					dataHolder.setBamUsername(elt.getText());
+				}
+				// set bam password
+				elt =
+				      getFirstChildElement(childElement,
+				                           CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
+				if (elt != null) {
+					String password = resolveSecret(elt);
+					if (password == null) {
+						plainTextWarn(CloudControllerConstants.BAM_SERVER_ADMIN_PASSWORD_ELEMENT);
+						password = elt.getText();
+					}
+
+					if (password != null) {
+						dataHolder.setBamPassword(password);
+					}
+				}
+			}
+
+			// set cron
+			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
+			if (childElement != null) {
+				dataHolder.setDataPublisherCron(childElement.getText());
+			}
+
+			// set cassandra info
+			childElement = getFirstChildElement(element, CloudControllerConstants.CASSANDRA_INFO_ELEMENT);
+
+			if (childElement != null) {
+				// set connection url
+				elt = getFirstChildElement(childElement, CloudControllerConstants.CONNECTION_URL_ELEMENT);
+				if (elt != null) {
+					dataHolder.setCassandraConnUrl(elt.getText());
+				}
+
+				// set user name
+				elt = getFirstChildElement(childElement, CloudControllerConstants.USER_NAME_ELEMENT);
+				if (elt != null) {
+					dataHolder.setCassandraUser(elt.getText());
+				}
+				// set password
+				elt = getFirstChildElement(childElement, CloudControllerConstants.PASSWORD_ELEMENT);
+				if (elt != null) {
+					String password = resolveSecret(elt);
+					if (password == null) {
+						plainTextWarn(CloudControllerConstants.PASSWORD_ELEMENT);
+						password = elt.getText();
+					}
+
+					if (password != null) {
+						dataHolder.setCassandraPassword(password);
+					}
+				}
+			}
+
+		}
+
+	}
+
+	/**
+     * @param cartridgeElement Cartridges section as a {@link String}
+     * @param aCartridge {@link Cartridge} instance.
+     * @param deploymentNodes list of deployment directory nodes
+     */
+    private void setDeploymentDirs(String cartridgeElementString, Cartridge aCartridge,
+                                   List<?> deploymentNodes) {
+	    Object nodeObj;
+	    if ((nodeObj = deploymentNodes.get(0)) instanceof OMNode) {
+	    	OMNode deploymentNode = (OMNode) nodeObj;
+
+	    	if (deploymentNode.getType() == OMNode.ELEMENT_NODE) {
+
+	    		OMElement deployElt = (OMElement) deploymentNode;
+
+	    		if (deployElt.getAttributeValue(new QName(
+	    		                                          CloudControllerConstants.BASE_DIR_ATTR)) != null) {
+
+	    			aCartridge.setBaseDir(deployElt.getAttributeValue(new QName(
+	    			                                                            CloudControllerConstants.BASE_DIR_ATTR)));
+	    		}
+
+	    		for (Iterator<?> iterator =
+	    		                            deployElt.getChildrenWithName(new QName(
+	    		                                                                    CloudControllerConstants.DIRECTORY_ELEMENT)); iterator.hasNext();) {
+	    			OMElement dir = (OMElement) iterator.next();
+	    			aCartridge.addDeploymentDir(dir.getText());
+	    		}
+
+	    	} else {
+	    		String msg =
+	    		             "Essential '" + CloudControllerConstants.DEPLOYMENT_ELEMENT +
+	    		                     "' element cannot" + " be found in " +
+	    		                     cartridgeElementString + " of " + xmlSource;
+	    		handleException(msg);
+	    	}
+
+	    }
+    }
+
+	public void setIaasProvidersList() {
+
+		List<IaasProvider> iaasProviders = FasterLookUpDataHolder.getInstance().getIaasProviders();
+
+		if (iaasProviders == null) {
+			FasterLookUpDataHolder.getInstance()
+			                      .setIaasProviders((iaasProviders = new ArrayList<IaasProvider>()));
+		}
+
+		List<OMNode> nodeList = getMatchingNodes(CloudControllerConstants.IAAS_PROVIDER_XPATH);
+
+		// this is a valid scenario. User can have 0..1 iaas provider elements
+		// in cloud-controller xml.
+		if (nodeList == null || nodeList.isEmpty()) {
+			return;
+		}
+
+		for (OMNode node : nodeList) {
+			iaasProviders.add(getIaasProvider(node, iaasProviders));
+		}
+
+	}
+
+
+	public void setTopologySyncRelatedData() {
+
+		String eltStr = CloudControllerConstants.TOPOLOGY_SYNC_ELEMENT;
+		// get topologySync element
+		OMElement element =
+		                    getElement(documentElement, eltStr,
+		                               CloudControllerConstants.TOPOLOGY_SYNC_XPATH);
+
+		if (element == null) {
+			return;
+		}
+
+		// get enable attribute
+		boolean isEnable =
+		                   Boolean.parseBoolean(element.getAttributeValue(new QName(
+		                                                                            CloudControllerConstants.ENABLE_ATTR)));
+
+		FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+		dataHolder.setEnableTopologySync(isEnable);
+
+		if (isEnable) {
+			// get MB server info
+			OMElement childElement =
+			                         getFirstChildElement(element,
+			                                              CloudControllerConstants.MB_SERVER_ELEMENT);
+
+			if (childElement != null) {
+				// set MB server IP
+				dataHolder.setMBServerUrl(childElement.getText());
+			}
+
+			// set cron
+			childElement = getFirstChildElement(element, CloudControllerConstants.CRON_ELEMENT);
+			if (childElement != null) {
+				dataHolder.setTopologySynchronizerCron(childElement.getText());
+			}
+
+		}
+
+	}
+
+	public boolean validate(final File schemaFile) throws Exception {
+		validate(documentElement, schemaFile);
+		return true;
+	}
+
+	public void validate(final OMElement omElement, final File schemaFile) throws Exception {
+
+		Element sourceElement;
+
+		// if the OMElement is created using DOM implementation use it
+		if (omElement instanceof ElementImpl) {
+			sourceElement = (Element) omElement;
+		} else { // else convert from llom to dom
+			sourceElement = getDOMElement(omElement);
+		}
+
+		// Create a SchemaFactory capable of understanding WXS schemas.
+
+		// Load a WXS schema, represented by a Schema instance.
+		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+		Source source = new StreamSource(schemaFile);
+
+		// Create a Validator object, which can be used to validate
+		// an instance document.
+		Schema schema = factory.newSchema(source);
+		Validator validator = schema.newValidator();
+
+		// Validate the DOM tree.
+		validator.validate(new DOMSource(sourceElement));
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
new file mode 100644
index 0000000..43baf76
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/concurrent/ThreadExecutor.java
@@ -0,0 +1,53 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.concurrent;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * This class can be used to create a thread pool, and hand over new jobs to the pool.
+ */
+public class ThreadExecutor {
+    private ExecutorService executor;
+
+    public ThreadExecutor(int poolSize) {
+        executor = Executors.newFixedThreadPool(poolSize);
+    }
+    
+    public void execute(Runnable job){
+        executor.execute(job);
+    }
+    
+    public void executeAll(Runnable[] jobs){
+        for (Runnable job : jobs) {
+            
+            executor.execute(job);
+        }
+    }
+    
+    public void shutdown() {
+        // This will make the executor accept no new threads
+        // and finish all existing threads in the queue
+        executor.shutdown();
+        // Wait until all threads are finished
+        while (!executor.isTerminated()) {}
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
new file mode 100644
index 0000000..46f5261
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/consumers/TopologyBuilder.java
@@ -0,0 +1,189 @@
+package org.wso2.carbon.stratos.cloud.controller.consumers;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+
+/**
+ * This class is responsible for generating the service topology and
+ * publishing it to a topic.
+ */
+public class TopologyBuilder implements Runnable {
+
+    private BlockingQueue<List<ServiceContext>> sharedQueue;
+	private static File topologyFile, backup;
+	private static final Log log = LogFactory.getLog(TopologyBuilder.class);
+	private static DeclarativeServiceReferenceHolder data = DeclarativeServiceReferenceHolder.getInstance();
+	
+	public TopologyBuilder(BlockingQueue<List<ServiceContext>> queue){
+		
+		sharedQueue = queue;
+		topologyFile = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH);
+		backup = new File(CloudControllerConstants.TOPOLOGY_FILE_PATH+".back");
+		
+	}
+	
+	@Override
+	public void run() {
+
+		while(true){
+            try {
+            	Object obj = sharedQueue.take();
+            	boolean isAdded = false;
+            	
+            	if(obj instanceof List<?>){
+            		@SuppressWarnings("unchecked")
+                    List<ServiceContext> ctxts = (List<ServiceContext>) obj;
+            		
+            		for (ServiceContext serviceContext : ctxts) {
+
+            			Node newNode = serviceContext.toNode();
+            			
+            			if(!topologyFile.exists()){
+            				FileUtils.writeStringToFile(topologyFile, "services {\n}");
+            			}
+            			
+            			String currentContent = FileUtils.readFileToString(topologyFile);
+            			Node currentNode = NodeBuilder.buildNode(currentContent);
+                   			
+            			for (Node aNode : currentNode.getChildNodes()) {
+            				// similar service element is present
+	                        if(aNode.getName().equals(newNode.getName())){
+	                        	// hence, we should not override, but append
+	                        	Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
+	                        	
+	                        	if(domainsNode == null){
+	                        		// existing node is useless
+	                        		currentNode.removeChildNode(aNode.getName());
+	                        		currentNode.appendChild(newNode);
+	                        		break;
+	                        	}
+	                        	
+	                        	// append the new node/s
+	                        	for (Node serNode : newNode.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
+	                                
+	                        		for (Node currentSerNode : domainsNode.getChildNodes()) {
+	                                    String prop = Constants.SUB_DOMAIN_ELEMENT;
+	                        			if(serNode.getName().equals(currentSerNode.getName()) &&
+	                        					serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
+	                        				// if domain and sub domain, are not unique, we shouldn't append, but override
+	                        				domainsNode.removeChildNode(currentSerNode.getName());
+	                        				break;
+	                        			}
+                                    }
+	                        		
+	                        		domainsNode.appendChild(serNode);
+                                }
+	                        	isAdded = true;
+	                        	break;
+	                        }
+                        }
+            			
+						if (!isAdded) {
+							currentNode.appendChild(newNode);
+						}
+						
+            			if (topologyFile.exists()) {
+            				backup.delete();
+            				topologyFile.renameTo(backup);
+            			}
+            			
+            			// overwrite the topology file
+            			FileUtils.writeStringToFile(topologyFile, currentNode.toString());
+            			
+            			// publish to the topic - to sync immediately
+            	        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
+
+                    }
+            	}
+                
+            } catch (InterruptedException ignore) {
+            } catch (IOException e) {
+            	log.error(e.getMessage(), e);
+            	throw new CloudControllerException(e.getMessage(), e);
+            }
+        }
+
+	}
+	
+	public static void removeTopologyAndPublish(ServiceContext serviceContext){
+	    
+	    Node currentNodeToBeRemoved = null;
+	    Node nodeToBeRemoved = serviceContext.toNode();
+        
+        if(!topologyFile.exists()){
+            return;
+        }
+        try{
+        String currentContent = FileUtils.readFileToString(topologyFile);
+        Node currentNode = NodeBuilder.buildNode(currentContent);
+            
+        for (Node aNode : currentNode.getChildNodes()) {
+            // similar service element is present
+            if(aNode.getName().equals(nodeToBeRemoved.getName())){
+                // let's check whether the domain node exists
+                
+                Node domainsNode = aNode.findChildNodeByName(Constants.DOMAIN_ELEMENT);
+                
+                if(domainsNode == null){
+                    continue;
+                }
+                
+                for (Node serNode : nodeToBeRemoved.findChildNodeByName(Constants.DOMAIN_ELEMENT).getChildNodes()) {
+                    
+                    for (Node currentSerNode : domainsNode.getChildNodes()) {
+                        String prop = Constants.SUB_DOMAIN_ELEMENT;
+                        if(serNode.getName().equals(currentSerNode.getName()) &&
+                                serNode.getProperty(prop).equals(currentSerNode.getProperty(prop))){
+                            // if domain and sub domain, are matching, we should remove the node.
+                            domainsNode.removeChildNode(currentSerNode.getName());
+                            if(domainsNode.getChildNodes().size() == 0){
+                                // if no cluster definitions remain, we shouldn't keep the node
+                                currentNodeToBeRemoved = aNode;
+                            }
+                            break;
+                        }
+                    }
+                    
+                }
+                
+            }
+        }
+        
+        if(currentNodeToBeRemoved != null){
+            // remove the node with empty clusters
+            currentNode.removeChildNode(currentNodeToBeRemoved);
+        }
+        
+        if (topologyFile.exists()) {
+            backup.delete();
+            topologyFile.renameTo(backup);
+        }
+        
+        // overwrite the topology file
+        FileUtils.writeStringToFile(topologyFile, currentNode.toString());
+        
+        // publish to the topic - to sync immediately
+        data.getConfigPub().publish(CloudControllerConstants.TOPIC_NAME, currentNode.toString());
+        
+        } catch (IOException e) {
+            log.error(e.getMessage(), e);
+            throw new CloudControllerException(e.getMessage(), e);
+        }
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
new file mode 100644
index 0000000..9881e5f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CartridgeDeployer.java
@@ -0,0 +1,194 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.deployers;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.wso2.carbon.stratos.cloud.controller.concurrent.ThreadExecutor;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * All the {@link Cartridge}s will get deployed / undeployed / updated via this class. 
+ */
+public class CartridgeDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(CartridgeDeployer.class);
+    
+    private FasterLookUpDataHolder serviceContextLookUpStructure;
+    private Map<String, List<Cartridge>> fileToCartridgeListMap;
+    private File cartridgesSchema, cartridgeSchema;
+
+    public void init(ConfigurationContext arg0) {
+        fileToCartridgeListMap = new ConcurrentHashMap<String, List<Cartridge>>();
+        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
+        cartridgesSchema = new File(etcDir+"cartridges.xsd");
+        cartridgeSchema = new File(etcDir+"cartridge.xsd");
+    }
+
+    public void setDirectory(String arg0) {
+        // component xml handles this
+    }
+
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
+        
+        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+        parser.parse();
+
+        try {
+        	// validate
+            validateCartridge(parser);
+            
+			// deploy - grab cartridges
+			List<Cartridge> cartridges = parser.getCartridgesList();
+
+			ThreadExecutor exec = new ThreadExecutor(3);
+			// create Jclouds objects, for each IaaS
+			for (Cartridge cartridge : cartridges) {
+				// jclouds object building is time consuming, hence I use Java executor framework
+				exec.execute(new JcloudsObjectBuilder(cartridge, deploymentFileData));
+			}
+			exec.shutdown();
+			// update map
+			fileToCartridgeListMap.put(deploymentFileData.getAbsolutePath(),
+			                           new ArrayList<Cartridge>(cartridges));
+
+			log.info("Successfully deployed the Cartridge definition specified at "+deploymentFileData.getAbsolutePath());
+			
+		} catch (Exception e) {
+			String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
+            // back up the file
+            File f = deploymentFileData.getFile();
+            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
+            log.error(msg, e);
+            throw new DeploymentException(msg, e);
+		} 
+        
+        
+    }
+    
+    private void validateCartridge(AxiomXpathParser parser) throws Exception {
+        boolean validated = false;
+        Exception firstException = null;
+
+        try{
+            // first try to validate using cartridges schema
+            parser.validate(cartridgesSchema);
+            validated = true;
+            
+        }catch (Exception e) {
+            firstException = e;
+        }
+        
+        if(!validated){
+            try{
+                // Now try to validate using cartridge schema
+                parser.validate(cartridgeSchema);
+                validated = true;
+                log.debug("Cartridge validation was successful.");
+                
+            }catch (Exception e) {
+                String msg = "Cartridge XML validation failed. Invalid Cartridge XML: "+parser.getXmlSource().getAbsolutePath();
+                log.error(msg, firstException);
+                throw firstException;
+            }
+        }
+        
+        
+    }
+
+    public void undeploy(String file) throws DeploymentException {
+        
+    	serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+    	
+        // grab the entry from Map
+        if(fileToCartridgeListMap.containsKey(file)){
+            // remove 'em
+            serviceContextLookUpStructure.removeCartridges(fileToCartridgeListMap.get(file));
+            
+            log.info("Successfully undeployed the Cartridge definition specified at "+file);
+        }
+        
+    }
+    
+    private void handleException(String msg, Exception e) {
+        log.fatal(msg, e);
+        throw new CloudControllerException(msg, e);
+    }
+    
+    /**
+     * JcloudsObjectBuilder job
+     *
+     */
+    class JcloudsObjectBuilder implements Runnable{
+    	
+    	private Cartridge cartridge;
+    	private DeploymentFileData file;
+
+    	public JcloudsObjectBuilder (Cartridge cartridge, DeploymentFileData file){
+    		this.cartridge = cartridge;
+    		this.file = file;
+    	}
+    	
+		@Override
+        public void run() {
+
+			for (IaasProvider iaasProvider : cartridge.getIaases()) {
+				try {
+					Iaas iaas = (Iaas) Class.forName(iaasProvider.getClassName()).newInstance();
+					iaas.buildComputeServiceAndTemplate(iaasProvider);
+					iaasProvider.setIaas(iaas);
+					
+				} catch (Exception e) {
+					rename();
+					handleException(e.getMessage(), e);
+				}
+			}
+			
+        }
+		
+		private void rename(){
+			// back up the file
+            File f = file.getFile();
+            f.renameTo(new File(file.getAbsolutePath()+".back"));
+		}
+    	
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
new file mode 100644
index 0000000..1f9dafc
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/CloudControllerDeployer.java
@@ -0,0 +1,110 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.deployers;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+
+/**
+ * All the {@link IaasProvider}s will get deployed / undeployed / updated via this class. 
+ */
+public class CloudControllerDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(CloudControllerDeployer.class);
+    private static final String FILE_NAME = "cloud-controller";
+    private Map<String, List<IaasProvider>> fileToIaasProviderListMap;
+
+    @Override
+    public void init(ConfigurationContext arg0) {
+    	fileToIaasProviderListMap = new ConcurrentHashMap<String, List<IaasProvider>>();
+    }
+
+    @Override
+    public void setDirectory(String arg0) {
+        // component xml handles this
+        
+    }
+
+    @Override
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artifact: "+deploymentFileData.getFile());
+        
+        // since cloud-controller.xml resides in repository/conf
+		if (deploymentFileData.getName().contains(FILE_NAME)) {
+
+			AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+
+			// parse the file
+			parser.parse();
+
+			// deploy iaases
+			parser.setIaasProvidersList();
+			parser.setDataPublisherRelatedData();
+			parser.setTopologySyncRelatedData();
+
+			// update map
+			fileToIaasProviderListMap.put(deploymentFileData.getAbsolutePath(),
+			                              new ArrayList<IaasProvider>(
+			                                                          FasterLookUpDataHolder.getInstance()
+			                                                                                .getIaasProviders()));
+
+			log.info("Successfully deployed the cloud-controller XML file specified at " +
+			         deploymentFileData.getAbsolutePath());
+		}
+        
+    }
+    
+
+    public void undeploy(String file) throws DeploymentException {
+        
+        if (file.contains(FILE_NAME)) {
+            // reset
+            FasterLookUpDataHolder.getInstance().setSerializationDir("");
+            
+            // grab the entry from Map
+            if(fileToIaasProviderListMap.containsKey(file)){
+                // remove 'em
+                FasterLookUpDataHolder.getInstance().getIaasProviders().removeAll(fileToIaasProviderListMap.get(file));
+                
+                log.info("Successfully undeployed the cloud-controller XML file specified at "+file);
+            }
+            // only one cloud-controller file, hence delete 'em all
+//            FasterLookUpDataHolder.getInstance().setIaasProviders(new ArrayList<IaasProvider>());
+            
+        }
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
new file mode 100644
index 0000000..a66bf8a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/deployers/ServiceDeployer.java
@@ -0,0 +1,153 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.deployers;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.deployment.AbstractDeployer;
+import org.apache.axis2.deployment.DeploymentException;
+import org.apache.axis2.deployment.repository.util.DeploymentFileData;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.wso2.carbon.stratos.cloud.controller.consumers.TopologyBuilder;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * All the {@link Cartridge}s will get deployed / undeployed / updated via this class. 
+ */
+public class ServiceDeployer extends AbstractDeployer{
+    
+    private static final Log log = LogFactory.getLog(ServiceDeployer.class);
+    
+    private FasterLookUpDataHolder serviceContextLookUpStructure;
+    private Map<String, List<ServiceContext>> fileToServiceContextListMap;
+    private File servicesSchema, serviceSchema;
+
+    @Override
+    public void init(ConfigurationContext arg0) {
+        fileToServiceContextListMap = new ConcurrentHashMap<String, List<ServiceContext>>();
+        String etcDir = CarbonUtils.getCarbonConfigDirPath() + File.separator + "etc" + File.separator;
+        servicesSchema = new File(etcDir+"services.xsd");
+        serviceSchema = new File(etcDir+"service.xsd");
+    }
+
+    @Override
+    public void setDirectory(String arg0) {
+        // component xml handles this
+    }
+
+    @Override
+    public void setExtension(String arg0) {
+        // component xml handles this
+    }
+    
+    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
+        
+        log.debug("Started to deploy the deployment artefact: "+deploymentFileData.getFile());
+        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+        
+        AxiomXpathParser parser = new AxiomXpathParser(deploymentFileData.getFile());
+        parser.parse();
+        
+        // validate
+        try {
+            validateService(parser);
+            
+        } catch (Exception e) {
+            String msg = "Invalid deployment artefact at "+deploymentFileData.getAbsolutePath();
+            // back up the file
+            File f = deploymentFileData.getFile();
+            f.renameTo(new File(deploymentFileData.getAbsolutePath()+".back"));
+            log.error(msg, e);
+            throw new DeploymentException(msg, e);
+        }
+        
+        // deploy
+        List<ServiceContext> services = parser.getServiceContexts();
+        
+        // notify consumer by adding the diff
+        try {
+	        serviceContextLookUpStructure.getSharedTopologyDiffQueue().put(services);
+        } catch (InterruptedException ignore) {
+        }
+        
+        // update map
+        fileToServiceContextListMap.put(deploymentFileData.getAbsolutePath(), new ArrayList<ServiceContext>(services));
+        
+        log.info("Successfully deployed the Service definition specified at "+deploymentFileData.getAbsolutePath());
+    }
+    
+    private void validateService(AxiomXpathParser parser) throws Exception {
+        boolean validated = false;
+        Exception firstException = null;
+
+        try{
+            // first try to validate using services schema
+            parser.validate(servicesSchema);
+            validated = true;
+            log.debug("Service validation was successful.");
+            
+        }catch (Exception e) {
+            firstException = e;
+        }
+        
+        if(!validated){
+            try{
+                // Now try to validate using service schema
+                parser.validate(serviceSchema);
+                validated = true;
+                log.debug("Service validation was successful.");
+                
+            }catch (Exception e) {
+                String msg = "Service XML validation failed. Invalid Service XML: "+parser.getXmlSource().getAbsolutePath();
+                log.error(msg, firstException);
+                throw firstException;
+            }
+        }
+        
+        
+    }
+
+    public void undeploy(String file) throws DeploymentException {
+
+        serviceContextLookUpStructure = FasterLookUpDataHolder.getInstance();
+
+        // grab the entry from Map
+        if(fileToServiceContextListMap.containsKey(file)){
+            // remove 'em all
+            for (ServiceContext ctxt : fileToServiceContextListMap.get(file)) {
+                serviceContextLookUpStructure.removeServiceContext(ctxt);
+                // remove from the topology
+                TopologyBuilder.removeTopologyAndPublish(ctxt);
+            }
+            
+            log.info("Successfully undeployed the Service definition specified at "+file);
+        }
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
new file mode 100644
index 0000000..f911de5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/CloudControllerException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class CloudControllerException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public CloudControllerException(String msg) {
+        super(msg);
+    }
+    
+    public CloudControllerException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
new file mode 100644
index 0000000..3b0ae7d
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/DeserializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class DeserializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -2426068347954381831L;
+
+    public DeserializationException(String msg) {
+        super(msg);
+    }
+    
+    public DeserializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
new file mode 100644
index 0000000..aa93b15
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidCartridgeDefinitionException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class InvalidCartridgeDefinitionException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public InvalidCartridgeDefinitionException(String msg) {
+        super(msg);
+    }
+    
+    public InvalidCartridgeDefinitionException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
new file mode 100644
index 0000000..fd14187
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/InvalidXMLException.java
@@ -0,0 +1,36 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class InvalidXMLException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public InvalidXMLException(String msg) {
+        super(msg);
+    }
+    
+    public InvalidXMLException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+    
+    public InvalidXMLException(Exception ex) {
+        super(ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
new file mode 100644
index 0000000..8b9240f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/MalformedConfigurationFileException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class MalformedConfigurationFileException extends RuntimeException {
+
+    private static final long serialVersionUID = -1662095377704279326L;
+    
+    public MalformedConfigurationFileException(String msg) {
+        super(msg);
+    }
+    
+    public MalformedConfigurationFileException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
new file mode 100644
index 0000000..ba8cb65
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/NoInstanceFoundException.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+/**
+ * This will throw when no instance is found
+ */
+public class NoInstanceFoundException extends Exception {
+
+    /**
+     * For serializing requirement
+     */
+    private static final long serialVersionUID = -435060299292679892L;
+
+
+    public NoInstanceFoundException(String msg) {
+        super(msg);
+    }
+    
+    public NoInstanceFoundException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
new file mode 100644
index 0000000..fd40f0a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/SerializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class SerializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -3701458642228072331L;
+
+    public SerializationException(String msg) {
+        super(msg);
+    }
+    
+    public SerializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}


[19/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateClusterDomainMessage.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateClusterDomainMessage.java
new file mode 100644
index 0000000..5d15952
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateClusterDomainMessage.java
@@ -0,0 +1,128 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.messages;
+
+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;
+
+/**
+ * TODO: class description
+ */
+public class CreateClusterDomainMessage extends ClusteringMessage {
+    private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
+    public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
+    private String service;
+    private String clusterDomain;
+    private String hostName;
+    //private int tenantId;
+    private String tenantRange;
+    private int minInstances;
+    private int maxInstances;
+	private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+    
+
+    public CreateClusterDomainMessage(String service, String clusterDomain,
+                                      String hostName, String tenantRange,
+                                      int minInstances, int maxInstances,
+                                      int maxRequestsPerSecond, int roundsToAverage,
+                                      double alarmingUpperRate, double alarmingLowerRate,
+                                      double scaleDownFactor) {
+        this.service = service;
+        this.clusterDomain = clusterDomain;
+        this.hostName = hostName;
+        this.tenantRange = tenantRange;
+        this.minInstances = minInstances;
+        this.maxInstances = maxInstances;
+        this.maxRequestsPerSecond = maxRequestsPerSecond;
+        this.roundsToAverage = roundsToAverage;
+        this.alarmingUpperRate = alarmingUpperRate;
+        this.alarmingLowerRate = alarmingLowerRate;
+        this.scaleDownFactor = scaleDownFactor;
+    }
+
+    @Override
+    public ClusteringCommand getResponse() {
+        return new ClusteringCommand() {
+            @Override
+            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+                log.info("Received response to CreateClusterDomainMessage");
+            }
+        };
+    }
+
+    @Override
+    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
+        log.info("Received ***" + this);
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException ignored) {
+                }
+                ClusterDomainManager clusterDomainManager =
+                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
+                if (clusterDomainManager != null) {
+                    clusterDomainManager.addClusterDomain(createClusterDomain());
+                } else {
+                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
+                }
+            }
+
+			private ClusterDomain createClusterDomain() {
+				
+				ClusterDomain clusterDomainObj = new ClusterDomain();
+				clusterDomainObj.setDomain(clusterDomain);
+				clusterDomainObj.setHostName(hostName);
+				clusterDomainObj.setMaxInstances(maxInstances);
+				clusterDomainObj.setMinInstances(minInstances);
+				clusterDomainObj.setSubDomain(null); // TODO subdomain
+				clusterDomainObj.setTenantRange(tenantRange);
+				clusterDomainObj.setServiceName(service);
+				clusterDomainObj.setMaxRequestsPerSecond(maxRequestsPerSecond);
+				clusterDomainObj.setRoundsToAverage(roundsToAverage);
+				clusterDomainObj.setAlarmingUpperRate(alarmingUpperRate);
+				clusterDomainObj.setAlarmingLowerRate(alarmingLowerRate);
+				clusterDomainObj.setScaleDownFactor(scaleDownFactor);
+				
+				if(log.isDebugEnabled())
+					log.debug("Cluster Domain is created with minInstances:" + minInstances + ", maxInstances: " + maxInstances);
+				
+				return clusterDomainObj;
+			}
+        };
+        new Thread(runnable).start();
+    }
+
+    @Override
+    public String toString() {
+        return "CreateClusterDomainMessage{" +
+               "service='" + service + '\'' +
+               ", clusterDomain='" + clusterDomain + '\'' +
+               ", hostName='" + hostName + '\'' +
+               ", tenantId=" + tenantRange +
+               '}';
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateRemoveClusterDomainMessage.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateRemoveClusterDomainMessage.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateRemoveClusterDomainMessage.java
new file mode 100644
index 0000000..529ec98
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/CreateRemoveClusterDomainMessage.java
@@ -0,0 +1,59 @@
+package org.wso2.carbon.cartridge.messages;
+
+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;
+
+public class CreateRemoveClusterDomainMessage extends ClusteringMessage{
+	
+	private static final Log log = LogFactory.getLog(CreateClusterDomainMessage.class);
+	public static final String CLUSTER_DOMAIN_MANAGER = "cluster.domain.manager";
+	private String domain;
+	private String subDomain;
+	private String hostName;
+	
+	
+	
+	public CreateRemoveClusterDomainMessage(String domain, String subDomain, String hostName) {
+	    this.domain = domain;
+	    this.subDomain = subDomain;
+	    this.hostName = hostName;
+    }
+
+	@Override
+    public ClusteringCommand getResponse() {
+		return new ClusteringCommand() {
+            @Override
+            public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
+                log.info("Received response to CreateRemoveClusterDomainMessage");
+            }
+        };
+    }
+
+	@Override
+    public void execute(final ConfigurationContext configurationContext) throws ClusteringFault {
+	    
+		log.info("Received ***" + this);
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(2000);
+                } catch (InterruptedException ignored) {
+                }
+                ClusterDomainManager clusterDomainManager =
+                        (ClusterDomainManager) configurationContext.getProperty(CLUSTER_DOMAIN_MANAGER);
+                log.info(" ***** Received clusterDomain Manager ** " + clusterDomainManager);
+                if (clusterDomainManager != null) {
+                    clusterDomainManager.removeClusterDomain(domain, subDomain, hostName);
+                } else {
+                    log.warn(CLUSTER_DOMAIN_MANAGER + " has not been defined in ConfigurationContext");
+                }
+            }
+        };
+        new Thread(runnable).start();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/pom.xml b/components/stratos/cartridge-agent/pom.xml
new file mode 100644
index 0000000..996debf
--- /dev/null
+++ b/components/stratos/cartridge-agent/pom.xml
@@ -0,0 +1,121 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>cartridge-agent-parent</artifactId>
+    <packaging>pom</packaging>
+    <name>WSO2 Cartridge Agent - Parent</name>
+    <description>WSO2 Cartridge Agent</description>
+
+    <licenses>
+        <license>
+            <name>Apache License Version 2.0</name>
+            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
+        </license>
+    </licenses>
+
+    <modules>
+        <module>org.wso2.carbon.cartridge.agent/2.1.1</module>
+        <module>org.wso2.carbon.cartridge.messages/2.1.1</module>
+    </modules>
+
+    <!--<dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+                <artifactId>axiom</artifactId>
+                <version>1.2.11.wso2v2</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.axis2.wso2</groupId>
+                <artifactId>axis2</artifactId>
+                <version>1.6.1.wso2v6</version>
+            </dependency>
+            <dependency>
+                <groupId>commons-logging</groupId>
+                <artifactId>commons-logging</artifactId>
+                <version>1.1.1</version>
+            </dependency>
+            <dependency>
+                <groupId>commons-httpclient</groupId>
+                <artifactId>commons-httpclient</artifactId>
+                <version>3.0.1</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.httpcomponents</groupId>
+                <artifactId>httpcore</artifactId>
+                <version>4.1.3</version>
+            </dependency>
+            <dependency>
+                <groupId>log4j</groupId>
+                <artifactId>log4j</artifactId>
+                <version>1.2.16</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.neethi.wso2</groupId>
+                <artifactId>neethi</artifactId>
+                <version>2.0.4.wso2v4</version>
+            </dependency>
+            <dependency>
+                <groupId>org.wso2.securevault</groupId>
+                <artifactId>org.wso2.securevault</artifactId>
+                <version>1.0.0</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.tomcat.wso2</groupId>
+                <artifactId>tribes</artifactId>
+                <version>7.0.28.wso2v1</version>
+            </dependency>
+            <dependency>
+                <groupId>wsdl4j.wso2</groupId>
+                <artifactId>wsdl4j</artifactId>
+                <version>1.6.2.wso2v4</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.ws.commons.schema.wso2</groupId>
+                <artifactId>XmlSchema</artifactId>
+                <version>1.4.7.wso2v2</version>
+            </dependency>
+            <dependency>
+                <groupId>org.wso2.carbon</groupId>
+                <artifactId>org.wso2.carbon.hosting.instanceinfo.mgt.stub</artifactId>
+                <version>1.0.0</version>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>-->
+
+    <organization>
+        <name>WSO2 Inc</name>
+        <url>http://wso2.com</url>
+    </organization>
+
+    <issueManagement>
+        <system>JIRA</system>
+        <url>https://wso2.org/jira/browse/CARBON</url>
+    </issueManagement>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/pom.xml b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..9a4b73e
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/pom.xml
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>domain-validator-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.validate.domain.ui</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Validate Domains - User Interface</name>
+
+    <build>
+
+        <plugins>
+
+            <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.wso2.carbon.validate.domain.ui.*,
+                        </Export-Package>
+                        <Import-Package>
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.lucene.*,
+                            org.wso2.carbon.validate.domain.stub.*; version="${carbon.platform.package.import.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Carbon-Component>UIBundle</Carbon-Component>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.equinox</groupId>
+            <artifactId>javax.servlet</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+            <artifactId>axiom</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.validate.domain.stub</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainAdminClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainAdminClient.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainAdminClient.java
new file mode 100644
index 0000000..9d0d34e
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainAdminClient.java
@@ -0,0 +1,117 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.validate.domain.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.validate.domain.stub.services.ValidateDomainAdminServiceStub;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class ValidateDomainAdminClient implements ValidateDomainClient {
+    private static final Log log = LogFactory.getLog(ValidateDomainAdminClient.class);
+
+    private ValidateDomainAdminServiceStub stub;
+    private String epr;
+
+    public ValidateDomainAdminClient(String cookie, String backendServerURL,
+            ConfigurationContext configContext) throws RegistryException {
+
+        epr = backendServerURL + "ValidateDomainAdminService";
+
+        try {
+            stub = new ValidateDomainAdminServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg =
+                    "Failed to initiate Validate Domain service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public ValidateDomainAdminClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+    	
+    	String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext =
+                (ConfigurationContext) config.getServletContext().getAttribute(
+                        CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "ValidateDomainAdminService";
+        
+        try {
+            stub = new ValidateDomainAdminServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg =
+                    "Failed to initiate Add Services service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public String getDomainValidationKey(String domain) throws RegistryException {
+        try {
+            return stub.getDomainValidationKey(domain);
+        } catch (Exception e) {
+            String msg = "Failed to get domain validation keys. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public String validateByDNSEntry(String domain) throws RegistryException {
+        try {
+            return stub.validateByDNSEntry(domain);
+        } catch (Exception e) {
+            String msg = "Failed to validate by dns entry. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public String validateByTextInRoot(String domain) throws RegistryException {
+        try {
+            return stub.validateByTextInRoot(domain);
+        } catch (Exception e) {
+            String msg = "Failed to validate by dns entry. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainClient.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainClient.java
new file mode 100644
index 0000000..8a81d17
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainClient.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.validate.domain.ui.clients;
+
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+
+public interface ValidateDomainClient {
+    public String getDomainValidationKey(String domain) throws RegistryException;
+
+    public String validateByDNSEntry(String domain) throws RegistryException;
+
+    public String validateByTextInRoot(String domain) throws RegistryException;
+   
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainNonAdminClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainNonAdminClient.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainNonAdminClient.java
new file mode 100644
index 0000000..520fdc6
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/clients/ValidateDomainNonAdminClient.java
@@ -0,0 +1,115 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.validate.domain.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.validate.domain.stub.services.ValidateDomainServiceStub;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class ValidateDomainNonAdminClient implements ValidateDomainClient {
+     private static final Log log = LogFactory.getLog(ValidateDomainNonAdminClient.class);
+
+    private ValidateDomainServiceStub stub;
+    private String epr;
+
+    public ValidateDomainNonAdminClient(
+            String cookie, String backendServerURL, ConfigurationContext configContext)
+            throws RegistryException {
+
+        epr = backendServerURL + "ValidateDomainService";
+
+        try {
+            stub = new ValidateDomainServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate AddServices service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public ValidateDomainNonAdminClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+
+        String cookie = (String)session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "ValidateDomainService";
+
+        try {
+            stub = new ValidateDomainServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate Add Services service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public String getDomainValidationKey(String domain) throws RegistryException {
+        try {
+            return stub.getDomainValidationKey(domain);
+        } catch (Exception e) {
+            String msg = "Failed to get domain validation keys. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public String validateByDNSEntry(String domain) throws RegistryException {
+        try {
+            return stub.validateByDNSEntry(domain);    
+        } catch (Exception e) {
+            String msg = "Failed to validate by dns entry. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    public String validateByTextInRoot(String domain) throws RegistryException {
+        try {
+            return stub.validateByTextInRoot(domain);   
+        } catch (Exception e) {
+            String msg = "Failed to validate by dns entry. " + e.getMessage();
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/utils/Util.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/utils/Util.java
new file mode 100644
index 0000000..b3f27eb
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/java/org/wso2/carbon/validate/domain/ui/utils/Util.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.validate.domain.ui.utils;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.validate.domain.ui.clients.ValidateDomainAdminClient;
+import org.wso2.carbon.validate.domain.ui.clients.ValidateDomainClient;
+import org.wso2.carbon.validate.domain.ui.clients.ValidateDomainNonAdminClient;
+
+public class Util {
+    public static ValidateDomainClient getValidateDomainClient(ServletRequest request,
+            ServletConfig config, HttpSession session) throws RegistryException {
+        // this doesn't make any security hole, as even a not-logged-in user try
+        // manually put status parameter to logged_in, still the back-end service
+        // try to validate him and he will fail.
+        
+        String status = request.getParameter("status");
+        if ("logged_in".equals(status)) {
+            return new ValidateDomainAdminClient(config, session);
+        }
+        return new ValidateDomainNonAdminClient(config, session);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..7d459e4
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,21 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+
+
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainAdminService.wsdl
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainAdminService.wsdl b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainAdminService.wsdl
new file mode 100644
index 0000000..0e16976
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainAdminService.wsdl
@@ -0,0 +1,238 @@
+<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://services.domain.validate.carbon.wso2.org" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://services.domain.validate.carbon.wso2.org">
+    <wsdl:documentation>ValidateDomainAdminService</wsdl:documentation>
+    <wsdl:types>
+        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://services.domain.validate.carbon.wso2.org">
+            <xs:element name="validateByTextInRootException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="validateByTextInRootException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:complexType name="Exception">
+                <xs:sequence>
+                    <xs:element minOccurs="0" name="Message" nillable="true" type="xs:string" />
+                </xs:sequence>
+            </xs:complexType>
+            <xs:element name="validateByTextInRoot">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByTextInRootResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntryException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="validateByDNSEntryException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntry">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntryResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKeyException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="getDomainValidationKeyException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKey">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKeyResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+        </xs:schema>
+    </wsdl:types>
+    <wsdl:message name="validateByTextInRootRequest">
+        <wsdl:part name="parameters" element="ns:validateByTextInRoot" />
+    </wsdl:message>
+    <wsdl:message name="validateByTextInRootResponse">
+        <wsdl:part name="parameters" element="ns:validateByTextInRootResponse" />
+    </wsdl:message>
+    <wsdl:message name="validateByTextInRootException">
+        <wsdl:part name="parameters" element="ns:validateByTextInRootException" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryRequest">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntry" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryResponse">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntryResponse" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryException">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntryException" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyRequest">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKey" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyResponse">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKeyResponse" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyException">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKeyException" />
+    </wsdl:message>
+    <wsdl:portType name="ValidateDomainAdminServicePortType">
+        <wsdl:operation name="validateByTextInRoot">
+            <wsdl:input message="ns:validateByTextInRootRequest" wsaw:Action="urn:validateByTextInRoot" />
+            <wsdl:output message="ns:validateByTextInRootResponse" wsaw:Action="urn:validateByTextInRootResponse" />
+            <wsdl:fault message="ns:validateByTextInRootException" name="validateByTextInRootException" wsaw:Action="urn:validateByTextInRootvalidateByTextInRootException" />
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <wsdl:input message="ns:validateByDNSEntryRequest" wsaw:Action="urn:validateByDNSEntry" />
+            <wsdl:output message="ns:validateByDNSEntryResponse" wsaw:Action="urn:validateByDNSEntryResponse" />
+            <wsdl:fault message="ns:validateByDNSEntryException" name="validateByDNSEntryException" wsaw:Action="urn:validateByDNSEntryvalidateByDNSEntryException" />
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <wsdl:input message="ns:getDomainValidationKeyRequest" wsaw:Action="urn:getDomainValidationKey" />
+            <wsdl:output message="ns:getDomainValidationKeyResponse" wsaw:Action="urn:getDomainValidationKeyResponse" />
+            <wsdl:fault message="ns:getDomainValidationKeyException" name="getDomainValidationKeyException" wsaw:Action="urn:getDomainValidationKeygetDomainValidationKeyException" />
+        </wsdl:operation>
+    </wsdl:portType>
+    <wsdl:binding name="ValidateDomainAdminServiceSoap11Binding" type="ns:ValidateDomainAdminServicePortType">
+        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="validateByTextInRoot">
+            <soap:operation soapAction="urn:validateByTextInRoot" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByTextInRootException">
+                <soap:fault use="literal" name="validateByTextInRootException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <soap:operation soapAction="urn:validateByDNSEntry" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByDNSEntryException">
+                <soap:fault use="literal" name="validateByDNSEntryException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <soap:operation soapAction="urn:getDomainValidationKey" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getDomainValidationKeyException">
+                <soap:fault use="literal" name="getDomainValidationKeyException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="ValidateDomainAdminServiceSoap12Binding" type="ns:ValidateDomainAdminServicePortType">
+        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="validateByTextInRoot">
+            <soap12:operation soapAction="urn:validateByTextInRoot" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByTextInRootException">
+                <soap12:fault use="literal" name="validateByTextInRootException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <soap12:operation soapAction="urn:validateByDNSEntry" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByDNSEntryException">
+                <soap12:fault use="literal" name="validateByDNSEntryException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <soap12:operation soapAction="urn:getDomainValidationKey" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getDomainValidationKeyException">
+                <soap12:fault use="literal" name="getDomainValidationKeyException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="ValidateDomainAdminServiceHttpBinding" type="ns:ValidateDomainAdminServicePortType">
+        <http:binding verb="POST" />
+        <wsdl:operation name="validateByTextInRoot">
+            <http:operation location="validateByTextInRoot" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <http:operation location="validateByDNSEntry" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <http:operation location="getDomainValidationKey" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:service name="ValidateDomainAdminService">
+        <wsdl:port name="ValidateDomainAdminServiceHttpsSoap11Endpoint" binding="ns:ValidateDomainAdminServiceSoap11Binding">
+            <soap:address location="https://192.168.1.100:9443/services/ValidateDomainAdminService.ValidateDomainAdminServiceHttpsSoap11Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="ValidateDomainAdminServiceHttpsSoap12Endpoint" binding="ns:ValidateDomainAdminServiceSoap12Binding">
+            <soap12:address location="https://192.168.1.100:9443/services/ValidateDomainAdminService.ValidateDomainAdminServiceHttpsSoap12Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="ValidateDomainAdminServiceHttpsEndpoint" binding="ns:ValidateDomainAdminServiceHttpBinding">
+            <http:address location="https://192.168.1.100:9443/services/ValidateDomainAdminService.ValidateDomainAdminServiceHttpsEndpoint/" />
+        </wsdl:port>
+    </wsdl:service>
+</wsdl:definitions>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainService.wsdl
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainService.wsdl b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainService.wsdl
new file mode 100644
index 0000000..c22a6ab
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/ValidateDomainService.wsdl
@@ -0,0 +1,238 @@
+<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://services.domain.validate.carbon.wso2.org" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://services.domain.validate.carbon.wso2.org">
+    <wsdl:documentation>ValidateDomainService</wsdl:documentation>
+    <wsdl:types>
+        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://services.domain.validate.carbon.wso2.org">
+            <xs:element name="validateByTextInRootException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="validateByTextInRootException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:complexType name="Exception">
+                <xs:sequence>
+                    <xs:element minOccurs="0" name="Message" nillable="true" type="xs:string" />
+                </xs:sequence>
+            </xs:complexType>
+            <xs:element name="validateByTextInRoot">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByTextInRootResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntryException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="validateByDNSEntryException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntry">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="validateByDNSEntryResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKeyException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="getDomainValidationKeyException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKey">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getDomainValidationKeyResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+        </xs:schema>
+    </wsdl:types>
+    <wsdl:message name="validateByTextInRootRequest">
+        <wsdl:part name="parameters" element="ns:validateByTextInRoot" />
+    </wsdl:message>
+    <wsdl:message name="validateByTextInRootResponse">
+        <wsdl:part name="parameters" element="ns:validateByTextInRootResponse" />
+    </wsdl:message>
+    <wsdl:message name="validateByTextInRootException">
+        <wsdl:part name="parameters" element="ns:validateByTextInRootException" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryRequest">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntry" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryResponse">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntryResponse" />
+    </wsdl:message>
+    <wsdl:message name="validateByDNSEntryException">
+        <wsdl:part name="parameters" element="ns:validateByDNSEntryException" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyRequest">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKey" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyResponse">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKeyResponse" />
+    </wsdl:message>
+    <wsdl:message name="getDomainValidationKeyException">
+        <wsdl:part name="parameters" element="ns:getDomainValidationKeyException" />
+    </wsdl:message>
+    <wsdl:portType name="ValidateDomainServicePortType">
+        <wsdl:operation name="validateByTextInRoot">
+            <wsdl:input message="ns:validateByTextInRootRequest" wsaw:Action="urn:validateByTextInRoot" />
+            <wsdl:output message="ns:validateByTextInRootResponse" wsaw:Action="urn:validateByTextInRootResponse" />
+            <wsdl:fault message="ns:validateByTextInRootException" name="validateByTextInRootException" wsaw:Action="urn:validateByTextInRootvalidateByTextInRootException" />
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <wsdl:input message="ns:validateByDNSEntryRequest" wsaw:Action="urn:validateByDNSEntry" />
+            <wsdl:output message="ns:validateByDNSEntryResponse" wsaw:Action="urn:validateByDNSEntryResponse" />
+            <wsdl:fault message="ns:validateByDNSEntryException" name="validateByDNSEntryException" wsaw:Action="urn:validateByDNSEntryvalidateByDNSEntryException" />
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <wsdl:input message="ns:getDomainValidationKeyRequest" wsaw:Action="urn:getDomainValidationKey" />
+            <wsdl:output message="ns:getDomainValidationKeyResponse" wsaw:Action="urn:getDomainValidationKeyResponse" />
+            <wsdl:fault message="ns:getDomainValidationKeyException" name="getDomainValidationKeyException" wsaw:Action="urn:getDomainValidationKeygetDomainValidationKeyException" />
+        </wsdl:operation>
+    </wsdl:portType>
+    <wsdl:binding name="ValidateDomainServiceSoap11Binding" type="ns:ValidateDomainServicePortType">
+        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="validateByTextInRoot">
+            <soap:operation soapAction="urn:validateByTextInRoot" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByTextInRootException">
+                <soap:fault use="literal" name="validateByTextInRootException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <soap:operation soapAction="urn:validateByDNSEntry" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByDNSEntryException">
+                <soap:fault use="literal" name="validateByDNSEntryException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <soap:operation soapAction="urn:getDomainValidationKey" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getDomainValidationKeyException">
+                <soap:fault use="literal" name="getDomainValidationKeyException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="ValidateDomainServiceSoap12Binding" type="ns:ValidateDomainServicePortType">
+        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="validateByTextInRoot">
+            <soap12:operation soapAction="urn:validateByTextInRoot" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByTextInRootException">
+                <soap12:fault use="literal" name="validateByTextInRootException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <soap12:operation soapAction="urn:validateByDNSEntry" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="validateByDNSEntryException">
+                <soap12:fault use="literal" name="validateByDNSEntryException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <soap12:operation soapAction="urn:getDomainValidationKey" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getDomainValidationKeyException">
+                <soap12:fault use="literal" name="getDomainValidationKeyException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="ValidateDomainServiceHttpBinding" type="ns:ValidateDomainServicePortType">
+        <http:binding verb="POST" />
+        <wsdl:operation name="validateByTextInRoot">
+            <http:operation location="validateByTextInRoot" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="validateByDNSEntry">
+            <http:operation location="validateByDNSEntry" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="getDomainValidationKey">
+            <http:operation location="getDomainValidationKey" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:service name="ValidateDomainService">
+        <wsdl:port name="ValidateDomainServiceHttpsSoap11Endpoint" binding="ns:ValidateDomainServiceSoap11Binding">
+            <soap:address location="https://192.168.1.100:9443/services/ValidateDomainService.ValidateDomainServiceHttpsSoap11Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="ValidateDomainServiceHttpsSoap12Endpoint" binding="ns:ValidateDomainServiceSoap12Binding">
+            <soap12:address location="https://192.168.1.100:9443/services/ValidateDomainService.ValidateDomainServiceHttpsSoap12Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="ValidateDomainServiceHttpsEndpoint" binding="ns:ValidateDomainServiceHttpBinding">
+            <http:address location="https://192.168.1.100:9443/services/ValidateDomainService.ValidateDomainServiceHttpsEndpoint/" />
+        </wsdl:port>
+    </wsdl:service>
+</wsdl:definitions>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/JSResources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/JSResources.properties b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/JSResources.properties
new file mode 100644
index 0000000..7052880
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/JSResources.properties
@@ -0,0 +1,7 @@
+validation.fail.with.text=Domain ownership validation failed. Make sure you have put the exact text content mentioned here in the web root. 
+validation.success.with.text=Domain ownership validation succeeded.
+validation.fail.with.dns=Domain ownership validation failed. Note it may take sometime to propagate the changes in DNS. Please retry after a little break.
+validation.success.with.dns=Domain ownership validation succeeded.
+domain.empty=The domain to validate ownership is empty.
+domain.unavailable=The domain is already registered. Please choose a different domain.
+session.timed.out=Your session timed out. Please login again.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/Resources.properties b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/Resources.properties
new file mode 100644
index 0000000..fc77420
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/org/wso2/carbon/validate/domain/ui/i18n/Resources.properties
@@ -0,0 +1,3 @@
+domain.ownership.validation=Domain Ownership Validation
+validate.domain.menu=Validate Domain
+validate=Validate

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/css/validate_domain.css
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/css/validate_domain.css b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/css/validate_domain.css
new file mode 100644
index 0000000..7b83d63
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/css/validate_domain.css
@@ -0,0 +1,31 @@
+div#validation-introduction {
+    margin: 5px;
+}
+
+div#with-text {
+    margin: 5px;
+}
+
+div#with-dns {
+    margin: 5px;
+}
+p {
+    padding:5px !important;
+}
+
+p.validate-button {
+    padding: 15px 5px 15px 5px !important;
+}
+
+li.catagory {
+    padding: 5px 0px 5px 25px  !important;
+}
+
+
+
+div.conf-info {
+    background: #cccccc !important;
+    border: 1px solid #111 !important;
+    margin: 5px !important;
+    padding: 2px !important;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/images/domain-validation.png
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/images/domain-validation.png b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/images/domain-validation.png
new file mode 100644
index 0000000..382dfdb
Binary files /dev/null and b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/images/domain-validation.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/userguide.html b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/userguide.html
new file mode 100644
index 0000000..204c14a
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/docs/userguide.html
@@ -0,0 +1,47 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>Validate Domain Ownership - User Guide</title>
+  <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all" />
+</head>
+
+<body>
+<h1>Validate Domain Ownership</h1>
+
+<p>
+You can validate the ownership of your domain using two methods,
+    <ul>
+    <li>Creating a text file in the domain web ROOT </li>
+    <li>Setting up a CNAME entry in your DNS</li>
+    </ul>
+
+</p>
+
+
+<p>Instructions are shown in the following form.</p>
+
+<p>
+<img src="images/domain-validation.png" alt="Validation domain ownership"/>
+<div><strong>Figure1: Validate domain Ownership</strong></div>
+</p>
+
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/ajax-loader.gif
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/ajax-loader.gif b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/ajax-loader.gif
new file mode 100644
index 0000000..f2a1bc0
Binary files /dev/null and b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/ajax-loader.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/right.gif
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/right.gif b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/right.gif
new file mode 100644
index 0000000..72a64c9
Binary files /dev/null and b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/right.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/wrong.gif
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/wrong.gif b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/wrong.gif
new file mode 100644
index 0000000..77e1f2c
Binary files /dev/null and b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/images/wrong.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/js/validate_domain.js
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/js/validate_domain.js b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/js/validate_domain.js
new file mode 100644
index 0000000..1585b42
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/js/validate_domain.js
@@ -0,0 +1,151 @@
+function validateWithText(domain, status) {
+	sessionAwareStatusAwareFunction(function() {
+    if(domain == "") {
+        CARBON.showWarningDialog(org_wso2_carbon_validate_domain_ui_jsi18n["domain.empty"]);
+        return false;
+    }
+
+    var reason = checkDomain(domain);
+    if (reason != "") {
+        CARBON.showWarningDialog(reason);
+        return false;
+    }
+
+    var continueDiv = document.getElementById("with-text-continue");
+    var msgDiv = document.getElementById("with-text-msg");
+    var keyInput = document.getElementById("with-text-success-key");
+
+    var busyTextPlaceHolder = document.getElementById("busyText");
+    busyTextPlaceHolder.innerHTML = "<img src=\"images/ajax-loader.gif\"/>";
+
+    new Ajax.Request('../validate-domain/validate_with_text_ajaxprocessor.jsp',
+    {
+        method:'post',
+        parameters: {domain: domain, status: status},
+
+        onSuccess: function(transport) {
+            busyTextPlaceHolder.innerHTML = "";
+            var returnValue = transport.responseText;
+            if (returnValue.search(/----false----/) >= 0) {
+                msgDiv.style.color = "#f00";
+                msgDiv.innerHTML = "<img src='images/wrong.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["validation.fail.with.text"];
+                continueDiv.style.visibility = "hidden";
+            } else if (returnValue.search(/----unavailable----/) >= 0) {
+                msgDiv.style.color = "#f00";
+                msgDiv.innerHTML = "<img src='images/wrong.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["domain.unavailable"];
+                continueDiv.style.visibility = "hidden";
+            } else if (returnValue != "") {
+                msgDiv.style.color = "#058000";
+                msgDiv.innerHTML = "<img src='images/right.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["validation.success.with.text"];
+                continueDiv.style.visibility = "visible";
+                keyInput.value = returnValue;
+            }
+        },
+
+        onFailure: function(transport){
+            busyTextPlaceHolder.innerHTML = "";
+        }
+    });
+	}, status, org_wso2_carbon_validate_domain_ui_jsi18n["session.timed.out"]);
+}
+
+function validateWithDNS(domain, status) {
+	sessionAwareStatusAwareFunction(function() {
+    if(domain == "") {
+        CARBON.showWarningDialog(org_wso2_carbon_validate_domain_ui_jsi18n["domain.empty"]);
+        return false;
+    }
+
+    var reason = checkDomain(domain);
+    if (reason != "") {
+        CARBON.showWarningDialog(reason);
+        return false;
+    }
+
+    var continueDiv = document.getElementById("with-dns-continue");
+    var msgDiv = document.getElementById("with-dns-msg");
+    var keyInput = document.getElementById("with-dns-success-key");
+
+    var busyDNSPlaceHolder = document.getElementById("busyDNS");
+    busyDNSPlaceHolder.innerHTML = "<img src=\"images/ajax-loader.gif\"/>";
+
+    new Ajax.Request('../validate-domain/validate_with_dns_ajaxprocessor.jsp',
+    {
+        method:'post',
+        parameters: {domain: domain, status: status},
+
+        onSuccess: function(transport) {
+            busyDNSPlaceHolder.innerHTML = "";
+            var returnValue = transport.responseText;
+            if (returnValue.search(/----false----/) >= 0) {
+                msgDiv.style.color = "#f00";
+                msgDiv.innerHTML = "<img src='images/wrong.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["validation.fail.with.dns"];
+                continueDiv.style.visibility = "hidden";
+            } else if (returnValue.search(/----unavailable----/) >= 0) {
+                msgDiv.style.color = "#f00";
+                msgDiv.innerHTML = "<img src='images/wrong.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["domain.unavailable"];
+                continueDiv.style.visibility = "hidden";
+            } else if (returnValue != "") {
+                msgDiv.style.color = "#058000";
+                msgDiv.innerHTML = "<img src='images/right.gif'/> " + org_wso2_carbon_validate_domain_ui_jsi18n["validation.success.with.dns"];
+                continueDiv.style.visibility = "visible";
+                keyInput.value = returnValue;
+            }
+        },
+
+        onFailure: function(transport){
+            busyDNSPlaceHolder.innerHTML = "";
+        }
+    });
+	}, status, org_wso2_carbon_validate_domain_ui_jsi18n["session.timed.out"]);
+}
+
+
+function gotoRegister() {
+    window.location.href = '../tenant-register/success_register.jsp';
+}
+
+function checkDomain(domain)
+{
+    var error = "";
+    var lastIndexOfDot = domain.lastIndexOf(".");
+    var indexOfDot = domain.indexOf(".");
+    var extension = domain.substring(lastIndexOfDot, domain.length);
+
+    var illegalChars = /([^a-zA-Z0-9\._\-])/; // allow only letters and numbers . - _and period
+    if (extension.indexOf("-trial") >= 0 || extension.indexOf("-unverified") >= 0) {
+        // we are not allowing to create a domain with -trial or -unverified is in the extension
+        error = "The domain name you entered is not valid. Please enter a valid domain name.";
+    }
+    else if (lastIndexOfDot <= 0) {
+        // since this is domain validation, this expects a valid domain with an extension.
+        error = "Invalid domain: " + domain + ". You should have an extension to your domain.";
+    }
+    else if (indexOfDot == 0) {
+        error = "Invalid domain, starting with '.'";
+    }
+    else if (illegalChars.test(domain)) {
+        error = "The domain only allows letters, numbers, '.', '-' and '_'. <br />";
+    }
+    return error;
+}
+
+function sessionAwareStatusAwareFunction(func, status, msg) {
+	if (status == "logged_in") {
+		sessionAwareFunction(func, msg);
+	} else {
+		func();
+	}
+}
+
+function submitValidateWithDNSForm(status) {
+	sessionAwareStatusAwareFunction(function() {
+		$('validateWithDNSForm').submit();
+	}, status, org_wso2_carbon_validate_domain_ui_jsi18n["session.timed.out"]);
+}
+
+function submitValidateWithTextForm(status) {
+	sessionAwareStatusAwareFunction(function() {
+		$('validateWithTextForm').submit();
+	}, status, org_wso2_carbon_validate_domain_ui_jsi18n["session.timed.out"]);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/submit_validate_domain_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/submit_validate_domain_ajaxprocessor.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/submit_validate_domain_ajaxprocessor.jsp
new file mode 100644
index 0000000..b5edff1
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/submit_validate_domain_ajaxprocessor.jsp
@@ -0,0 +1,36 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.utils.multitenancy.MultitenantConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+String successKey = request.getParameter("successKey");
+String domain = request.getParameter("domain");
+String status = request.getParameter("status");
+session.setAttribute("validate-domain-success-key", successKey);
+session.setAttribute("temp-domain-to-register", domain);
+
+// redirect to the add registry domain page
+if ("logged_in".equals(status)) {
+    // we have already logged in so redirect to the account management page
+    response.sendRedirect("../account-mgt/validation_success_ajaxprocessor.jsp");
+}
+else {
+    // if not logged in we will redirect to the register org page
+    response.sendRedirect("../tenant-register/success_register.jsp");
+}
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_logged_in.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_logged_in.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_logged_in.jsp
new file mode 100644
index 0000000..6ee6e47
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_logged_in.jsp
@@ -0,0 +1,22 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<jsp:include page="validate_domain_template.jsp">
+    <jsp:param name="status" 
+     value="logged_in" />
+</jsp:include>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_not_logged_in.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_not_logged_in.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_not_logged_in.jsp
new file mode 100644
index 0000000..92b4f61
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_not_logged_in.jsp
@@ -0,0 +1,22 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<jsp:include page="validate_domain_template.jsp">
+    <jsp:param name="status" 
+     value="not_logged_in" />
+</jsp:include>
\ No newline at end of file


[26/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
new file mode 100644
index 0000000..bae3df9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.jdbc;
+
+import java.sql.Connection;
+
+public class Transaction {
+
+    private static ThreadLocal<Boolean> tStarted = new ThreadLocal<Boolean>() {
+        protected Boolean initialValue() {
+            return false;
+        }
+    };
+
+    private static ThreadLocal<Connection> tConnection = new ThreadLocal<Connection>() {
+        protected Connection initialValue() {
+            return null;
+        }
+    };
+
+    // this is a property that will be specific to embedded registry
+    private static ThreadLocal<Integer> tNestedDepth = new ThreadLocal<Integer>() {
+        protected Integer initialValue() {
+            return 0;
+        }
+    };
+
+    private static ThreadLocal<Boolean> tRollbacked = new ThreadLocal<Boolean>() {
+        protected Boolean initialValue() {
+            return false;
+        }
+    };
+
+    public static boolean isStarted() {
+        if (tStarted.get() == null) {
+            return false;
+        }
+
+        return tStarted.get();
+    }
+
+    public static void setStarted(boolean started) {
+        tStarted.set(started);
+    }
+
+    public static Connection getConnection() {
+        return tConnection.get();
+    }
+
+    public static void setConnection(Connection connection) {
+        if (connection != null) {
+            tStarted.set(true);
+        }
+        tConnection.set(connection);
+    }
+
+    public static void removeConnection() {
+        tStarted.remove();
+        tConnection.remove();
+    }
+
+    // the following two methods will increment and decrement
+    // the transaction depth of the current session
+    public static void incNestedDepth() {
+        int transactionDepth = tNestedDepth.get().intValue();
+        if (transactionDepth == 0) {
+            tStarted.set(true);
+            tRollbacked.set(false);
+        }
+        transactionDepth++;
+        tNestedDepth.set(transactionDepth);
+    }
+
+    public static void decNestedDepth() {
+        int transactionDepth = tNestedDepth.get().intValue();
+        transactionDepth--;
+        tNestedDepth.set(transactionDepth);
+        if (transactionDepth == 0) {
+            tStarted.set(false);
+        }
+    }
+
+    public static int getNestedDepth() {
+        return tNestedDepth.get().intValue();
+    }
+
+
+    public static boolean isRollbacked() {
+        if (tRollbacked.get() == null) {
+            return false;
+        }
+
+        return tRollbacked.get();
+    }
+
+    public static void setRollbacked(boolean rollbacked) {
+        tRollbacked.set(rollbacked);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
new file mode 100644
index 0000000..269beb5
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * This job is run by the scheduled task for
+ * bill generation
+ */
+public class BillingJob implements Job {
+    private static final Log log = LogFactory.getLog(BillingJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+        // first we generate the bill
+        BillingEngine billingEngine =
+                (BillingEngine) jobExecutionContext.getMergedJobDataMap().get(
+                        BillingConstants.BILLING_ENGINE_KEY);
+        SchedulerContext schedulerContext =
+                (SchedulerContext) jobExecutionContext.getMergedJobDataMap().get(
+                        BillingConstants.SCHEDULER_CONTEXT);
+        try {
+            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            long startTime = System.currentTimeMillis();
+            log.info("Bill generation started at " + dateFormat.format(new Date(System.currentTimeMillis())));
+
+            billingEngine.generateBill(schedulerContext);
+
+            log.info("Bill generation completed at " + dateFormat.format(new Date(System.currentTimeMillis())));
+            long timeTaken = System.currentTimeMillis() - startTime;
+            log.info("Time taken for bill generation: " + timeTaken/1000 + "s");
+        } catch (BillingException e) {
+            String msg = "Error in generating the bill";
+            log.error(msg, e);
+            throw new JobExecutionException(msg, e);
+        }
+        
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
new file mode 100644
index 0000000..c589431
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.TaskSchedulerFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+
+import java.util.*;
+
+public class BillingScheduler {
+    private static Log log = LogFactory.getLog(BillingScheduler.class);
+    private TaskScheduler taskScheduler;
+    private BillingTaskConfiguration billingTaskConfig;
+    private BillingEngine billingEngine;
+
+    public BillingScheduler(BillingEngine billingEngine,
+                            BillingTaskConfiguration billingTaskConfiguration) {
+        this.billingTaskConfig = billingTaskConfiguration;
+        this.billingEngine = billingEngine;
+        taskScheduler = TaskSchedulerFactory.getTaskScheduler(TaskConstants.TASK_SCHEDULER);
+        if (!taskScheduler.isInitialized()) {
+            Properties properties = new Properties();
+            taskScheduler.init(properties);
+        }
+    }
+
+    public SchedulerContext createScheduleContext() throws BillingException {
+        SchedulerContext schedulerContext = new SchedulerContext();
+        ScheduleHelper triggerCalculator = billingTaskConfig.getScheduleHelper();
+        if (triggerCalculator != null) {
+            triggerCalculator.invoke(schedulerContext);
+        }
+        return schedulerContext;
+    }
+
+    public void scheduleNextCycle(SchedulerContext schedulerContext) {
+
+        String taskName = UUIDGenerator.generateUUID();
+
+        TaskDescription taskDescription = new TaskDescription();
+        taskDescription.setName(taskName);
+        taskDescription.setGroup(BillingConstants.GROUP_ID);
+        taskDescription.setCron(schedulerContext.getCronString());
+        
+        Map<String, Object> resources = new HashMap<String, Object>();
+        resources.put(BillingConstants.TASK_NAME_KEY, taskName);
+        resources.put(BillingConstants.SCHEDULER_KEY, this);
+        resources.put(BillingConstants.BILLING_ENGINE_KEY, billingEngine);
+        resources.put(BillingConstants.SCHEDULER_CONTEXT, schedulerContext);
+        taskScheduler.scheduleTask(taskDescription, resources, BillingJob.class);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
new file mode 100644
index 0000000..4eb8cad
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.wso2.carbon.billing.core.BillingException;
+
+import java.util.Map;
+
+public interface ScheduleHelper {
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException;
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
new file mode 100644
index 0000000..3d450f9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+/**
+ * This class is used to store attributes necessary in
+ * scheduling bill generation
+ */
+public class SchedulerContext {
+
+    private String cronString;
+
+    public String getCronString() {
+        return cronString;
+    }
+
+    public void setCronString(String cronString) {
+        this.cronString = cronString;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
new file mode 100644
index 0000000..fadbb2c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler.scheduleHelpers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+import java.util.TimeZone;
+
+public class MonthlyScheduleHelper implements ScheduleHelper {
+    private static final Log log = LogFactory.getLog(MonthlyScheduleHelper.class);
+
+    private static final String CRON_KEY = "cron";
+    private static final String TIME_ZONE_KEY = "timeZone";
+    private static final String DEFAULT_TIMEZONE = "GMT-8:00";
+
+    private String cron;
+    private TimeZone timeZone;
+    
+
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException {
+        String timeZoneStr = triggerCalculatorConfig.get(TIME_ZONE_KEY);
+        if (timeZoneStr == null) {
+            timeZoneStr = DEFAULT_TIMEZONE;
+        }
+        timeZone = TimeZone.getTimeZone(timeZoneStr);
+        //Timezone is important when comparing dates in sql queries
+        DataAccessObject.TIMEZONE = timeZoneStr;
+        
+        cron = triggerCalculatorConfig.get(CRON_KEY);
+        log.debug("Cron string: " + cron);
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        schedulerContext.setCronString(cron);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
new file mode 100644
index 0000000..00e078a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler.scheduleHelpers;
+
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+
+public class OneTimeScheduleHelper implements ScheduleHelper {
+
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException {
+        // nothing to init
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        // nothing much to do
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
new file mode 100644
index 0000000..37df06b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.utilities;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Utility class for customer related operations
+ */
+public class CustomerUtils {
+    private static Log log = LogFactory.getLog(CustomerUtils.class);
+
+    /**
+     * Fill the customer object with data retrieved from the tenant manager
+     * @param customerId
+     * @param customer
+     * @throws BillingException
+     */
+    public static void fillCustomerData(int customerId, Customer customer) throws BillingException{
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            customer.setId(customerId);
+            customer.setName(tenant.getDomain());
+            customer.setStartedDate(tenant.getCreatedDate());
+            customer.setEmail(tenant.getEmail());
+            //customer.setAddress(); //we dont have the address
+        }catch (Exception e){
+            String msg = "Failed to fill the data for customer: " +
+                    customer.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    /**
+     * Get the customer by tenant id (customer id) using the realm service
+     * @param customerId
+     * @return
+     * @throws BillingException
+     */
+    public static Customer getCustomer(int customerId) throws BillingException{
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        Customer customer = null;
+
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            if(tenant!=null){
+                customer = new Customer();
+                customer.setId(customerId);
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+            }
+        } catch (Exception e){
+            String msg = "Failed to get customer for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customer;
+    }
+
+    /**
+     * Get the tenantId (customer id) of a customer from the realm service
+     * @param customerName
+     * @return
+     * @throws BillingException
+     */
+    public static int getCustomerId(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        int tenantId;
+        try{
+            tenantId = tenantManager.getTenantId(customerName);
+        }catch (Exception e){
+            String msg = "Failed to get tenant for domain: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return tenantId;
+    }
+
+    /**
+     * Get all the customers ( fill customers from tenants)
+     * @return
+     * @throws BillingException
+     */
+    public static List<Customer> getAllCustomers() throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            Tenant[] tenants = tenantManager.getAllTenants();
+            if(tenants!=null && tenants.length>0){
+                for(Tenant tenant : tenants){
+                    Customer customer = new Customer();
+                    customer.setId(tenant.getId());
+                    customer.setName(tenant.getDomain());
+                    customer.setStartedDate(tenant.getCreatedDate());
+                    customer.setEmail(tenant.getEmail());
+                    //customer.setAddress(); //no address yet
+                    customers.add(customer);
+                }
+            }
+        } catch (Exception e){
+            String msg = "Failed to get all the customers.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
new file mode 100644
index 0000000..78ea40d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
@@ -0,0 +1,34 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.billing.core.utilities;
+
+import javax.sql.DataSource;
+
+public class DataSourceHolder {
+    public static DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public static void setDataSource(DataSource dataSource) {
+        DataSourceHolder.dataSource = dataSource;
+    }
+
+    private static DataSource dataSource;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
new file mode 100644
index 0000000..500adb5
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class CarbonHome1Test extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "carbonHome1TestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+//        SessionDescription sessionDescription = new SessionDescription();
+//        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        /*RuleServerManager ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        */
+//        OMElement config = TestUtils.loadConfigXML();
+////        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+//        RuleServerManager ruleServerManager = new RuleServerManager();
+//        ruleServerManager.init(ruleServerConfiguration);
+
+        //Util.setRuleEngineConfigService(ruleServerManager);
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testDataSource() throws BillingException {
+        TestUtils.deleteAllTables();
+        Item item = new Item();
+        item.setName("myitem-0");
+        item.setCost(new Cash("$50.23"));
+        item.setDescription("Just a simple item");
+
+        Item accessedItem;
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            int itemId;
+            List<Item> items = billingEngine.getItemsWithName(item.getName());
+            for (Item existingItem : items) {
+                //billingEngine.deleteItem(existingItem.getId());
+            }
+            itemId = billingEngine.addItem(item);
+            accessedItem = billingEngine.getItem(itemId);
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+        assertEquals("Item name", accessedItem.getName(), item.getName());
+        assertEquals("Item description", accessedItem.getDescription(), item.getDescription());
+        assertEquals("Item cost", accessedItem.getCost().serializeToString(), item.getCost().serializeToString());
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$1.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+        for (int i = 0; i < customers.size(); i++) {
+            Customer customer = customers.get(i);
+            Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java
new file mode 100644
index 0000000..9ddc2d1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+public class CashTest extends TestCase {
+    public void testCash() throws BillingException {
+        successCase("$20.58", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 58);
+        successCase("$20.5", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 50);
+        successCase("$20.05", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 5);
+        successCase("20.05", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 5);
+        successCase("20", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 0);
+        successCase("20.0", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 0);
+        successCase("-20.0", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 20, 0);
+        successCase("$-21.5", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 50);
+        successCase("$-0.05", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 0, 5);
+
+        failCase("2343x");
+        failCase("20.");
+        failCase("34.34.34");
+        failCase("34.2343");
+        failCase("34x.23");
+        failCase("34.2x");
+        failCase("$-.05");
+
+        // always putting
+        checkSerialize("$5.8", "$5.80");
+        checkSerialize("0.5", "$0.50");
+        checkSerialize("$-3", "$-3.00");
+        checkSerialize("$-2.5", "$-2.50");
+        checkSerialize("-0.5", "$-0.50");
+
+        // checking some adds
+        checkAdd("3.54", "3.34", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 6, 88);
+        checkAdd("3.54", "3.6", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 7, 14);
+        checkAdd("3.8", "-5.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 2, 0);
+        checkAdd("-23.8", "2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 0);
+        checkAdd("-23.8", "-2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 26, 60);
+
+
+        checkSustract("3.54", "3.34", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 0, 20);
+        checkSustract("3.54", "3.6", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 0, 6);
+        checkSustract("3.8", "-5.8", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 9, 60);
+        checkSustract("-23.8", "2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 26, 60);
+        checkSustract("-23.8", "-2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 0);
+    }
+
+    private void checkAdd(String cashA, String cashB, String currency,
+                          Cash.Sign sign, int wholeNumber, int decimalNumber) throws BillingException {
+        successCase(Cash.add(new Cash(cashA), new Cash(cashB)).serializeToString(),
+                currency, sign, wholeNumber, decimalNumber);
+    }
+
+    private void checkSustract(String cashA, String cashB, String currency,
+                               Cash.Sign sign, int wholeNumber, int decimalNumber) throws BillingException {
+        successCase(Cash.subtract(new Cash(cashA), new Cash(cashB)).serializeToString(),
+                currency, sign, wholeNumber, decimalNumber);
+    }
+
+    private void checkSerialize(String cashStr, String cashStrShouldBe) throws BillingException {
+        Cash cash = new Cash(cashStr);
+        assertEquals("Cash string should be " + cashStrShouldBe, cash.serializeToString(), cashStrShouldBe);
+    }
+
+    private void successCase(String cashString, String currency, Cash.Sign sign, int wholeNumber, int decimalNumber)
+            throws BillingException {
+        Cash cash = new Cash(cashString);
+        boolean success = currency.equals(cash.getCurrency()) &&
+                sign == cash.getSign() &&
+                wholeNumber == cash.getWholeNumber() &&
+                decimalNumber == cash.getDecimalNumber();
+        assertTrue(cashString + " failed", success);
+    }
+
+    public void failCase(String cashString) {
+        boolean gotError;
+        try {
+            new Cash(cashString);
+            gotError = false;
+        } catch (BillingException e) {
+            gotError = true;
+        }
+        assertTrue(cashString + "is not failed (should have failed)", gotError);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
new file mode 100644
index 0000000..6ac08d6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+
+public class FiveSecondTriggerCalculator implements ScheduleHelper {
+    private int countUpToLimit;
+    private static int count;
+
+    public void init(Map<String, String> triggerCalculatorConfig) {
+        String countUpToStr = triggerCalculatorConfig.get("countUpToLimit");
+        countUpToLimit = Integer.parseInt(countUpToStr);
+        count = 0; // obviously this is not thread-safe.
+        // nothing to init
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        if (count >= countUpToLimit) {
+            //schedulerContext.setNextTriggerInterval(-1);
+            return;
+        }
+        //long currentTime = System.currentTimeMillis();
+        //schedulerContext.setNextTriggerInterval(5000);
+        count++;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
new file mode 100644
index 0000000..a5e9bf2
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+
+import java.util.Map;
+
+public class FiveSecondTriggerTester implements BillingHandler {
+    private static int count;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to init   
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        count++;
+    }
+
+    public static int getCount() {
+        return count;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
new file mode 100644
index 0000000..2cb029f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.handlers.EmailSendingHandler;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.*;
+
+public class InvoiceMsgTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "ruleTestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+
+        /*RuleEngineConfigService recf = new
+        RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+
+        Customer customer = customers.get(0);
+        Invoice invoice = billingEngine.getLastInvoice(customer);
+
+        Map<String, String> mailParameters =
+                EmailSendingHandler.deriveInvoiceMailParameters(invoice);
+
+        assertEquals(mailParameters.get("total-cost"), "$0.20");
+        assertEquals(mailParameters.get("total-payments"), "$5.50");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
new file mode 100644
index 0000000..54dc574
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+import org.wso2.carbon.billing.core.scheduler.scheduleHelpers.MonthlyScheduleHelper;
+
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TimeZone;
+
+public class MonthlyTriggerCalculatorTest extends TestCase {
+    @Override
+    public void setUp() {
+        // nothing to setup here
+    }
+
+    public void testNextTriggerInterval() throws BillingException {
+        nextMonthFirstDate("1", 1999, Calendar.DECEMBER, 2, 2000, Calendar.JANUARY, 1, 1999,
+                Calendar.NOVEMBER, 1, 1999, Calendar.NOVEMBER, 30, "1999-November");
+        nextMonthFirstDate("1", 2009, Calendar.DECEMBER, 2, 2010, Calendar.JANUARY, 1, 2009,
+                Calendar.NOVEMBER, 1, 2009, Calendar.NOVEMBER, 30, "2009-November");
+        nextMonthFirstDate("1", 2009, Calendar.DECEMBER, 31, 2010, Calendar.JANUARY, 1, 2009,
+                Calendar.NOVEMBER, 1, 2009, Calendar.NOVEMBER, 30, "2009-November");
+        nextMonthFirstDate("15", 2010, Calendar.FEBRUARY, 8, 2010, Calendar.MARCH, 15, 2010,
+                Calendar.JANUARY, 15, 2010, Calendar.FEBRUARY, 14, "2010-January");
+    }
+
+    private void nextMonthFirstDate(String triggerOn, int someYear, int someMonth, int someDay,
+                                    int nextMonthFirstDateYear, int nextMonthFirstDateMonth,
+                                    int nextMonthFirstDateDay, int durationStartYear,
+                                    int durationStartMonth, int durationStartDay,
+                                    int durationEndYear, int durationEndMonth, int durationEndDay,
+                                    String yearMonthString) throws BillingException {
+        Calendar someCalender = Calendar.getInstance();
+        someCalender.set(someYear, someMonth, someDay);
+        long someDateTimeStamp = someCalender.getTimeInMillis();
+
+        Map<String, String> args = new HashMap<String, String>();
+        String timeZoneStr = "GMT-8:00";
+        TimeZone timeZone = TimeZone.getTimeZone(timeZoneStr);
+        args.put("timeZone", timeZoneStr);
+        args.put("dayToTriggerOn", triggerOn);
+        args.put("hourToTriggerOn", "0");
+        MonthlyScheduleHelper monthlyTriggerCalculator = new MonthlyScheduleHelper();
+        monthlyTriggerCalculator.init(args);
+
+        SchedulerContext schedulerContext = new SchedulerContext();
+        //monthlyTriggerCalculator.invoke(schedulerContext, someDateTimeStamp);
+
+        //long nextMonthFirstTimeStampDuration = schedulerContext.getNextTriggerInterval();
+
+        //long durationStart = schedulerContext.getCurrentDurationStart();
+        //long durationEnd = schedulerContext.getCurrentDurationEnd();
+        //String realMonthStr = schedulerContext.getDurationString();
+
+        Calendar nextMonthFirstCalendar = Calendar.getInstance(timeZone);
+        //nextMonthFirstCalendar.setTimeInMillis(someDateTimeStamp + nextMonthFirstTimeStampDuration);
+
+        assertEquals("Year should be " + nextMonthFirstDateYear,
+                nextMonthFirstCalendar.get(Calendar.YEAR), nextMonthFirstDateYear);
+        assertEquals("Month should be " + nextMonthFirstDateMonth,
+                nextMonthFirstCalendar.get(Calendar.MONTH), nextMonthFirstDateMonth);
+        assertEquals("Date should be " + nextMonthFirstDateDay,
+                nextMonthFirstCalendar.get(Calendar.DAY_OF_MONTH), nextMonthFirstDateDay);
+
+        Calendar durationStartCalendar = Calendar.getInstance(timeZone);
+        //durationStartCalendar.setTimeInMillis(durationStart);
+
+        assertEquals("Year should be " + durationStartYear,
+                durationStartCalendar.get(Calendar.YEAR), durationStartYear);
+        assertEquals("Month should be " + durationStartMonth,
+                durationStartCalendar.get(Calendar.MONTH), durationStartMonth);
+        assertEquals("Date should be " + durationStartDay,
+                durationStartCalendar.get(Calendar.DAY_OF_MONTH), durationStartDay);
+
+        Calendar durationEndCalendar = Calendar.getInstance(timeZone);
+        //durationEndCalendar.setTimeInMillis(durationEnd);
+
+        assertEquals("Year should be " + durationEndYear, durationEndCalendar.get(Calendar.YEAR),
+                durationEndYear);
+        assertEquals("Month should be " + durationEndMonth,
+                durationEndCalendar.get(Calendar.MONTH), durationEndMonth);
+        assertEquals("Date should be " + durationEndDay,
+                durationEndCalendar.get(Calendar.DAY_OF_MONTH), durationEndDay);
+
+        //assertEquals("YearMonth String should be equal", realMonthStr, yearMonthString);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
new file mode 100644
index 0000000..126939f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class RuleTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "ruleTestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        /*RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+        for (int i = 0; i < customers.size(); i++) {
+            Customer customer = customers.get(i);
+            Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
new file mode 100644
index 0000000..395d86b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import java.io.*;
+
+public class TestUtils {
+
+    private static final String RULE_COMPONENT_CONF = "rule-component.conf";
+
+    public static void deleteAllTables() throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        boolean succeeded = false;
+        try {
+            dataAccessObject.beginTransaction();
+            /*dataAccessObject.deleteInvoiceSubscriptionItems();
+            dataAccessObject.deleteInvoiceSubscriptions();
+            dataAccessObject.deletePaymentSubscriptions();
+            dataAccessObject.deletePayments();
+            dataAccessObject.deleteInvoice();
+            dataAccessObject.deleteSubscribers();
+            dataAccessObject.deleteItems();
+            dataAccessObject.deleteCustomers();
+            */
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                dataAccessObject.commitTransaction();
+            } else {
+                dataAccessObject.rollbackTransaction();
+            }
+        }
+    }
+
+    public static OMElement loadConfigXML() throws Exception {
+
+        String carbonHome = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH);
+        String path = carbonHome + File.separator + RULE_COMPONENT_CONF;
+        BufferedInputStream inputStream = null;
+        try {
+            File file = new File(path);
+            if (!file.exists()) {
+                inputStream = new BufferedInputStream(
+                        new ByteArrayInputStream("<RuleServer/>".getBytes()));
+            } else {
+                inputStream = new BufferedInputStream(new FileInputStream(file));
+            }
+            XMLStreamReader parser = XMLInputFactory.newInstance().
+                    createXMLStreamReader(inputStream);
+            StAXOMBuilder builder = new StAXOMBuilder(parser);
+            return builder.getDocumentElement();
+        } finally {
+            try {
+                if (inputStream != null) {
+                    inputStream.close();
+                }
+            } catch (IOException ignored) {
+            }
+        }
+    }
+}


[42/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/AccountMgtService.wsdl
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/AccountMgtService.wsdl b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/AccountMgtService.wsdl
new file mode 100644
index 0000000..f5aa207
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/AccountMgtService.wsdl
@@ -0,0 +1,628 @@
+<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://services.mgt.account.carbon.wso2.org" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ax21="http://beans.mgt.account.carbon.wso2.org/xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://services.mgt.account.carbon.wso2.org">
+    <wsdl:documentation>AccountMgtService</wsdl:documentation>
+    <wsdl:types>
+        <xs:schema xmlns:ax22="http://beans.mgt.account.carbon.wso2.org/xsd" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://services.mgt.account.carbon.wso2.org">
+            <xs:import namespace="http://beans.mgt.account.carbon.wso2.org/xsd" />
+            <xs:element name="updateFullnameException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="updateFullnameException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:complexType name="Exception">
+                <xs:sequence>
+                    <xs:element minOccurs="0" name="Message" nillable="true" type="xs:string" />
+                </xs:sequence>
+            </xs:complexType>
+            <xs:element name="updateFullname">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="accountInfoBean" nillable="true" type="ax21:AccountInfoBean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="updateFullnameResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" type="xs:boolean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="updateContactException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="updateContactException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="updateContact">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="contactEmail" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isEmailValidatedException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="isEmailValidatedException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isEmailValidated">
+                <xs:complexType>
+                    <xs:sequence />
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isEmailValidatedResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" type="xs:boolean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isDomainValidatedException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="isDomainValidatedException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isDomainValidated">
+                <xs:complexType>
+                    <xs:sequence />
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="isDomainValidatedResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" type="xs:boolean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getFullnameException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="getFullnameException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getFullname">
+                <xs:complexType>
+                    <xs:sequence />
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getFullnameResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="ax21:AccountInfoBean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getContactException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="getContactException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getContact">
+                <xs:complexType>
+                    <xs:sequence />
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="getContactResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="finishedDomainValidationException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="finishedDomainValidationException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="finishedDomainValidation">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="validatedDomain" nillable="true" type="xs:string" />
+                        <xs:element minOccurs="0" name="successKey" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="finishedDomainValidationResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" type="xs:boolean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="deactivateException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="deactivateException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="deactivate">
+                <xs:complexType>
+                    <xs:sequence />
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="checkDomainAvailabilityException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="checkDomainAvailabilityException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="checkDomainAvailability">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domainName" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:element name="checkDomainAvailabilityResponse">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="return" type="xs:boolean" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+        </xs:schema>
+        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://beans.mgt.account.carbon.wso2.org/xsd">
+            <xs:complexType name="AccountInfoBean">
+                <xs:sequence>
+                    <xs:element minOccurs="0" name="firstname" nillable="true" type="xs:string" />
+                    <xs:element minOccurs="0" name="lastname" nillable="true" type="xs:string" />
+                </xs:sequence>
+            </xs:complexType>
+        </xs:schema>
+    </wsdl:types>
+    <wsdl:message name="checkDomainAvailabilityRequest">
+        <wsdl:part name="parameters" element="ns:checkDomainAvailability" />
+    </wsdl:message>
+    <wsdl:message name="checkDomainAvailabilityResponse">
+        <wsdl:part name="parameters" element="ns:checkDomainAvailabilityResponse" />
+    </wsdl:message>
+    <wsdl:message name="checkDomainAvailabilityException">
+        <wsdl:part name="parameters" element="ns:checkDomainAvailabilityException" />
+    </wsdl:message>
+    <wsdl:message name="getContactRequest">
+        <wsdl:part name="parameters" element="ns:getContact" />
+    </wsdl:message>
+    <wsdl:message name="getContactResponse">
+        <wsdl:part name="parameters" element="ns:getContactResponse" />
+    </wsdl:message>
+    <wsdl:message name="getContactException">
+        <wsdl:part name="parameters" element="ns:getContactException" />
+    </wsdl:message>
+    <wsdl:message name="isEmailValidatedRequest">
+        <wsdl:part name="parameters" element="ns:isEmailValidated" />
+    </wsdl:message>
+    <wsdl:message name="isEmailValidatedResponse">
+        <wsdl:part name="parameters" element="ns:isEmailValidatedResponse" />
+    </wsdl:message>
+    <wsdl:message name="isEmailValidatedException">
+        <wsdl:part name="parameters" element="ns:isEmailValidatedException" />
+    </wsdl:message>
+    <wsdl:message name="updateFullnameRequest">
+        <wsdl:part name="parameters" element="ns:updateFullname" />
+    </wsdl:message>
+    <wsdl:message name="updateFullnameResponse">
+        <wsdl:part name="parameters" element="ns:updateFullnameResponse" />
+    </wsdl:message>
+    <wsdl:message name="updateFullnameException">
+        <wsdl:part name="parameters" element="ns:updateFullnameException" />
+    </wsdl:message>
+    <wsdl:message name="isDomainValidatedRequest">
+        <wsdl:part name="parameters" element="ns:isDomainValidated" />
+    </wsdl:message>
+    <wsdl:message name="isDomainValidatedResponse">
+        <wsdl:part name="parameters" element="ns:isDomainValidatedResponse" />
+    </wsdl:message>
+    <wsdl:message name="isDomainValidatedException">
+        <wsdl:part name="parameters" element="ns:isDomainValidatedException" />
+    </wsdl:message>
+    <wsdl:message name="deactivateRequest">
+        <wsdl:part name="parameters" element="ns:deactivate" />
+    </wsdl:message>
+    <wsdl:message name="deactivateResponse" />
+    <wsdl:message name="deactivateException">
+        <wsdl:part name="parameters" element="ns:deactivateException" />
+    </wsdl:message>
+    <wsdl:message name="getFullnameRequest">
+        <wsdl:part name="parameters" element="ns:getFullname" />
+    </wsdl:message>
+    <wsdl:message name="getFullnameResponse">
+        <wsdl:part name="parameters" element="ns:getFullnameResponse" />
+    </wsdl:message>
+    <wsdl:message name="getFullnameException">
+        <wsdl:part name="parameters" element="ns:getFullnameException" />
+    </wsdl:message>
+    <wsdl:message name="finishedDomainValidationRequest">
+        <wsdl:part name="parameters" element="ns:finishedDomainValidation" />
+    </wsdl:message>
+    <wsdl:message name="finishedDomainValidationResponse">
+        <wsdl:part name="parameters" element="ns:finishedDomainValidationResponse" />
+    </wsdl:message>
+    <wsdl:message name="finishedDomainValidationException">
+        <wsdl:part name="parameters" element="ns:finishedDomainValidationException" />
+    </wsdl:message>
+    <wsdl:message name="updateContactRequest">
+        <wsdl:part name="parameters" element="ns:updateContact" />
+    </wsdl:message>
+    <wsdl:message name="updateContactResponse" />
+    <wsdl:message name="updateContactException">
+        <wsdl:part name="parameters" element="ns:updateContactException" />
+    </wsdl:message>
+    <wsdl:portType name="AccountMgtServicePortType">
+        <wsdl:operation name="checkDomainAvailability">
+            <wsdl:input message="ns:checkDomainAvailabilityRequest" wsaw:Action="urn:checkDomainAvailability" />
+            <wsdl:output message="ns:checkDomainAvailabilityResponse" wsaw:Action="urn:checkDomainAvailabilityResponse" />
+            <wsdl:fault message="ns:checkDomainAvailabilityException" name="checkDomainAvailabilityException" wsaw:Action="urn:checkDomainAvailabilitycheckDomainAvailabilityException" />
+        </wsdl:operation>
+        <wsdl:operation name="getContact">
+            <wsdl:input message="ns:getContactRequest" wsaw:Action="urn:getContact" />
+            <wsdl:output message="ns:getContactResponse" wsaw:Action="urn:getContactResponse" />
+            <wsdl:fault message="ns:getContactException" name="getContactException" wsaw:Action="urn:getContactgetContactException" />
+        </wsdl:operation>
+        <wsdl:operation name="isEmailValidated">
+            <wsdl:input message="ns:isEmailValidatedRequest" wsaw:Action="urn:isEmailValidated" />
+            <wsdl:output message="ns:isEmailValidatedResponse" wsaw:Action="urn:isEmailValidatedResponse" />
+            <wsdl:fault message="ns:isEmailValidatedException" name="isEmailValidatedException" wsaw:Action="urn:isEmailValidatedisEmailValidatedException" />
+        </wsdl:operation>
+        <wsdl:operation name="updateFullname">
+            <wsdl:input message="ns:updateFullnameRequest" wsaw:Action="urn:updateFullname" />
+            <wsdl:output message="ns:updateFullnameResponse" wsaw:Action="urn:updateFullnameResponse" />
+            <wsdl:fault message="ns:updateFullnameException" name="updateFullnameException" wsaw:Action="urn:updateFullnameupdateFullnameException" />
+        </wsdl:operation>
+        <wsdl:operation name="isDomainValidated">
+            <wsdl:input message="ns:isDomainValidatedRequest" wsaw:Action="urn:isDomainValidated" />
+            <wsdl:output message="ns:isDomainValidatedResponse" wsaw:Action="urn:isDomainValidatedResponse" />
+            <wsdl:fault message="ns:isDomainValidatedException" name="isDomainValidatedException" wsaw:Action="urn:isDomainValidatedisDomainValidatedException" />
+        </wsdl:operation>
+        <wsdl:operation name="deactivate">
+            <wsdl:input message="ns:deactivateRequest" wsaw:Action="urn:deactivate" />
+            <wsdl:output message="ns:deactivateResponse" wsaw:Action="urn:deactivateResponse" />
+            <wsdl:fault message="ns:deactivateException" name="deactivateException" wsaw:Action="urn:deactivatedeactivateException" />
+        </wsdl:operation>
+        <wsdl:operation name="getFullname">
+            <wsdl:input message="ns:getFullnameRequest" wsaw:Action="urn:getFullname" />
+            <wsdl:output message="ns:getFullnameResponse" wsaw:Action="urn:getFullnameResponse" />
+            <wsdl:fault message="ns:getFullnameException" name="getFullnameException" wsaw:Action="urn:getFullnamegetFullnameException" />
+        </wsdl:operation>
+        <wsdl:operation name="finishedDomainValidation">
+            <wsdl:input message="ns:finishedDomainValidationRequest" wsaw:Action="urn:finishedDomainValidation" />
+            <wsdl:output message="ns:finishedDomainValidationResponse" wsaw:Action="urn:finishedDomainValidationResponse" />
+            <wsdl:fault message="ns:finishedDomainValidationException" name="finishedDomainValidationException" wsaw:Action="urn:finishedDomainValidationfinishedDomainValidationException" />
+        </wsdl:operation>
+        <wsdl:operation name="updateContact">
+            <wsdl:input message="ns:updateContactRequest" wsaw:Action="urn:updateContact" />
+            <wsdl:output message="ns:updateContactResponse" wsaw:Action="urn:updateContactResponse" />
+            <wsdl:fault message="ns:updateContactException" name="updateContactException" wsaw:Action="urn:updateContactupdateContactException" />
+        </wsdl:operation>
+    </wsdl:portType>
+    <wsdl:binding name="AccountMgtServiceSoap11Binding" type="ns:AccountMgtServicePortType">
+        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="checkDomainAvailability">
+            <soap:operation soapAction="urn:checkDomainAvailability" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="checkDomainAvailabilityException">
+                <soap:fault use="literal" name="checkDomainAvailabilityException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getContact">
+            <soap:operation soapAction="urn:getContact" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getContactException">
+                <soap:fault use="literal" name="getContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="isEmailValidated">
+            <soap:operation soapAction="urn:isEmailValidated" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="isEmailValidatedException">
+                <soap:fault use="literal" name="isEmailValidatedException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="updateFullname">
+            <soap:operation soapAction="urn:updateFullname" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="updateFullnameException">
+                <soap:fault use="literal" name="updateFullnameException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="isDomainValidated">
+            <soap:operation soapAction="urn:isDomainValidated" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="isDomainValidatedException">
+                <soap:fault use="literal" name="isDomainValidatedException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="deactivate">
+            <soap:operation soapAction="urn:deactivate" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="deactivateException">
+                <soap:fault use="literal" name="deactivateException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getFullname">
+            <soap:operation soapAction="urn:getFullname" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getFullnameException">
+                <soap:fault use="literal" name="getFullnameException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="finishedDomainValidation">
+            <soap:operation soapAction="urn:finishedDomainValidation" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="finishedDomainValidationException">
+                <soap:fault use="literal" name="finishedDomainValidationException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="updateContact">
+            <soap:operation soapAction="urn:updateContact" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="updateContactException">
+                <soap:fault use="literal" name="updateContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="AccountMgtServiceSoap12Binding" type="ns:AccountMgtServicePortType">
+        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="checkDomainAvailability">
+            <soap12:operation soapAction="urn:checkDomainAvailability" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="checkDomainAvailabilityException">
+                <soap12:fault use="literal" name="checkDomainAvailabilityException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getContact">
+            <soap12:operation soapAction="urn:getContact" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getContactException">
+                <soap12:fault use="literal" name="getContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="isEmailValidated">
+            <soap12:operation soapAction="urn:isEmailValidated" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="isEmailValidatedException">
+                <soap12:fault use="literal" name="isEmailValidatedException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="updateFullname">
+            <soap12:operation soapAction="urn:updateFullname" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="updateFullnameException">
+                <soap12:fault use="literal" name="updateFullnameException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="isDomainValidated">
+            <soap12:operation soapAction="urn:isDomainValidated" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="isDomainValidatedException">
+                <soap12:fault use="literal" name="isDomainValidatedException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="deactivate">
+            <soap12:operation soapAction="urn:deactivate" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="deactivateException">
+                <soap12:fault use="literal" name="deactivateException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="getFullname">
+            <soap12:operation soapAction="urn:getFullname" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="getFullnameException">
+                <soap12:fault use="literal" name="getFullnameException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="finishedDomainValidation">
+            <soap12:operation soapAction="urn:finishedDomainValidation" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="finishedDomainValidationException">
+                <soap12:fault use="literal" name="finishedDomainValidationException" />
+            </wsdl:fault>
+        </wsdl:operation>
+        <wsdl:operation name="updateContact">
+            <soap12:operation soapAction="urn:updateContact" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="updateContactException">
+                <soap12:fault use="literal" name="updateContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="AccountMgtServiceHttpBinding" type="ns:AccountMgtServicePortType">
+        <http:binding verb="POST" />
+        <wsdl:operation name="checkDomainAvailability">
+            <http:operation location="checkDomainAvailability" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="getContact">
+            <http:operation location="getContact" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="isEmailValidated">
+            <http:operation location="isEmailValidated" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="updateFullname">
+            <http:operation location="updateFullname" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="isDomainValidated">
+            <http:operation location="isDomainValidated" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="deactivate">
+            <http:operation location="deactivate" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="getFullname">
+            <http:operation location="getFullname" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="finishedDomainValidation">
+            <http:operation location="finishedDomainValidation" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+        <wsdl:operation name="updateContact">
+            <http:operation location="updateContact" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:service name="AccountMgtService">
+        <wsdl:port name="AccountMgtServiceHttpsSoap11Endpoint" binding="ns:AccountMgtServiceSoap11Binding">
+            <soap:address location="https://192.168.1.100:9443/services/AccountMgtService.AccountMgtServiceHttpsSoap11Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="AccountMgtServiceHttpsSoap12Endpoint" binding="ns:AccountMgtServiceSoap12Binding">
+            <soap12:address location="https://192.168.1.100:9443/services/AccountMgtService.AccountMgtServiceHttpsSoap12Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="AccountMgtServiceHttpsEndpoint" binding="ns:AccountMgtServiceHttpBinding">
+            <http:address location="https://192.168.1.100:9443/services/AccountMgtService.AccountMgtServiceHttpsEndpoint/" />
+        </wsdl:port>
+    </wsdl:service>
+</wsdl:definitions>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/EmailValidationService.wsdl
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/EmailValidationService.wsdl b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/EmailValidationService.wsdl
new file mode 100644
index 0000000..7cb056f
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/EmailValidationService.wsdl
@@ -0,0 +1,95 @@
+<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://services.mgt.account.carbon.wso2.org" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://services.mgt.account.carbon.wso2.org">
+    <wsdl:documentation>EmailValidationService</wsdl:documentation>
+    <wsdl:types>
+        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://services.mgt.account.carbon.wso2.org">
+            <xs:element name="proceedUpdateContactException">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="proceedUpdateContactException" nillable="true" type="ns:Exception" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+            <xs:complexType name="Exception">
+                <xs:sequence>
+                    <xs:element minOccurs="0" name="Message" nillable="true" type="xs:string" />
+                </xs:sequence>
+            </xs:complexType>
+            <xs:element name="proceedUpdateContact">
+                <xs:complexType>
+                    <xs:sequence>
+                        <xs:element minOccurs="0" name="domain" nillable="true" type="xs:string" />
+                        <xs:element minOccurs="0" name="email" nillable="true" type="xs:string" />
+                        <xs:element minOccurs="0" name="confirmationKey" nillable="true" type="xs:string" />
+                    </xs:sequence>
+                </xs:complexType>
+            </xs:element>
+        </xs:schema>
+    </wsdl:types>
+    <wsdl:message name="proceedUpdateContactRequest">
+        <wsdl:part name="parameters" element="ns:proceedUpdateContact" />
+    </wsdl:message>
+    <wsdl:message name="proceedUpdateContactResponse" />
+    <wsdl:message name="proceedUpdateContactException">
+        <wsdl:part name="parameters" element="ns:proceedUpdateContactException" />
+    </wsdl:message>
+    <wsdl:portType name="EmailValidationServicePortType">
+        <wsdl:operation name="proceedUpdateContact">
+            <wsdl:input message="ns:proceedUpdateContactRequest" wsaw:Action="urn:proceedUpdateContact" />
+            <wsdl:output message="ns:proceedUpdateContactResponse" wsaw:Action="urn:proceedUpdateContactResponse" />
+            <wsdl:fault message="ns:proceedUpdateContactException" name="proceedUpdateContactException" wsaw:Action="urn:proceedUpdateContactproceedUpdateContactException" />
+        </wsdl:operation>
+    </wsdl:portType>
+    <wsdl:binding name="EmailValidationServiceSoap11Binding" type="ns:EmailValidationServicePortType">
+        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="proceedUpdateContact">
+            <soap:operation soapAction="urn:proceedUpdateContact" style="document" />
+            <wsdl:input>
+                <soap:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="proceedUpdateContactException">
+                <soap:fault use="literal" name="proceedUpdateContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="EmailValidationServiceSoap12Binding" type="ns:EmailValidationServicePortType">
+        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
+        <wsdl:operation name="proceedUpdateContact">
+            <soap12:operation soapAction="urn:proceedUpdateContact" style="document" />
+            <wsdl:input>
+                <soap12:body use="literal" />
+            </wsdl:input>
+            <wsdl:output>
+                <soap12:body use="literal" />
+            </wsdl:output>
+            <wsdl:fault name="proceedUpdateContactException">
+                <soap12:fault use="literal" name="proceedUpdateContactException" />
+            </wsdl:fault>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:binding name="EmailValidationServiceHttpBinding" type="ns:EmailValidationServicePortType">
+        <http:binding verb="POST" />
+        <wsdl:operation name="proceedUpdateContact">
+            <http:operation location="proceedUpdateContact" />
+            <wsdl:input>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:input>
+            <wsdl:output>
+                <mime:content type="text/xml" part="parameters" />
+            </wsdl:output>
+        </wsdl:operation>
+    </wsdl:binding>
+    <wsdl:service name="EmailValidationService">
+        <wsdl:port name="EmailValidationServiceHttpsSoap11Endpoint" binding="ns:EmailValidationServiceSoap11Binding">
+            <soap:address location="https://192.168.1.100:9443/services/EmailValidationService.EmailValidationServiceHttpsSoap11Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="EmailValidationServiceHttpsSoap12Endpoint" binding="ns:EmailValidationServiceSoap12Binding">
+            <soap12:address location="https://192.168.1.100:9443/services/EmailValidationService.EmailValidationServiceHttpsSoap12Endpoint/" />
+        </wsdl:port>
+        <wsdl:port name="EmailValidationServiceHttpsEndpoint" binding="ns:EmailValidationServiceHttpBinding">
+            <http:address location="https://192.168.1.100:9443/services/EmailValidationService.EmailValidationServiceHttpsEndpoint/" />
+        </wsdl:port>
+    </wsdl:service>
+</wsdl:definitions>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..6170c1f
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,35 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <!-- sample menu configuration -->
+    <menus>
+        <menu>
+            <id>gaas_account_mgt_menu</id>
+	    <i18n-bundle>org.wso2.carbon.account.mgt.ui.i18n.Resources</i18n-bundle>
+            <i18n-key>account.mgt.menu</i18n-key>            
+            <parent-menu>configure_menu</parent-menu>
+            <link>../account-mgt/account_mgt.jsp</link>
+            <region>region1</region>
+            <order>1</order>
+            <style-class>manage</style-class>
+            <icon>../account-mgt/images/account-mgt-icon.gif</icon>
+            <require-permission>/permission/admin/configure/account</require-permission>
+            <require-not-super-tenant>true</require-not-super-tenant>
+        </menu>
+    </menus>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/JSResources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/JSResources.properties b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/JSResources.properties
new file mode 100644
index 0000000..92f331d
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/JSResources.properties
@@ -0,0 +1,5 @@
+domain.available=Domain is available to register.
+domain.unavailable=Sorry!. The Domain is already registered. Please choose a different domain.
+domain.you.own=Currently you have registered an account with this domain. But you have not verified the ownership to it. 
+domain.validation.failed=Domain validation Failed.
+successfully.validated=The ownership of the domain is succesfully validated.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/Resources.properties b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/Resources.properties
new file mode 100644
index 0000000..ef72bbb
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/account/mgt/ui/i18n/Resources.properties
@@ -0,0 +1,24 @@
+account.mgt.menu=Account
+account.mgt.title=Account Management
+deactivate.account=Deactivate Account
+deactivate.account.title=Deactivate Account
+contact.information=Contact Information
+admin.information=Administrator Profile
+contact.email=Contact Email
+fullname=Full Name
+firstname=First Name
+lastname=Last Name
+update.contact=Update Contact
+update.profile=Update Profile
+validate.contact=Validate Contact
+deactive.account=Deactivate Account
+deactivate.account.msg=You can deactivate your account from here. <b>Caution: This is not undoable by the tenant.</b>
+deactivate.account.btn=Deactivate Account
+validate.domain.title=Validate Domain Ownership
+current.domain=Your Domain
+validate.domain=Validate Now!
+domain.to.validate=Domain to Validate
+successfully.validated=You have successfully validated your domain name.
+usage.plan.information= Usage Plan Information
+select.usage.plan.for.tenant=Select Usage Plan For Tenant
+select.package.message=According to the selected plan, resources will be allocated to you.\n You can update or downgrade your plan later \n according to your requirements. If you need further information on plans, click "Pricing Info".

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/account_mgt.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/account_mgt.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/account_mgt.jsp
new file mode 100644
index 0000000..a43e0f2
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/account_mgt.jsp
@@ -0,0 +1,526 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="org.wso2.carbon.account.mgt.stub.beans.xsd.AccountInfoBean" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.UsagePlanClient" %>
+<%@ page import="org.wso2.carbon.stratos.common.constants.StratosConstants" %>
+<%@ page import="org.wso2.carbon.stratos.common.util.CommonUtil" %>
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.utils.multitenancy.MultitenantConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<link rel="stylesheet" type="text/css" href="../yui/assets/yui.css">
+<link rel="stylesheet" type="text/css" href="../yui/build/menu/assets/skins/sam/menu.css"/>
+<link rel="stylesheet" type="text/css" href="../yui/build/button/assets/skins/sam/button.css"/>
+<link rel="stylesheet" type="text/css"
+      href="../yui/build/container/assets/skins/sam/container.css"/>
+<link rel="stylesheet" type="text/css"
+      href="../yui/build/autocomplete/assets/skins/sam/autocomplete.css"/>
+<link rel="stylesheet" type="text/css" href="../yui/build/editor/assets/skins/sam/editor.css"/>
+<link rel="stylesheet" type="text/css" href="../account-mgt/css/account_mgt.css"/>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="../account-mgt/js/account_mgt.js"></script>
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.account.mgt.ui.i18n.JSResources"
+        request="<%=request%>"/>
+<fmt:bundle basename="org.wso2.carbon.account.mgt.ui.i18n.Resources">
+
+<%
+    if ("true".equals(session.getAttribute("domain-validation-failure"))) {
+        session.removeAttribute("domain-validation-failure");
+%>
+
+<script type="text/javascript">
+    jQuery(document).ready(function() {
+        CARBON.showWarningDialog(jsi18n["domain.validation.failed"]);
+    });
+</script>
+<%
+    }
+    if ("true".equals(session.getAttribute("domain-validation-success"))) {
+        session.removeAttribute("domain-validation-success");
+%>
+
+<script type="text/javascript">
+    jQuery(document).ready(function() {
+        CARBON.showWarningDialog(jsi18n["successfully.validated"]);
+    });
+</script>
+<%
+    }
+
+
+    if ("false".equals(session.getAttribute("temp-domain-available"))) {
+        session.removeAttribute("temp-domain-available");
+%>
+
+<script type="text/javascript">
+    jQuery(document).ready(function() {
+        CARBON.showWarningDialog(jsi18n["domain.unavailable"]);
+    });
+</script>
+<%
+    }
+%>
+<%
+
+    String contactEmail = "";
+    String firstname = "";
+    String lastname = "";
+    String tenantDomain = "";
+    String usagePlan = "";
+    boolean isDomainValidated;
+    boolean isEmailValidated = false;
+    AccountMgtClient client;
+    try {
+        client = new AccountMgtClient(config, session);
+        contactEmail = client.getContact();
+        AccountInfoBean accountInfoBean = client.getFullname();
+        firstname = accountInfoBean.getFirstname();
+        lastname = accountInfoBean.getLastname();
+        if (firstname == null) {
+            firstname = "";
+        }
+        if (lastname == null) {
+            lastname = "";
+        }
+        isDomainValidated = client.isDomainValidated();
+        isEmailValidated = client.isEmailValidated();
+
+
+        if ("true".equals(request.getParameter("isUpdate"))) {
+            usagePlan = request.getParameter("selectedUsagePlan");
+            if (org.wso2.carbon.account.mgt.ui.utils.Util.updateUsagePlan(request, config, session)) {
+%>
+<script type="text/javascript">
+    //        window.location.href="../admin/logout_action.jsp";
+    CARBON.showInfoDialog("Your usage plan has been updated.");
+</script>
+<%
+} else {
+%>
+<script type="text/javascript">
+    //        window.location.href="../admin/logout_action.jsp";
+    CARBON.showInfoDialog("Error occured while updating usage plan.");
+</script>
+<%
+        }
+    }
+    usagePlan = org.wso2.carbon.account.mgt.ui.utils.Util.getUsagePlanName(config, session);
+    if ("true".equals(request.getParameter("isDeactivated"))) {
+        client.deactivate();
+        tenantDomain = (String) session.getAttribute("tenantDomain");
+%>
+
+<script type="text/javascript">
+    //        window.location.href="../admin/logout_action.jsp";
+    CARBON.showInfoDialog("Your account has been deactivated.",
+                         function() {
+                             window.location.href = "../admin/logout_action.jsp"
+                         },
+                         function() {
+                             window.location.href = "../admin/logout_action.jsp"
+                         });
+</script>
+<%
+    }
+} catch (RegistryException e) {
+%>
+<div>Error in getting account management information.</div>
+<%
+        return;
+    }
+
+    String currentDomain = (String) session.getAttribute(MultitenantConstants.TENANT_DOMAIN);
+
+    if (session.getAttribute("submit-firstname") != null) {
+        firstname = (String) session.getAttribute("submit-firstname");
+        session.setAttribute("submit-firstname", null);
+    }
+    if (session.getAttribute("submit-lastname") != null) {
+        lastname = (String) session.getAttribute("submit-lastname");
+        session.setAttribute("submit-lastname", null);
+    }
+
+%>
+
+<carbon:breadcrumb label="resources"
+                   resourceBundle="org.wso2.carbon.account.mgt.ui.i18n.Resources"
+                   topPage="true" request="<%=request%>"/>
+<div id="middle">
+
+<div id="workArea">
+<h2><fmt:message key="account.mgt.title"/></h2>
+
+
+<table class="styledLeft">
+    <thead>
+    <tr>
+        <th><fmt:message key="contact.information"/></th>
+    </tr>
+    </thead>
+    <tbody>
+
+    <tr>
+        <td class="nopadding">
+            <form method="POST" action="update_contact_ajaxprocessor.jsp">
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <tr>
+                        <td width="200px"><fmt:message key="contact.email"/><span
+                                class="required">*</span></td>
+                        <td colspan="2">
+                            <input type="text" name="email" id="email" style="width:400px"
+                                   value="<%=contactEmail%>"/> <span id="busyContact">&nbsp;</span>
+                            <span style="visibility:hidden"
+                                  id="old-email"><%=isEmailValidated ? contactEmail : ""%></span>
+                        </td>
+                    </tr>
+                    <%
+                        if (isEmailValidated) {
+                    %>
+
+                    <tr>
+                        <td></td>
+                        <td colspan="2"><input onclick="updateContact()" type="button"
+                                               value="<fmt:message key="update.contact"/>"/></td>
+                    </tr>
+                    <%
+                    } else {
+                    %>
+                    <tr>
+                        <td colspan="3">
+                            <div class="not-validated"><img src="images/wrong.gif" alt="Validated"/>Your
+                                email is not validated.
+                                Please validate it from here.
+                            </div>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td></td>
+                        <td colspan="2"><input onclick="updateContact()" type="button"
+                                               value="<fmt:message key="validate.contact"/>"/></td>
+                    </tr>
+                    <%
+                        }
+                    %>
+
+                    <tr>
+                        <td colspan="3">
+                            <div class="table-spacer">&nbsp;</div>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </td>
+
+    </tr>
+
+    </tbody>
+</table>
+
+
+<table class="styledLeft">
+    <thead>
+    <tr>
+        <th><fmt:message key="admin.information"/></th>
+    </tr>
+    </thead>
+    <tbody>
+
+    <tr>
+        <td class="nopadding">
+            <form id="update_profile_form" action="update_profile_processor.jsp" method="POST">
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <tr>
+                        <td width="200px"><fmt:message key="firstname"/><span
+                                class="required">*</span></td>
+                        <td colspan="2">
+                            <input type="text" name="firstname" id="firstname" style="width:400px"
+                                   value="<%=firstname%>"/>
+                            <span style="visibility:hidden" id="old-firstname"><%=firstname%></span>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td width="200px"><fmt:message key="lastname"/><span
+                                class="required">*</span></td>
+                        <td colspan="2">
+                            <input type="text" name="lastname" id="lastname" style="width:400px"
+                                   value="<%=lastname%>"/>
+                            <span style="visibility:hidden" id="old-lastname"><%=lastname%></span>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td></td>
+                        <td colspan="2"><input onclick="updateProfile()" type="button"
+                                               value="<fmt:message key="update.profile"/>"/></td>
+                    </tr>
+                    <tr>
+                        <td colspan="3">
+                            <div class="table-spacer">&nbsp;</div>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </td>
+
+    </tr>
+
+    </tbody>
+</table>
+
+
+<table class="styledLeft">
+    <thead>
+    <tr>
+        <th><fmt:message key="validate.domain.title"/></th>
+    </tr>
+    </thead>
+    <tbody>
+
+    <tr>
+        <td class="nopadding">
+            <form onsubmit="return domainSelected();" id="validateDomainForm" method="POST"
+                  action="validate_domain_ajaxprocessor.jsp">
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <tr>
+                        <td width="200px"><fmt:message key="current.domain"/></td>
+                        <td colspan="2"><input readonly="true" type="text" name="domain" id="domain"
+                                               style="width:400px" value="<%=currentDomain%>"/>
+                        </td>
+                    </tr>
+
+                    <%
+                        if (isDomainValidated) {
+                    %>
+                    <tr>
+                        <td colspan="3">
+                            <div class="validated"><img src="images/right.gif" alt="Validated"/> The
+                                ownership of your domain is already validated.
+                            </div>
+                        </td>
+                    </tr>
+
+                    <%
+                    } else {
+                    %>
+                    <tr>
+                        <td colspan="3">
+                            <div class="not-validated"><img src="images/wrong.gif" alt="Validated"/>
+                                The ownership of your
+                                domain is not validated. You can validate it from here.
+                            </div>
+                        </td>
+                    </tr>
+
+                    <tr>
+                        <td></td>
+                        <td colspan="2"><input type="submit"
+                                               value="<fmt:message key="validate.domain"/>"/></td>
+                    </tr>
+                    <tr>
+                        <td colspan="3">
+                            <div class="table-spacer">&nbsp;</div>
+                        </td>
+                    </tr>
+
+                    <%
+                        }
+                    %>
+                    </tbody>
+                </table>
+            </form>
+        </td>
+    </tr>
+
+    </tbody>
+</table>
+
+
+<table class="styledLeft">
+    <thead>
+    <tr>
+        <th><fmt:message key="deactivate.account.title"/></th>
+    </tr>
+    </thead>
+    <tbody>
+
+
+    <tr>
+        <td class="nopadding">
+            <form method="POST" id="deactivate_form" action="account_mgt.jsp">
+                <input type="hidden" name="isDeactivated" value="true"/>
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <tr>
+                        <td colspan="3"><fmt:message key="deactivate.account.msg"/></td>
+                    </tr>
+                    <tr>
+                        <td width="200px"></td>
+                        <td colspan="2"><input onclick="return deactivate('<%=currentDomain%>');"
+                                               type="button"
+                                               value="<fmt:message key="deactivate.account.btn"/>"/>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td colspan="3">
+                            <div class="table-spacer">&nbsp;</div>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </td>
+    </tr>
+
+    </tbody>
+</table>
+
+
+<table class="styledLeft">
+    <thead>
+    <tr>
+        <th><fmt:message key="usage.plan.information"/>
+            <% if (usagePlan.length() > 10) {
+                String planName = usagePlan;
+            %>
+            - Your Current Usage Plan is : <%=planName%>
+            <%}%>
+        </th>
+    </tr>
+    </thead>
+    <tbody>
+
+<script type="text/javascript">
+<%
+    boolean chargeOnRegistration = CommonUtil.isChargedOnRegistration();
+%>
+
+function updatePlan(plan, existingPlan, regTenantDomain) {
+    var newPlan = plan.options[plan.selectedIndex].value;
+    if(newPlan==existingPlan){
+        CARBON.showInfoDialog("Please select the new plan before updating");
+    }else{
+        sessionAwareFunction(function() {
+        CARBON.showConfirmationDialog("Are you sure you want to update your UsagePlan ? "
+                                      , function() {
+
+
+
+
+
+            var submitForm = document.getElementById("usagePlanUpdate_form");
+            submitForm.submit();
+        });
+    }, "Session timed out. Please login again.");
+    }
+}
+</script>
+
+    <tr>
+        <td class="nopadding">
+            <form method="POST" id="usagePlanUpdate_form"
+            <% if (chargeOnRegistration){ %>
+            action="init_payment_ajaxprocessor.jsp"
+            <% } else { %>
+            action="account_mgt.jsp"
+            <% } %>
+            >
+                <input type="hidden" name="isUpdate" value="true"/>
+                <table class="normal-nopadding" cellspacing="0">
+                    <tbody>
+                    <td><fmt:message key="select.usage.plan.for.tenant"/></td>
+                    <td>
+                        <select name="selectedUsagePlan" id="selectedUsagePlan">
+                        </select>
+                        <a href="<%=CommonUtil.getStratosConfig().getUsagePlanURL()%>"
+                           target="_blank">
+                            <b>Pricing Info</b></a>
+                    </td>
+
+
+                    </tr>
+                    <tr>
+                        <td colspan="2"><fmt:message key="select.package.message"/>
+                        </td>
+                    </tr>
+                    <tr>
+                        <td width="200px"></td>
+                        <td colspan="2"><input
+                                onclick="return updatePlan(document.getElementById('selectedUsagePlan'), '<%=usagePlan%>', '<%=currentDomain%>');"
+                                type="button"
+                                value="Update Plan"/>
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+    </tbody>
+</table>
+</div>
+</div>
+</fmt:bundle>
+<script type="text/javascript">
+
+    jQuery(document).ready(
+                          function() {
+                              jQuery.ajax({
+                                  type: 'POST',
+                                  url: 'get_package_info_ajaxprocessor.jsp',
+                                  dataType: 'json',
+                                  data: 'plan=0',
+                                  async: false,
+                                  success: function(data) {
+                                      packageInfo = data;
+                                  },
+                                  error:function (xhr, ajaxOptions, thrownError) {
+                                      CARBON.showErrorDialog('Could not get package information.');
+                                  }
+                              });
+
+                              var charge;
+                              var name;
+                              for (var i = 0; i < packageInfo.length; i++) {
+                                  charge = packageInfo[i].subscriptionCharge;
+                                  name = packageInfo[i].name;
+                                  if (name == '<%=org.wso2.carbon.account.mgt.ui.utils.Util.getUsagePlanName(config, session)%>') {
+                                      option = document.createElement("option");
+                                      option.value = name;
+                                      option.selected = name;
+                                      option.innerHTML = name;
+                                      document.getElementById('selectedUsagePlan').appendChild(option);
+
+                                  }
+                                  else {
+                                      option = document.createElement("option");
+                                      option.value = name;
+                                      option.innerHTML = name
+                                      document.getElementById('selectedUsagePlan').appendChild(option);
+                                  }
+                              }
+                          }
+            );
+</script>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/account_mgt.css
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/account_mgt.css b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/account_mgt.css
new file mode 100644
index 0000000..9dd4170
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/account_mgt.css
@@ -0,0 +1,15 @@
+div.not-validated {
+    color: #f00;
+    padding: 15px 0px 10px 0px;
+}
+
+div.validated {
+    font-color: #058000;
+    padding: 15px 0px 10px 0px;
+}
+
+
+div.table-spacer {
+    margin: 5px;
+    clear:both;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/update_profile.css
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/update_profile.css b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/update_profile.css
new file mode 100644
index 0000000..c3878ae
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/css/update_profile.css
@@ -0,0 +1,29 @@
+body {
+	color:#111111;
+	font-family:"Calibri","Lucida Grande","Lucida Sans","Microsoft Sans Serif","Lucida Sans Unicode","Verdana","Sans-serif","trebuchet ms" !important;
+	font-size:0.75em;
+	font-size-adjust:none;
+	font-style:normal;
+	font-variant:normal;
+	font-weight:normal;
+	line-height:1.25em;
+	background-position: left top;
+	background-repeat: repeat-x;
+	margin: 0px;
+	padding: 0px;
+}
+
+div.clear {
+	clear:both;
+}
+p { }
+
+td { }
+
+a:link { }
+
+a:visited { }
+
+a:hover { }
+
+a:active { }

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/deactivate_account_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/deactivate_account_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/deactivate_account_ajaxprocessor.jsp
new file mode 100644
index 0000000..fabc967
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/deactivate_account_ajaxprocessor.jsp
@@ -0,0 +1,38 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+AccountMgtClient client;
+try {
+    client = new AccountMgtClient(config, session);
+    client.deactivate();
+
+    // redirect to the carbon login page
+    %><script type="text/javascript">
+        CARBON.showInfoDialog("Your account has been deactivated.",
+                function() {window.location.href="../admin/logout_action.jsp"},
+                function() {window.location.href="../admin/logout_action.jsp"});
+    </script><%
+} catch (RegistryException e) {
+%>
+  <div>Error in deactivating the account.</div>
+<%
+}
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/aboutUsagePlans.html
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/aboutUsagePlans.html b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/aboutUsagePlans.html
new file mode 100644
index 0000000..791b867
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/aboutUsagePlans.html
@@ -0,0 +1,104 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>Select Usage Plan For Tenant - User Guide</title>
+  <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all" />
+</head>
+
+<body>
+
+
+ <h1>Select Usage Plan For Tenant</h1>
+
+
+ <h2> <b> Usage Plans(Subscriptions)</b></h2>
+
+<p>
+    According to the usage plan that you selected you will get different volume of service and registry
+    bandwidths other services that available for tenants.By selecting right usage plan that suits
+    your requirements you can get maximum profit
+</p>
+
+
+<h2><b>Multitenancy Free</b></h2>
+<p>
+  This is the free usage plan.You will get limited amount of resources.This package is
+  best suite for evaluation and tests.
+</p>
+ <h2><b>Multitenancy Small</b></h2>
+<p>
+   This package is best suite for small business.
+</p>
+<h2><b>Multitenancy Medium</b></h2>
+<p>
+   This usage plan suites for medium scale business.You will get average amount of resources
+    with this package.
+</p>
+<h2><b>Multitenancy Large</b></h2>
+<p>
+   This is the premium usage plan.You will get maximum resources form this plan.
+   This is best suite to large scale business.
+</p>
+
+<p>
+
+   Usage Plan summery
+<table border="1">
+<tr>
+<td>Usage Plan Name</td>
+<td>Number Of Users</td>
+<td>Registry Bandwidth (Mb) </td>
+<td>Service BandWidth (Mb) </td>
+<td>Cost Per Month ($)</td>
+</tr>
+<tr>
+<td>Multitenancy Free</td>
+<td>5</td>
+<td>10</td>
+<td>10</td>
+<td>10</td>
+</tr>
+<tr>
+<td>Multitenancy Small</td>
+<td>10</td>
+<td>25</td>
+<td>25</td>
+<td>25</td>
+</tr>
+<tr>
+<td>Multitenancy Medium</td>
+<td>20</td>
+<td>100</td>
+<td>100</td>
+<td>100</td>
+</tr>
+<tr>
+<td>Multitenancy Large</td>
+<td>50</td>
+<td>200</td>
+<td>200</td>
+<td>200</td>
+</tr>
+</table> 
+<div><strong>Figure1: Usage Plan Summery Table</strong></div>
+</p>
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/images/account-mgt.png
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/images/account-mgt.png b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/images/account-mgt.png
new file mode 100644
index 0000000..f67777f
Binary files /dev/null and b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/images/account-mgt.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/userguide.html b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/userguide.html
new file mode 100644
index 0000000..fd04465
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/docs/userguide.html
@@ -0,0 +1,44 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+  <title>Stratos Account Managment- User Guide</title>
+  <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all" />
+</head>
+
+<body>
+<h1>Stratos Account Management</h1>
+
+<p>
+You can use this form to
+<ul>
+    <li>Update or validate the contact information</li>
+    <li>Deactivate the account</li>
+    <li>Validate the domain name ownership (If you have not already done it)</li>
+</ul>
+</p>
+
+<p>
+<img src="images/account-mgt.png" alt="Account Management Page"/>
+<div><strong>Figure1: Account Management Page</strong></div>
+</p>
+
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/get_package_info_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/get_package_info_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/get_package_info_ajaxprocessor.jsp
new file mode 100644
index 0000000..8a52783
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/get_package_info_ajaxprocessor.jsp
@@ -0,0 +1,39 @@
+<%--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+--%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.json.JSONArray" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.PackageInfoServiceClient" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+
+<%
+
+    String backendServerUrl = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    ConfigurationContext configContext =
+            (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    PackageInfoServiceClient client = new PackageInfoServiceClient(cookie, backendServerUrl, configContext);
+    JSONArray packageInfoArray = client.getBillingPackagesJsonArray();
+
+    out.write(packageInfoArray.toString());
+%>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/account-mgt-icon.gif
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/account-mgt-icon.gif b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/account-mgt-icon.gif
new file mode 100644
index 0000000..7cd3939
Binary files /dev/null and b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/account-mgt-icon.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/ajax-loader.gif
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/ajax-loader.gif b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/ajax-loader.gif
new file mode 100644
index 0000000..f2a1bc0
Binary files /dev/null and b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/ajax-loader.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/right.gif
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/right.gif b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/right.gif
new file mode 100644
index 0000000..72a64c9
Binary files /dev/null and b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/right.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/wrong.gif
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/wrong.gif b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/wrong.gif
new file mode 100644
index 0000000..77e1f2c
Binary files /dev/null and b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/images/wrong.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/init_payment_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/init_payment_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/init_payment_ajaxprocessor.jsp
new file mode 100644
index 0000000..088fb32
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/init_payment_ajaxprocessor.jsp
@@ -0,0 +1,99 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.json.JSONArray"%>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.register.ui.clients.PackageInfoServiceClient" %>
+<%@ page import="org.wso2.carbon.stratos.common.util.CommonUtil" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="java.util.Collections" %>
+<%@ page import="java.util.Enumeration" %>
+<%@ page import="java.util.Iterator" %>
+<%@ page import="java.util.List" %>
+<%@ page import="java.util.Map" %>
+<%@ page import="org.json.JSONException" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<carbon:jsi18n
+		resourceBundle="org.wso2.carbon.register.ui.i18n.JSResources"
+		request="<%=request%>" />
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="../admin/js/jquery.js"></script>
+<script type="text/javascript" src="../admin/js/jquery.form.js"></script>
+<script type="text/javascript" src="../dialog/js/jqueryui/jquery-ui.min.js"></script>
+<%
+    String tenantDomain = (String) session.getAttribute("tenantDomain");
+    // The actual usage plan the tenant selects in select_usage_plan.jsp
+    String selectedUsagePlan = request.getParameter("selectedUsagePlan");
+    session.setAttribute("selectedUsagePlan", selectedUsagePlan);
+
+    String backendServerUrl = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    ConfigurationContext configContext =
+            (ConfigurationContext)config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    PackageInfoServiceClient client = new PackageInfoServiceClient(cookie, backendServerUrl,configContext);
+    JSONArray packageInfoArray = client.getBillingPackagesJsonArray();
+    String amount = "0";
+
+    for (int i = 0; i < packageInfoArray.length(); i++) {
+        try {
+            if (packageInfoArray.getJSONObject(i).getString("name").equals(selectedUsagePlan)) {
+                amount = packageInfoArray.getJSONObject(i).getString("subscriptionCharge");
+            }
+        } catch (JSONException e) {
+            //
+        }
+    }
+
+    String paypalUrl = CommonUtil.getStratosConfig().getPaypalUrl();
+    String adminConsoleURL = CarbonUIUtil.getAdminConsoleURL(request);
+    adminConsoleURL = adminConsoleURL.substring(0, adminConsoleURL.indexOf("carbon"));
+    String successUrl = adminConsoleURL + "carbon/payment/registration_payment.jsp";
+    String cancelUrl = adminConsoleURL + "carbon/account-mgt/account_mgt.jsp";
+%>
+
+<script type="text/javascript">
+
+
+        var successUrl = '<%=successUrl%>';
+        var cancelUrl = '<%=cancelUrl%>';
+        var amount = '<%=amount%>';
+        var tenantDomain = '<%=tenantDomain%>';
+        jQuery.ajax({
+            type: 'GET',
+            url: '../payment/setEC-ajaxprocessor.jsp',
+            data: 'successUrl=' + successUrl + '&cancelUrl=' + cancelUrl + '&amount=' + amount + '&tenantDomain=' + tenantDomain,
+            dataType: 'json',
+            async: false,
+            success: function(msg) {
+                var resp = msg;
+                if(resp.ack=='Success'){
+                    location.href = '<%=paypalUrl%>' + resp.token;
+                }else{
+                    location.href = cancelUrl;
+                }
+            },
+            error:function () {
+                location.href = cancelUrl;
+            }
+        });
+</script>
\ No newline at end of file


[31/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
new file mode 100644
index 0000000..bae3df9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.jdbc;
+
+import java.sql.Connection;
+
+public class Transaction {
+
+    private static ThreadLocal<Boolean> tStarted = new ThreadLocal<Boolean>() {
+        protected Boolean initialValue() {
+            return false;
+        }
+    };
+
+    private static ThreadLocal<Connection> tConnection = new ThreadLocal<Connection>() {
+        protected Connection initialValue() {
+            return null;
+        }
+    };
+
+    // this is a property that will be specific to embedded registry
+    private static ThreadLocal<Integer> tNestedDepth = new ThreadLocal<Integer>() {
+        protected Integer initialValue() {
+            return 0;
+        }
+    };
+
+    private static ThreadLocal<Boolean> tRollbacked = new ThreadLocal<Boolean>() {
+        protected Boolean initialValue() {
+            return false;
+        }
+    };
+
+    public static boolean isStarted() {
+        if (tStarted.get() == null) {
+            return false;
+        }
+
+        return tStarted.get();
+    }
+
+    public static void setStarted(boolean started) {
+        tStarted.set(started);
+    }
+
+    public static Connection getConnection() {
+        return tConnection.get();
+    }
+
+    public static void setConnection(Connection connection) {
+        if (connection != null) {
+            tStarted.set(true);
+        }
+        tConnection.set(connection);
+    }
+
+    public static void removeConnection() {
+        tStarted.remove();
+        tConnection.remove();
+    }
+
+    // the following two methods will increment and decrement
+    // the transaction depth of the current session
+    public static void incNestedDepth() {
+        int transactionDepth = tNestedDepth.get().intValue();
+        if (transactionDepth == 0) {
+            tStarted.set(true);
+            tRollbacked.set(false);
+        }
+        transactionDepth++;
+        tNestedDepth.set(transactionDepth);
+    }
+
+    public static void decNestedDepth() {
+        int transactionDepth = tNestedDepth.get().intValue();
+        transactionDepth--;
+        tNestedDepth.set(transactionDepth);
+        if (transactionDepth == 0) {
+            tStarted.set(false);
+        }
+    }
+
+    public static int getNestedDepth() {
+        return tNestedDepth.get().intValue();
+    }
+
+
+    public static boolean isRollbacked() {
+        if (tRollbacked.get() == null) {
+            return false;
+        }
+
+        return tRollbacked.get();
+    }
+
+    public static void setRollbacked(boolean rollbacked) {
+        tRollbacked.set(rollbacked);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
new file mode 100644
index 0000000..269beb5
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * This job is run by the scheduled task for
+ * bill generation
+ */
+public class BillingJob implements Job {
+    private static final Log log = LogFactory.getLog(BillingJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+        // first we generate the bill
+        BillingEngine billingEngine =
+                (BillingEngine) jobExecutionContext.getMergedJobDataMap().get(
+                        BillingConstants.BILLING_ENGINE_KEY);
+        SchedulerContext schedulerContext =
+                (SchedulerContext) jobExecutionContext.getMergedJobDataMap().get(
+                        BillingConstants.SCHEDULER_CONTEXT);
+        try {
+            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            long startTime = System.currentTimeMillis();
+            log.info("Bill generation started at " + dateFormat.format(new Date(System.currentTimeMillis())));
+
+            billingEngine.generateBill(schedulerContext);
+
+            log.info("Bill generation completed at " + dateFormat.format(new Date(System.currentTimeMillis())));
+            long timeTaken = System.currentTimeMillis() - startTime;
+            log.info("Time taken for bill generation: " + timeTaken/1000 + "s");
+        } catch (BillingException e) {
+            String msg = "Error in generating the bill";
+            log.error(msg, e);
+            throw new JobExecutionException(msg, e);
+        }
+        
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
new file mode 100644
index 0000000..c589431
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.TaskSchedulerFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+
+import java.util.*;
+
+public class BillingScheduler {
+    private static Log log = LogFactory.getLog(BillingScheduler.class);
+    private TaskScheduler taskScheduler;
+    private BillingTaskConfiguration billingTaskConfig;
+    private BillingEngine billingEngine;
+
+    public BillingScheduler(BillingEngine billingEngine,
+                            BillingTaskConfiguration billingTaskConfiguration) {
+        this.billingTaskConfig = billingTaskConfiguration;
+        this.billingEngine = billingEngine;
+        taskScheduler = TaskSchedulerFactory.getTaskScheduler(TaskConstants.TASK_SCHEDULER);
+        if (!taskScheduler.isInitialized()) {
+            Properties properties = new Properties();
+            taskScheduler.init(properties);
+        }
+    }
+
+    public SchedulerContext createScheduleContext() throws BillingException {
+        SchedulerContext schedulerContext = new SchedulerContext();
+        ScheduleHelper triggerCalculator = billingTaskConfig.getScheduleHelper();
+        if (triggerCalculator != null) {
+            triggerCalculator.invoke(schedulerContext);
+        }
+        return schedulerContext;
+    }
+
+    public void scheduleNextCycle(SchedulerContext schedulerContext) {
+
+        String taskName = UUIDGenerator.generateUUID();
+
+        TaskDescription taskDescription = new TaskDescription();
+        taskDescription.setName(taskName);
+        taskDescription.setGroup(BillingConstants.GROUP_ID);
+        taskDescription.setCron(schedulerContext.getCronString());
+        
+        Map<String, Object> resources = new HashMap<String, Object>();
+        resources.put(BillingConstants.TASK_NAME_KEY, taskName);
+        resources.put(BillingConstants.SCHEDULER_KEY, this);
+        resources.put(BillingConstants.BILLING_ENGINE_KEY, billingEngine);
+        resources.put(BillingConstants.SCHEDULER_CONTEXT, schedulerContext);
+        taskScheduler.scheduleTask(taskDescription, resources, BillingJob.class);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
new file mode 100644
index 0000000..4eb8cad
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+import org.wso2.carbon.billing.core.BillingException;
+
+import java.util.Map;
+
+public interface ScheduleHelper {
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException;
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
new file mode 100644
index 0000000..3d450f9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler;
+
+/**
+ * This class is used to store attributes necessary in
+ * scheduling bill generation
+ */
+public class SchedulerContext {
+
+    private String cronString;
+
+    public String getCronString() {
+        return cronString;
+    }
+
+    public void setCronString(String cronString) {
+        this.cronString = cronString;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
new file mode 100644
index 0000000..fadbb2c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler.scheduleHelpers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+import java.util.TimeZone;
+
+public class MonthlyScheduleHelper implements ScheduleHelper {
+    private static final Log log = LogFactory.getLog(MonthlyScheduleHelper.class);
+
+    private static final String CRON_KEY = "cron";
+    private static final String TIME_ZONE_KEY = "timeZone";
+    private static final String DEFAULT_TIMEZONE = "GMT-8:00";
+
+    private String cron;
+    private TimeZone timeZone;
+    
+
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException {
+        String timeZoneStr = triggerCalculatorConfig.get(TIME_ZONE_KEY);
+        if (timeZoneStr == null) {
+            timeZoneStr = DEFAULT_TIMEZONE;
+        }
+        timeZone = TimeZone.getTimeZone(timeZoneStr);
+        //Timezone is important when comparing dates in sql queries
+        DataAccessObject.TIMEZONE = timeZoneStr;
+        
+        cron = triggerCalculatorConfig.get(CRON_KEY);
+        log.debug("Cron string: " + cron);
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        schedulerContext.setCronString(cron);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
new file mode 100644
index 0000000..00e078a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.scheduler.scheduleHelpers;
+
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+
+public class OneTimeScheduleHelper implements ScheduleHelper {
+
+    public void init(Map<String, String> triggerCalculatorConfig) throws BillingException {
+        // nothing to init
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        // nothing much to do
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
new file mode 100644
index 0000000..37df06b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.utilities;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Utility class for customer related operations
+ */
+public class CustomerUtils {
+    private static Log log = LogFactory.getLog(CustomerUtils.class);
+
+    /**
+     * Fill the customer object with data retrieved from the tenant manager
+     * @param customerId
+     * @param customer
+     * @throws BillingException
+     */
+    public static void fillCustomerData(int customerId, Customer customer) throws BillingException{
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            customer.setId(customerId);
+            customer.setName(tenant.getDomain());
+            customer.setStartedDate(tenant.getCreatedDate());
+            customer.setEmail(tenant.getEmail());
+            //customer.setAddress(); //we dont have the address
+        }catch (Exception e){
+            String msg = "Failed to fill the data for customer: " +
+                    customer.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    /**
+     * Get the customer by tenant id (customer id) using the realm service
+     * @param customerId
+     * @return
+     * @throws BillingException
+     */
+    public static Customer getCustomer(int customerId) throws BillingException{
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        Customer customer = null;
+
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            if(tenant!=null){
+                customer = new Customer();
+                customer.setId(customerId);
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+            }
+        } catch (Exception e){
+            String msg = "Failed to get customer for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customer;
+    }
+
+    /**
+     * Get the tenantId (customer id) of a customer from the realm service
+     * @param customerName
+     * @return
+     * @throws BillingException
+     */
+    public static int getCustomerId(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        int tenantId;
+        try{
+            tenantId = tenantManager.getTenantId(customerName);
+        }catch (Exception e){
+            String msg = "Failed to get tenant for domain: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return tenantId;
+    }
+
+    /**
+     * Get all the customers ( fill customers from tenants)
+     * @return
+     * @throws BillingException
+     */
+    public static List<Customer> getAllCustomers() throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            Tenant[] tenants = tenantManager.getAllTenants();
+            if(tenants!=null && tenants.length>0){
+                for(Tenant tenant : tenants){
+                    Customer customer = new Customer();
+                    customer.setId(tenant.getId());
+                    customer.setName(tenant.getDomain());
+                    customer.setStartedDate(tenant.getCreatedDate());
+                    customer.setEmail(tenant.getEmail());
+                    //customer.setAddress(); //no address yet
+                    customers.add(customer);
+                }
+            }
+        } catch (Exception e){
+            String msg = "Failed to get all the customers.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
new file mode 100644
index 0000000..78ea40d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
@@ -0,0 +1,34 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.billing.core.utilities;
+
+import javax.sql.DataSource;
+
+public class DataSourceHolder {
+    public static DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public static void setDataSource(DataSource dataSource) {
+        DataSourceHolder.dataSource = dataSource;
+    }
+
+    private static DataSource dataSource;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
new file mode 100644
index 0000000..500adb5
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class CarbonHome1Test extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "carbonHome1TestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+//        SessionDescription sessionDescription = new SessionDescription();
+//        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        /*RuleServerManager ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        */
+//        OMElement config = TestUtils.loadConfigXML();
+////        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+//        RuleServerManager ruleServerManager = new RuleServerManager();
+//        ruleServerManager.init(ruleServerConfiguration);
+
+        //Util.setRuleEngineConfigService(ruleServerManager);
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testDataSource() throws BillingException {
+        TestUtils.deleteAllTables();
+        Item item = new Item();
+        item.setName("myitem-0");
+        item.setCost(new Cash("$50.23"));
+        item.setDescription("Just a simple item");
+
+        Item accessedItem;
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            int itemId;
+            List<Item> items = billingEngine.getItemsWithName(item.getName());
+            for (Item existingItem : items) {
+                //billingEngine.deleteItem(existingItem.getId());
+            }
+            itemId = billingEngine.addItem(item);
+            accessedItem = billingEngine.getItem(itemId);
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+        assertEquals("Item name", accessedItem.getName(), item.getName());
+        assertEquals("Item description", accessedItem.getDescription(), item.getDescription());
+        assertEquals("Item cost", accessedItem.getCost().serializeToString(), item.getCost().serializeToString());
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$1.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+        for (int i = 0; i < customers.size(); i++) {
+            Customer customer = customers.get(i);
+            Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CashTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CashTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CashTest.java
new file mode 100644
index 0000000..9ddc2d1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CashTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+public class CashTest extends TestCase {
+    public void testCash() throws BillingException {
+        successCase("$20.58", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 58);
+        successCase("$20.5", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 50);
+        successCase("$20.05", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 5);
+        successCase("20.05", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 5);
+        successCase("20", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 0);
+        successCase("20.0", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 20, 0);
+        successCase("-20.0", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 20, 0);
+        successCase("$-21.5", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 50);
+        successCase("$-0.05", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 0, 5);
+
+        failCase("2343x");
+        failCase("20.");
+        failCase("34.34.34");
+        failCase("34.2343");
+        failCase("34x.23");
+        failCase("34.2x");
+        failCase("$-.05");
+
+        // always putting
+        checkSerialize("$5.8", "$5.80");
+        checkSerialize("0.5", "$0.50");
+        checkSerialize("$-3", "$-3.00");
+        checkSerialize("$-2.5", "$-2.50");
+        checkSerialize("-0.5", "$-0.50");
+
+        // checking some adds
+        checkAdd("3.54", "3.34", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 6, 88);
+        checkAdd("3.54", "3.6", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 7, 14);
+        checkAdd("3.8", "-5.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 2, 0);
+        checkAdd("-23.8", "2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 0);
+        checkAdd("-23.8", "-2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 26, 60);
+
+
+        checkSustract("3.54", "3.34", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 0, 20);
+        checkSustract("3.54", "3.6", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 0, 6);
+        checkSustract("3.8", "-5.8", Cash.CURRENCY_USD, Cash.Sign.POSITIVE, 9, 60);
+        checkSustract("-23.8", "2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 26, 60);
+        checkSustract("-23.8", "-2.8", Cash.CURRENCY_USD, Cash.Sign.NEGATIVE, 21, 0);
+    }
+
+    private void checkAdd(String cashA, String cashB, String currency,
+                          Cash.Sign sign, int wholeNumber, int decimalNumber) throws BillingException {
+        successCase(Cash.add(new Cash(cashA), new Cash(cashB)).serializeToString(),
+                currency, sign, wholeNumber, decimalNumber);
+    }
+
+    private void checkSustract(String cashA, String cashB, String currency,
+                               Cash.Sign sign, int wholeNumber, int decimalNumber) throws BillingException {
+        successCase(Cash.subtract(new Cash(cashA), new Cash(cashB)).serializeToString(),
+                currency, sign, wholeNumber, decimalNumber);
+    }
+
+    private void checkSerialize(String cashStr, String cashStrShouldBe) throws BillingException {
+        Cash cash = new Cash(cashStr);
+        assertEquals("Cash string should be " + cashStrShouldBe, cash.serializeToString(), cashStrShouldBe);
+    }
+
+    private void successCase(String cashString, String currency, Cash.Sign sign, int wholeNumber, int decimalNumber)
+            throws BillingException {
+        Cash cash = new Cash(cashString);
+        boolean success = currency.equals(cash.getCurrency()) &&
+                sign == cash.getSign() &&
+                wholeNumber == cash.getWholeNumber() &&
+                decimalNumber == cash.getDecimalNumber();
+        assertTrue(cashString + " failed", success);
+    }
+
+    public void failCase(String cashString) {
+        boolean gotError;
+        try {
+            new Cash(cashString);
+            gotError = false;
+        } catch (BillingException e) {
+            gotError = true;
+        }
+        assertTrue(cashString + "is not failed (should have failed)", gotError);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
new file mode 100644
index 0000000..6ac08d6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.Map;
+
+public class FiveSecondTriggerCalculator implements ScheduleHelper {
+    private int countUpToLimit;
+    private static int count;
+
+    public void init(Map<String, String> triggerCalculatorConfig) {
+        String countUpToStr = triggerCalculatorConfig.get("countUpToLimit");
+        countUpToLimit = Integer.parseInt(countUpToStr);
+        count = 0; // obviously this is not thread-safe.
+        // nothing to init
+    }
+
+    public void invoke(SchedulerContext schedulerContext) throws BillingException {
+        if (count >= countUpToLimit) {
+            //schedulerContext.setNextTriggerInterval(-1);
+            return;
+        }
+        //long currentTime = System.currentTimeMillis();
+        //schedulerContext.setNextTriggerInterval(5000);
+        count++;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
new file mode 100644
index 0000000..a5e9bf2
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+
+import java.util.Map;
+
+public class FiveSecondTriggerTester implements BillingHandler {
+    private static int count;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to init   
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        count++;
+    }
+
+    public static int getCount() {
+        return count;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
new file mode 100644
index 0000000..2cb029f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.handlers.EmailSendingHandler;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.*;
+
+public class InvoiceMsgTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "ruleTestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+
+        /*RuleEngineConfigService recf = new
+        RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+
+        Customer customer = customers.get(0);
+        Invoice invoice = billingEngine.getLastInvoice(customer);
+
+        Map<String, String> mailParameters =
+                EmailSendingHandler.deriveInvoiceMailParameters(invoice);
+
+        assertEquals(mailParameters.get("total-cost"), "$0.20");
+        assertEquals(mailParameters.get("total-payments"), "$5.50");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
new file mode 100644
index 0000000..54dc574
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+import org.wso2.carbon.billing.core.scheduler.scheduleHelpers.MonthlyScheduleHelper;
+
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TimeZone;
+
+public class MonthlyTriggerCalculatorTest extends TestCase {
+    @Override
+    public void setUp() {
+        // nothing to setup here
+    }
+
+    public void testNextTriggerInterval() throws BillingException {
+        nextMonthFirstDate("1", 1999, Calendar.DECEMBER, 2, 2000, Calendar.JANUARY, 1, 1999,
+                Calendar.NOVEMBER, 1, 1999, Calendar.NOVEMBER, 30, "1999-November");
+        nextMonthFirstDate("1", 2009, Calendar.DECEMBER, 2, 2010, Calendar.JANUARY, 1, 2009,
+                Calendar.NOVEMBER, 1, 2009, Calendar.NOVEMBER, 30, "2009-November");
+        nextMonthFirstDate("1", 2009, Calendar.DECEMBER, 31, 2010, Calendar.JANUARY, 1, 2009,
+                Calendar.NOVEMBER, 1, 2009, Calendar.NOVEMBER, 30, "2009-November");
+        nextMonthFirstDate("15", 2010, Calendar.FEBRUARY, 8, 2010, Calendar.MARCH, 15, 2010,
+                Calendar.JANUARY, 15, 2010, Calendar.FEBRUARY, 14, "2010-January");
+    }
+
+    private void nextMonthFirstDate(String triggerOn, int someYear, int someMonth, int someDay,
+                                    int nextMonthFirstDateYear, int nextMonthFirstDateMonth,
+                                    int nextMonthFirstDateDay, int durationStartYear,
+                                    int durationStartMonth, int durationStartDay,
+                                    int durationEndYear, int durationEndMonth, int durationEndDay,
+                                    String yearMonthString) throws BillingException {
+        Calendar someCalender = Calendar.getInstance();
+        someCalender.set(someYear, someMonth, someDay);
+        long someDateTimeStamp = someCalender.getTimeInMillis();
+
+        Map<String, String> args = new HashMap<String, String>();
+        String timeZoneStr = "GMT-8:00";
+        TimeZone timeZone = TimeZone.getTimeZone(timeZoneStr);
+        args.put("timeZone", timeZoneStr);
+        args.put("dayToTriggerOn", triggerOn);
+        args.put("hourToTriggerOn", "0");
+        MonthlyScheduleHelper monthlyTriggerCalculator = new MonthlyScheduleHelper();
+        monthlyTriggerCalculator.init(args);
+
+        SchedulerContext schedulerContext = new SchedulerContext();
+        //monthlyTriggerCalculator.invoke(schedulerContext, someDateTimeStamp);
+
+        //long nextMonthFirstTimeStampDuration = schedulerContext.getNextTriggerInterval();
+
+        //long durationStart = schedulerContext.getCurrentDurationStart();
+        //long durationEnd = schedulerContext.getCurrentDurationEnd();
+        //String realMonthStr = schedulerContext.getDurationString();
+
+        Calendar nextMonthFirstCalendar = Calendar.getInstance(timeZone);
+        //nextMonthFirstCalendar.setTimeInMillis(someDateTimeStamp + nextMonthFirstTimeStampDuration);
+
+        assertEquals("Year should be " + nextMonthFirstDateYear,
+                nextMonthFirstCalendar.get(Calendar.YEAR), nextMonthFirstDateYear);
+        assertEquals("Month should be " + nextMonthFirstDateMonth,
+                nextMonthFirstCalendar.get(Calendar.MONTH), nextMonthFirstDateMonth);
+        assertEquals("Date should be " + nextMonthFirstDateDay,
+                nextMonthFirstCalendar.get(Calendar.DAY_OF_MONTH), nextMonthFirstDateDay);
+
+        Calendar durationStartCalendar = Calendar.getInstance(timeZone);
+        //durationStartCalendar.setTimeInMillis(durationStart);
+
+        assertEquals("Year should be " + durationStartYear,
+                durationStartCalendar.get(Calendar.YEAR), durationStartYear);
+        assertEquals("Month should be " + durationStartMonth,
+                durationStartCalendar.get(Calendar.MONTH), durationStartMonth);
+        assertEquals("Date should be " + durationStartDay,
+                durationStartCalendar.get(Calendar.DAY_OF_MONTH), durationStartDay);
+
+        Calendar durationEndCalendar = Calendar.getInstance(timeZone);
+        //durationEndCalendar.setTimeInMillis(durationEnd);
+
+        assertEquals("Year should be " + durationEndYear, durationEndCalendar.get(Calendar.YEAR),
+                durationEndYear);
+        assertEquals("Month should be " + durationEndMonth,
+                durationEndCalendar.get(Calendar.MONTH), durationEndMonth);
+        assertEquals("Date should be " + durationEndDay,
+                durationEndCalendar.get(Calendar.DAY_OF_MONTH), durationEndDay);
+
+        //assertEquals("YearMonth String should be equal", realMonthStr, yearMonthString);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/RuleTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
new file mode 100644
index 0000000..126939f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class RuleTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "ruleTestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        /*RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome1";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        billingEngine.generateBill();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+        for (int i = 0; i < customers.size(); i++) {
+            Customer customer = customers.get(i);
+            Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TestUtils.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
new file mode 100644
index 0000000..395d86b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import java.io.*;
+
+public class TestUtils {
+
+    private static final String RULE_COMPONENT_CONF = "rule-component.conf";
+
+    public static void deleteAllTables() throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        boolean succeeded = false;
+        try {
+            dataAccessObject.beginTransaction();
+            /*dataAccessObject.deleteInvoiceSubscriptionItems();
+            dataAccessObject.deleteInvoiceSubscriptions();
+            dataAccessObject.deletePaymentSubscriptions();
+            dataAccessObject.deletePayments();
+            dataAccessObject.deleteInvoice();
+            dataAccessObject.deleteSubscribers();
+            dataAccessObject.deleteItems();
+            dataAccessObject.deleteCustomers();
+            */
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                dataAccessObject.commitTransaction();
+            } else {
+                dataAccessObject.rollbackTransaction();
+            }
+        }
+    }
+
+    public static OMElement loadConfigXML() throws Exception {
+
+        String carbonHome = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH);
+        String path = carbonHome + File.separator + RULE_COMPONENT_CONF;
+        BufferedInputStream inputStream = null;
+        try {
+            File file = new File(path);
+            if (!file.exists()) {
+                inputStream = new BufferedInputStream(
+                        new ByteArrayInputStream("<RuleServer/>".getBytes()));
+            } else {
+                inputStream = new BufferedInputStream(new FileInputStream(file));
+            }
+            XMLStreamReader parser = XMLInputFactory.newInstance().
+                    createXMLStreamReader(inputStream);
+            StAXOMBuilder builder = new StAXOMBuilder(parser);
+            return builder.getDocumentElement();
+        } finally {
+            try {
+                if (inputStream != null) {
+                    inputStream.close();
+                }
+            } catch (IOException ignored) {
+            }
+        }
+    }
+}


[51/52] [partial] git commit: initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache


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

Branch: refs/heads/master
Commit: c1efa3931a823dec7b571473566c1b5ed9d2facd
Parents: 
Author: Your Name <yo...@example.com>
Authored: Sat Jun 29 00:35:24 2013 +0530
Committer: Lakmal Warusawithana <la...@wso2.com>
Committed: Sat Jun 29 11:46:22 2013 +0530

----------------------------------------------------------------------
 .../4.1.0/pom.xml                               |  200 ++
 .../autoscaler/service/IAutoscalerService.java  |  111 +
 .../exception/AutoscalerServiceException.java   |   32 +
 .../exception/DeserializationException.java     |   32 +
 .../MalformedConfigurationFileException.java    |   32 +
 .../exception/NoInstanceFoundException.java     |   38 +
 .../exception/SerializationException.java       |   32 +
 .../service/impl/AutoscalerServiceImpl.java     | 1388 ++++++++++
 .../internal/AutoscalerServiceDSComponent.java  |   29 +
 .../autoscaler/service/io/Deserializer.java     |   67 +
 .../autoscaler/service/io/Serializer.java       |   60 +
 .../service/jcloud/ComputeServiceBuilder.java   |   64 +
 .../service/util/AutoscalerConstant.java        |   72 +
 .../autoscaler/service/util/IaasContext.java    |  389 +++
 .../autoscaler/service/util/IaasProvider.java   |  140 +
 .../service/util/InstanceContext.java           |   92 +
 .../service/util/ServiceTemplate.java           |   83 +
 .../xml/ElasticScalerConfigFileReader.java      |  556 ++++
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../service/util/IaasContextComparatorTest.java |   97 +
 .../service/util/IaasContextTest.java           |  112 +
 .../xml/ElasticScalerConfigFileReaderTest.java  |   59 +
 .../test/resources/elastic-scaler-config.xml    |   66 +
 .../4.1.3/pom.xml                               |  133 +
 .../callables/AppNodeSanityCheckCallable.java   |   84 +
 .../callables/AutoscaleDeciderCallable.java     |  242 ++
 .../callables/InstanceCountCallable.java        |   77 +
 .../callables/PendingInstanceCountCallable.java |   64 +
 .../callables/RunningInstanceCountCallable.java |   67 +
 .../clients/CloudControllerClient.java          |   65 +
 .../clients/CloudControllerOsgiClient.java      |   81 +
 .../clients/CloudControllerStubClient.java      |   92 +
 .../lbautoscale/context/AppDomainContext.java   |  169 ++
 .../context/LoadBalancerContext.java            |  103 +
 .../AutoscalerTaskServiceComponent.java         |  328 +++
 .../lbautoscale/internal/RegistryManager.java   |   51 +
 .../mediators/AutoscaleInMediator.java          |  173 ++
 .../mediators/AutoscaleOutMediator.java         |   77 +
 .../check/PendingInstancesStateChecker.java     |  147 +
 .../check/TerminatingInstancesStateChecker.java |   88 +
 .../task/AutoscalerTaskInitializer.java         |   47 +
 .../task/AutoscalerTaskMgmtAdminService.java    |  345 +++
 .../lbautoscale/task/AutoscalingJob.java        |   65 +
 .../task/ServiceRequestsInFlightAutoscaler.java |  525 ++++
 .../lbautoscale/task/TaskSchedulingManager.java |  185 ++
 .../lbautoscale/util/AutoscaleConstants.java    |   65 +
 .../lbautoscale/util/AutoscaleUtil.java         |  356 +++
 .../util/AutoscalerTaskDSHolder.java            |  129 +
 ...rg.apache.synapse.config.xml.MediatorFactory |    2 +
 ...apache.synapse.config.xml.MediatorSerializer |    2 +
 .../src/main/resources/synapse-load-average.xml |  138 +
 .../resources/synapse-messages-in-flight.xml    |  135 +
 .../synapse-service-messages-in-flight.xml      |  108 +
 .../lbautoscale/AppDomainContextsTest.java      |  105 +
 .../ServiceRequestsInFlightAutoscalerTest.java  |   29 +
 .../4.1.3/src/test/resources/loadbalancer.conf  |   50 +
 .../org.wso2.carbon.lb.endpoint/4.1.3/pom.xml   |  107 +
 .../carbon/lb/endpoint/EndpointConstants.java   |   28 +
 .../carbon/lb/endpoint/EndpointDeployer.java    |   68 +
 ...TenantAwareLoadBalanceEndpointException.java |   36 +
 .../TenantLoadBalanceMembershipHandler.java     |  190 ++
 .../lb/endpoint/builder/TopologySyncher.java    |  142 +
 .../manager/ClusterDomainManagerImpl.java       |  227 ++
 .../TenantAwareLoadBalanceEndpoint.java         |  513 ++++
 .../group/mgt/GroupMgtAgentBuilder.java         |   62 +
 .../LoadBalanceEndpointServiceComponent.java    |  394 +++
 .../lb/endpoint/internal/RegistryManager.java   |   51 +
 .../endpoint/subscriber/TopicHealthChecker.java |   67 +
 .../endpoint/subscriber/TopologyListener.java   |   28 +
 .../endpoint/subscriber/TopologySubscriber.java |   77 +
 .../carbon/lb/endpoint/util/ConfigHolder.java   |  189 ++
 .../lb/endpoint/util/TopologyConstants.java     |   13 +
 .../org.wso2.carbon.lb.common/4.1.3/pom.xml     |  115 +
 .../wso2/carbon/lb/common/cache/LRUCache.java   |  100 +
 .../carbon/lb/common/cache/URLMappingCache.java |   44 +
 .../common/conf/LoadBalancerConfiguration.java  | 1205 +++++++++
 .../LoadBalancerConfigurationDSComponent.java   |   46 +
 .../carbon/lb/common/conf/structure/Node.java   |  355 +++
 .../lb/common/conf/structure/NodeBuilder.java   |  139 +
 .../carbon/lb/common/conf/util/Constants.java   |   49 +
 .../carbon/lb/common/conf/util/HostContext.java |  160 ++
 .../conf/util/LoadBalancerConfigUtil.java       |  288 ++
 .../common/conf/util/TenantDomainContext.java   |   79 +
 .../conf/util/TenantDomainRangeContext.java     |  149 +
 .../mgt/SubDomainAwareGroupManagementAgent.java |   57 +
 .../RequestTokenReplicationCommand.java         |   72 +
 .../LoadBalancerConfigurationService.java       |   79 +
 .../LoadBalancerConfigurationServiceImpl.java   |   61 +
 .../carbon/lb/common/util/DomainMapping.java    |   22 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../test/AgentPersistenceManagerTest.java       |  267 ++
 .../test/LoadBalancerConfigurationTest.java     |  169 ++
 .../carbon/lb/common/test/NodeBuilderTest.java  |  123 +
 .../4.1.3/src/test/resources/loadbalancer.conf  |   64 +
 .../4.1.3/src/test/resources/loadbalancer1.conf |   39 +
 .../4.1.3/src/test/resources/loadbalancer2.conf |   30 +
 .../4.1.3/src/test/resources/testng.xml         |   15 +
 components/load-balancer/pom.xml                |   74 +
 .../2.1.0/pom.xml                               |   90 +
 .../mgt/ui/clients/AccountMgtClient.java        |  176 ++
 .../mgt/ui/clients/EmailValidationClient.java   |   95 +
 .../ui/clients/PackageInfoServiceClient.java    |   97 +
 .../account/mgt/ui/clients/UsagePlanClient.java |  104 +
 .../wso2/carbon/account/mgt/ui/utils/Util.java  |  117 +
 .../src/main/resources/AccountMgtService.wsdl   |  628 +++++
 .../main/resources/EmailValidationService.wsdl  |   95 +
 .../src/main/resources/META-INF/component.xml   |   35 +
 .../account/mgt/ui/i18n/JSResources.properties  |    5 +
 .../account/mgt/ui/i18n/Resources.properties    |   24 +
 .../resources/web/account-mgt/account_mgt.jsp   |  526 ++++
 .../web/account-mgt/css/account_mgt.css         |   15 +
 .../web/account-mgt/css/update_profile.css      |   29 +
 .../deactivate_account_ajaxprocessor.jsp        |   38 +
 .../web/account-mgt/docs/aboutUsagePlans.html   |  104 +
 .../web/account-mgt/docs/images/account-mgt.png |  Bin 0 -> 39610 bytes
 .../web/account-mgt/docs/userguide.html         |   44 +
 .../get_package_info_ajaxprocessor.jsp          |   39 +
 .../web/account-mgt/images/account-mgt-icon.gif |  Bin 0 -> 1041 bytes
 .../web/account-mgt/images/ajax-loader.gif      |  Bin 0 -> 673 bytes
 .../resources/web/account-mgt/images/right.gif  |  Bin 0 -> 924 bytes
 .../resources/web/account-mgt/images/wrong.gif  |  Bin 0 -> 976 bytes
 .../account-mgt/init_payment_ajaxprocessor.jsp  |   99 +
 .../resources/web/account-mgt/js/account_mgt.js |  214 ++
 .../update_contact_ajaxprocessor.jsp            |   35 +
 .../account-mgt/update_profile_processor.jsp    |   62 +
 .../web/account-mgt/update_verifier.jsp         |   56 +
 ...update_verifier_redirector_ajaxprocessor.jsp |   30 +
 .../validate_domain_ajaxprocessor.jsp           |   29 +
 .../validation_success_ajaxprocessor.jsp        |   49 +
 .../org.wso2.carbon.account.mgt/2.1.0/pom.xml   |   88 +
 .../account/mgt/beans/AccountInfoBean.java      |   40 +
 .../internal/AccountMgtServiceComponent.java    |  139 +
 .../account/mgt/services/AccountMgtService.java |  416 +++
 .../mgt/services/EmailValidationService.java    |  153 ++
 .../org/wso2/carbon/account/mgt/util/Util.java  |  173 ++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |   80 +
 components/stratos/account-mgt/pom.xml          |   41 +
 .../org.wso2.carbon.adc.mgt.cli/2.1.3/pom.xml   |  124 +
 .../2.1.3/src/main/assembly/src.xml             |   33 +
 .../org/wso2/carbon/adc/mgt/cli/CliTool.java    |   73 +
 .../org/wso2/carbon/adc/mgt/cli/Command.java    |   64 +
 .../wso2/carbon/adc/mgt/cli/CommandContext.java |   85 +
 .../adc/mgt/cli/CommandLineApplication.java     |  187 ++
 .../carbon/adc/mgt/cli/CommandLineService.java  |  553 ++++
 .../carbon/adc/mgt/cli/StratosApplication.java  |  501 ++++
 .../adc/mgt/cli/StratosCommandContext.java      |   28 +
 .../cli/commands/AddDomainMappingCommand.java   |   84 +
 .../adc/mgt/cli/commands/CartridgesCommand.java |   68 +
 .../adc/mgt/cli/commands/ExitCommand.java       |   67 +
 .../adc/mgt/cli/commands/HelpCommand.java       |   70 +
 .../adc/mgt/cli/commands/InfoCommand.java       |   72 +
 .../adc/mgt/cli/commands/ListCommand.java       |  120 +
 .../adc/mgt/cli/commands/PoliciesCommand.java   |   68 +
 .../commands/RemoveDomainMappingCommand.java    |   72 +
 .../adc/mgt/cli/commands/SubscribeCommand.java  |  205 ++
 .../adc/mgt/cli/commands/SyncCommand.java       |   73 +
 .../mgt/cli/commands/UnsubscribeCommand.java    |  127 +
 .../adc/mgt/cli/completer/CommandCompleter.java |  130 +
 .../adc/mgt/cli/exception/CommandException.java |   36 +
 .../carbon/adc/mgt/cli/utils/CliConstants.java  |  111 +
 .../carbon/adc/mgt/cli/utils/CliMessages.java   |    0
 .../adc/mgt/cli/utils/CommandLineUtils.java     |   91 +
 .../carbon/adc/mgt/cli/utils/RowMapper.java     |   20 +
 .../src/main/resources/Resources.properties     |   25 +
 .../2.1.3/src/main/resources/log4j.properties   |   15 +
 .../2.1.3/src/main/resources/wso2carbon.jks     |  Bin 0 -> 33260 bytes
 .../2.1.1/pom.xml                               |   87 +
 .../service/RepositorySynchronizer.java         |   37 +
 .../src/main/webapp/WEB-INF/cxf-servlet.xml     |   34 +
 .../2.1.1/src/main/webapp/WEB-INF/web.xml       |   49 +
 .../2.1.1/src/main/webapp/servicelist.css       |  117 +
 .../org.wso2.carbon.adc.mgt/2.1.3/pom.xml       |  134 +
 .../2.1.3/src/conf/cartridge-config.properties  |   38 +
 .../2.1.3/src/conf/tenant-resource-policy.xml   |    1 +
 .../adc/mgt/client/CartridgeAgentClient.java    |   39 +
 .../client/CloudControllerServiceClient.java    |   94 +
 .../carbon/adc/mgt/client/RegistryClient.java   |  112 +
 .../adc/mgt/custom/domain/RegistryManager.java  |  106 +
 .../adc/mgt/dao/CartridgeSubscription.java      |  186 ++
 .../wso2/carbon/adc/mgt/dao/DataCartridge.java  |   49 +
 .../wso2/carbon/adc/mgt/dao/PortMapping.java    |   56 +
 .../org/wso2/carbon/adc/mgt/dao/Repository.java |   56 +
 .../adc/mgt/dao/RepositoryCredentials.java      |   27 +
 .../org/wso2/carbon/adc/mgt/dns/DNSManager.java |   86 +
 .../org/wso2/carbon/adc/mgt/dto/AppRepo.java    |   85 +
 .../org/wso2/carbon/adc/mgt/dto/Cartridge.java  |  198 ++
 .../carbon/adc/mgt/dto/CartridgeDetail.java     |    0
 .../adc/mgt/dto/CartridgeInformation.java       |    0
 .../carbon/adc/mgt/dto/CartridgeWrapper.java    |   49 +
 .../org/wso2/carbon/adc/mgt/dto/Policy.java     |  145 +
 .../carbon/adc/mgt/dto/PolicyDefinition.java    |   80 +
 .../adc/mgt/dto/RepositoryInformation.java      |   43 +
 .../carbon/adc/mgt/dto/SubscriptionInfo.java    |   43 +
 .../carbon/adc/mgt/exception/ADCException.java  |   46 +
 .../exception/AlreadySubscribedException.java   |   45 +
 .../exception/DomainMappingExistsException.java |   45 +
 .../DuplicateCartridgeAliasException.java       |   53 +
 .../InvalidCartridgeAliasException.java         |   54 +
 .../exception/InvalidRepositoryException.java   |   32 +
 .../mgt/exception/NotSubscribedException.java   |   46 +
 .../adc/mgt/exception/PolicyException.java      |   38 +
 .../RepositoryCredentialsRequiredException.java |   37 +
 .../exception/RepositoryRequiredException.java  |   37 +
 .../exception/RepositoryTransportException.java |   37 +
 .../UnregisteredCartridgeException.java         |   45 +
 .../internal/ADCManagementServerComponent.java  |  106 +
 .../carbon/adc/mgt/internal/DataHolder.java     |   77 +
 .../adc/mgt/internal/HostingConstants.java      |   37 +
 .../internal/HostingManagementActivator.java    |   60 +
 .../service/ApplicationManagementService.java   |  620 +++++
 .../InstanceInformationManagementService.java   |   55 +
 .../mgt/service/RepoNotificationService.java    |  179 ++
 .../adc/mgt/service/RepositoryInfoBean.java     |   78 +
 .../service/RepositoryInformationService.java   |   66 +
 .../mgt/utils/ApplicationManagementUtil.java    | 1095 ++++++++
 .../carbon/adc/mgt/utils/CartridgeAppType.java  |   41 +
 .../mgt/utils/CartridgeConfigFileReader.java    |   59 +
 .../adc/mgt/utils/CartridgeConstants.java       |   74 +
 .../carbon/adc/mgt/utils/CartridgeDomain.java   |  143 +
 .../wso2/carbon/adc/mgt/utils/DomainInfo.java   |   40 +
 .../adc/mgt/utils/PersistenceManager.java       |  853 ++++++
 .../wso2/carbon/adc/mgt/utils/PolicyHolder.java |  289 ++
 .../carbon/adc/mgt/utils/RepositoryCreator.java |  266 ++
 .../carbon/adc/mgt/utils/RepositoryFactory.java |  129 +
 .../carbon/adc/mgt/utils/StratosDBUtils.java    |  210 ++
 .../mgt/utils/SynchronizeRepositoryRequest.java |  143 +
 .../src/main/resources/META-INF/services.xml    |   86 +
 .../2.1.3/src/main/resources/policies.xsd       |   36 +
 .../2.1.3/src/scripts/append_zone_file.sh       |   24 +
 .../carbon/adc/mgt/test/PolicyHolderTest.java   |   63 +
 .../2.1.3/src/test/resources/log4j.properties   |    8 +
 .../2.1.3/src/test/resources/policies-1.xml     |   22 +
 .../2.1.3/pom.xml                               |  131 +
 .../topology/mgt/builder/TopologySyncher.java   |  114 +
 .../mgt/exception/TopologyMgtException.java     |   35 +
 .../mgt/group/mgt/GroupMgtAgentBuilder.java     |  109 +
 .../mgt/SubDomainAwareGroupManagementAgent.java |   32 +
 .../mgt/internal/TopologyMgtDSComponent.java    |  290 ++
 .../mgt/service/TopologyManagementService.java  |   69 +
 .../impl/TopologyManagementServiceImpl.java     |  126 +
 .../mgt/serviceobjects/DomainContext.java       |   90 +
 .../mgt/subscriber/TopicHealthChecker.java      |   67 +
 .../mgt/subscriber/TopologyListener.java        |   44 +
 .../mgt/subscriber/TopologySubscriber.java      |   92 +
 .../mgt/subscriber/TopologySubscriberTask.java  |    0
 .../adc/topology/mgt/util/ConfigHolder.java     |  197 ++
 .../topology/mgt/util/TopologyConstants.java    |   13 +
 .../adc/topology/mgt/util/TopologyMgtUtil.java  |    5 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../org.wso2.carbon.billing.core/2.1.0/pom.xml  |  140 +
 .../carbon/billing/core/BillingConstants.java   |   55 +
 .../wso2/carbon/billing/core/BillingEngine.java |  462 ++++
 .../billing/core/BillingEngineContext.java      |   62 +
 .../carbon/billing/core/BillingException.java   |   27 +
 .../carbon/billing/core/BillingHandler.java     |   30 +
 .../carbon/billing/core/BillingManager.java     |   83 +
 .../core/BillingTenantMgtListenerImpl.java      |  203 ++
 .../carbon/billing/core/DataAccessManager.java  |  244 ++
 .../core/beans/OutstandingBalanceInfoBean.java  |   89 +
 .../core/beans/PaginatedBalanceInfoBean.java    |   52 +
 .../billing/core/conf/BillingConfiguration.java |  185 ++
 .../core/conf/BillingTaskConfiguration.java     |  251 ++
 .../carbon/billing/core/dataobjects/Cash.java   |  304 +++
 .../billing/core/dataobjects/Customer.java      |  143 +
 .../billing/core/dataobjects/Discount.java      |   88 +
 .../billing/core/dataobjects/Invoice.java       |  129 +
 .../carbon/billing/core/dataobjects/Item.java   |  143 +
 .../billing/core/dataobjects/Payment.java       |   92 +
 .../billing/core/dataobjects/Subscription.java  |  125 +
 .../core/handlers/DefaultFinalizingHandler.java |   91 +
 .../DefaultSubscriptionFeedingHandler.java      |  147 +
 .../core/handlers/EmailSendingHandler.java      |  311 +++
 .../handlers/InvoiceCalculationHandler.java     |  226 ++
 .../billing/core/handlers/RuleHandler.java      |  142 +
 .../SubscriptionTreeBuildingHandler.java        |  132 +
 .../core/internal/BillingServiceComponent.java  |  171 ++
 .../wso2/carbon/billing/core/internal/Util.java |  132 +
 .../billing/core/jdbc/DataAccessObject.java     | 2557 ++++++++++++++++++
 .../carbon/billing/core/jdbc/Transaction.java   |  113 +
 .../billing/core/scheduler/BillingJob.java      |   63 +
 .../core/scheduler/BillingScheduler.java        |   74 +
 .../billing/core/scheduler/ScheduleHelper.java  |   26 +
 .../core/scheduler/SchedulerContext.java        |   33 +
 .../scheduleHelpers/MonthlyScheduleHelper.java  |   55 +
 .../scheduleHelpers/OneTimeScheduleHelper.java  |   33 +
 .../billing/core/utilities/CustomerUtils.java   |  136 +
 .../core/utilities/DataSourceHolder.java        |   34 +
 .../carbon/billing/test/CarbonHome1Test.java    |  242 ++
 .../org/wso2/carbon/billing/test/CashTest.java  |  101 +
 .../test/FiveSecondTriggerCalculator.java       |   44 +
 .../billing/test/FiveSecondTriggerTester.java   |   38 +
 .../carbon/billing/test/InvoiceMsgTest.java     |  217 ++
 .../test/MonthlyTriggerCalculatorTest.java      |  106 +
 .../org/wso2/carbon/billing/test/RuleTest.java  |  213 ++
 .../org/wso2/carbon/billing/test/TestUtils.java |   83 +
 .../wso2/carbon/billing/test/TriggerTest.java   |  226 ++
 .../repository/conf/billing-config.xml          |   83 +
 .../repository/conf/billing-rules1.drl          |   15 +
 .../conf/email-registration-complete.xml        |   31 +
 .../repository/conf/email-registration.xml      |   33 +
 .../repository/conf/email-update.xml            |   34 +
 .../conf/multitenancy-billing-rule.xml          |   41 +
 .../repository/conf/multitenancy-packages.xml   |   88 +
 .../repository/conf/notification.xml            |   23 +
 .../repository/conf/billing-config.xml          |   86 +
 .../repository/conf/billing-rules1.drl          |   15 +
 .../conf/email-registration-complete.xml        |   31 +
 .../repository/conf/email-registration.xml      |   33 +
 .../repository/conf/email-update.xml            |   34 +
 .../conf/multitenancy-billing-rule.xml          |   41 +
 .../repository/conf/multitenancy-packages.xml   |   88 +
 .../repository/conf/notification.xml            |   23 +
 .../org.wso2.carbon.billing.core/2.1.3/pom.xml  |  140 +
 .../carbon/billing/core/BillingConstants.java   |   56 +
 .../wso2/carbon/billing/core/BillingEngine.java |  466 ++++
 .../billing/core/BillingEngineContext.java      |   62 +
 .../carbon/billing/core/BillingException.java   |   27 +
 .../carbon/billing/core/BillingHandler.java     |   30 +
 .../carbon/billing/core/BillingManager.java     |   83 +
 .../core/BillingTenantMgtListenerImpl.java      |  203 ++
 .../carbon/billing/core/DataAccessManager.java  |  244 ++
 .../core/beans/OutstandingBalanceInfoBean.java  |   89 +
 .../core/beans/PaginatedBalanceInfoBean.java    |   52 +
 .../billing/core/conf/BillingConfiguration.java |  185 ++
 .../core/conf/BillingTaskConfiguration.java     |  251 ++
 .../carbon/billing/core/dataobjects/Cash.java   |  304 +++
 .../billing/core/dataobjects/Customer.java      |  152 ++
 .../billing/core/dataobjects/Discount.java      |   88 +
 .../billing/core/dataobjects/Invoice.java       |  129 +
 .../carbon/billing/core/dataobjects/Item.java   |  161 ++
 .../billing/core/dataobjects/Payment.java       |   92 +
 .../billing/core/dataobjects/Subscription.java  |  125 +
 .../core/handlers/DefaultFinalizingHandler.java |   91 +
 .../DefaultSubscriptionFeedingHandler.java      |  147 +
 .../core/handlers/EmailSendingHandler.java      |  311 +++
 .../handlers/InvoiceCalculationHandler.java     |  240 ++
 .../billing/core/handlers/RuleHandler.java      |  142 +
 .../SubscriptionTreeBuildingHandler.java        |  132 +
 .../core/internal/BillingServiceComponent.java  |  171 ++
 .../wso2/carbon/billing/core/internal/Util.java |  132 +
 .../billing/core/jdbc/DataAccessObject.java     | 2557 ++++++++++++++++++
 .../carbon/billing/core/jdbc/Transaction.java   |  113 +
 .../billing/core/scheduler/BillingJob.java      |   63 +
 .../core/scheduler/BillingScheduler.java        |   74 +
 .../billing/core/scheduler/ScheduleHelper.java  |   26 +
 .../core/scheduler/SchedulerContext.java        |   33 +
 .../scheduleHelpers/MonthlyScheduleHelper.java  |   55 +
 .../scheduleHelpers/OneTimeScheduleHelper.java  |   33 +
 .../billing/core/utilities/CustomerUtils.java   |  136 +
 .../core/utilities/DataSourceHolder.java        |   34 +
 .../carbon/billing/test/CarbonHome1Test.java    |  242 ++
 .../org/wso2/carbon/billing/test/CashTest.java  |  101 +
 .../test/FiveSecondTriggerCalculator.java       |   44 +
 .../billing/test/FiveSecondTriggerTester.java   |   38 +
 .../carbon/billing/test/InvoiceMsgTest.java     |  217 ++
 .../test/MonthlyTriggerCalculatorTest.java      |  106 +
 .../org/wso2/carbon/billing/test/RuleTest.java  |  213 ++
 .../org/wso2/carbon/billing/test/TestUtils.java |   83 +
 .../wso2/carbon/billing/test/TriggerTest.java   |  226 ++
 .../repository/conf/billing-config.xml          |   83 +
 .../repository/conf/billing-rules1.drl          |   15 +
 .../conf/email-registration-complete.xml        |   31 +
 .../repository/conf/email-registration.xml      |   33 +
 .../repository/conf/email-update.xml            |   34 +
 .../conf/multitenancy-billing-rule.xml          |   41 +
 .../repository/conf/multitenancy-packages.xml   |   88 +
 .../repository/conf/notification.xml            |   23 +
 .../repository/conf/billing-config.xml          |   86 +
 .../repository/conf/billing-rules1.drl          |   15 +
 .../conf/email-registration-complete.xml        |   31 +
 .../repository/conf/email-registration.xml      |   33 +
 .../repository/conf/email-update.xml            |   34 +
 .../conf/multitenancy-billing-rule.xml          |   41 +
 .../repository/conf/multitenancy-packages.xml   |   88 +
 .../repository/conf/notification.xml            |   23 +
 .../2.1.0/pom.xml                               |  117 +
 .../mgt/ui/clients/BillingServiceClient.java    |  122 +
 .../billing/mgt/ui/utils/BillingUtil.java       |  182 ++
 .../src/main/resources/META-INF/component.xml   |  100 +
 .../billing/mgt/ui/i18n/JSResources.properties  |    1 +
 .../billing/mgt/ui/i18n/Resources.properties    |   52 +
 .../add_discount_ajaxprocessor.jsp              |   66 +
 .../add_payment-ajaxprocessor.jsp               |   56 +
 .../add_registration_payment-ajaxprocessor.jsp  |   79 +
 .../web/tenant-billing/adjustments.jsp          |  196 ++
 .../resources/web/tenant-billing/css/billing.cs |    7 +
 .../web/tenant-billing/css/billing.css          |   58 +
 .../resources/web/tenant-billing/discounts.jsp  |  182 ++
 .../web/tenant-billing/docs/images/add-org.png  |  Bin 0 -> 49926 bytes
 .../web/tenant-billing/docs/images/billing.png  |  Bin 0 -> 4264 bytes
 .../web/tenant-billing/docs/images/paypal.png   |  Bin 0 -> 9298 bytes
 .../web/tenant-billing/docs/userguide.html      |   75 +
 .../find_invoices_ajaxprocessor.jsp             |   47 +
 .../get_invoice_by_id_ajaxprocessor.jsp         |   25 +
 .../web/tenant-billing/images/logo.png          |  Bin 0 -> 5977 bytes
 .../web/tenant-billing/images/view-invoice.gif  |  Bin 0 -> 1014 bytes
 .../web/tenant-billing/interim_invoice.jsp      |  355 +++
 .../make_adjustment_ajaxprocessor.jsp           |   49 +
 .../web/tenant-billing/past_invoice.jsp         |  470 ++++
 .../prepare_checkout_ajaxprocessor.jsp          |   28 +
 .../web/tenant-billing/view_balance.jsp         |  171 ++
 .../org.wso2.carbon.billing.mgt/2.1.0/pom.xml   |  116 +
 .../billing/mgt/api/DefaultTenantBilling.java   |  201 ++
 .../mgt/api/MultitenancyBillingInfo.java        |  166 ++
 .../carbon/billing/mgt/beans/BilledEntry.java   |   41 +
 .../carbon/billing/mgt/beans/BillingPeriod.java |   60 +
 .../billing/mgt/beans/MultitenancyInvoice.java  |  121 +
 .../mgt/beans/MultitenancyPurchaseOrder.java    |   60 +
 .../mgt/beans/MultitenancySubscription.java     |   67 +
 .../mgt/dataobjects/MultitenancyCustomer.java   |  126 +
 .../mgt/dataobjects/MultitenancyPackage.java    |  141 +
 .../dataobjects/MultitenancyPackageSubItem.java |   22 +
 .../MultitenancySubscriptionFeedingHandler.java |  231 ++
 .../MultitenancyBillingServiceComponent.java    |  109 +
 .../mgt/services/BillingDataAccessService.java  |  281 ++
 .../billing/mgt/services/BillingService.java    |  606 +++++
 .../org/wso2/carbon/billing/mgt/util/Util.java  |  173 ++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |   96 +
 .../org.wso2.carbon.billing.mgt/2.1.3/pom.xml   |  117 +
 .../billing/mgt/api/DefaultTenantBilling.java   |  201 ++
 .../mgt/api/MultitenancyBillingInfo.java        |  178 ++
 .../carbon/billing/mgt/beans/BilledEntry.java   |   41 +
 .../carbon/billing/mgt/beans/BillingPeriod.java |   60 +
 .../billing/mgt/beans/MultitenancyInvoice.java  |  121 +
 .../mgt/beans/MultitenancyPurchaseOrder.java    |   60 +
 .../mgt/beans/MultitenancySubscription.java     |   67 +
 .../mgt/dataobjects/MultitenancyCustomer.java   |  135 +
 .../mgt/dataobjects/MultitenancyPackage.java    |  152 ++
 .../dataobjects/MultitenancyPackageSubItem.java |   22 +
 .../MultitenancySubscriptionFeedingHandler.java |  234 ++
 .../MultitenancyBillingServiceComponent.java    |  109 +
 .../mgt/services/BillingDataAccessService.java  |  281 ++
 .../billing/mgt/services/BillingService.java    |  606 +++++
 .../org/wso2/carbon/billing/mgt/util/Util.java  |  173 ++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |   96 +
 components/stratos/billing/pom.xml              |   42 +
 .../2.1.3/pom.xml                               |  115 +
 .../cartridge/agent/ClusteringClient.java       |  268 ++
 .../cartridge/agent/ELBMembershipListener.java  |   81 +
 .../InstanceStateNotificationClientThread.java  |   44 +
 .../org/wso2/carbon/cartridge/agent/Main.java   |  156 ++
 .../agent/RegistrantMembershipListener.java     |   55 +
 .../exception/CartridgeAgentException.java      |   39 +
 .../agent/internal/CartridgeAgentConstants.java |   26 +
 .../CartridgeAgentServiceComponent.java         |  138 +
 .../cartridge/agent/internal/DataHolder.java    |   41 +
 .../cartridge/agent/registrant/PortMapping.java |   88 +
 .../cartridge/agent/registrant/Registrant.java  |  197 ++
 .../agent/registrant/RegistrantDatabase.java    |  141 +
 .../registrant/RegistrantHealthChecker.java     |  113 +
 .../agent/registrant/RegistrantUtil.java        |  175 ++
 .../agent/service/CartridgeAgentService.java    |   67 +
 .../src/main/resources/META-INF/services.xml    |   27 +
 .../2.1.1/pom.xml                               |   73 +
 .../cartridge/messages/ClusterDomain.java       |   99 +
 .../messages/ClusterDomainManager.java          |   34 +
 .../messages/CreateClusterDomainMessage.java    |  128 +
 .../CreateRemoveClusterDomainMessage.java       |   59 +
 components/stratos/cartridge-agent/pom.xml      |  121 +
 .../2.1.0/pom.xml                               |   96 +
 .../ui/clients/ValidateDomainAdminClient.java   |  117 +
 .../domain/ui/clients/ValidateDomainClient.java |   27 +
 .../clients/ValidateDomainNonAdminClient.java   |  115 +
 .../carbon/validate/domain/ui/utils/Util.java   |   40 +
 .../src/main/resources/META-INF/component.xml   |   21 +
 .../resources/ValidateDomainAdminService.wsdl   |  238 ++
 .../main/resources/ValidateDomainService.wsdl   |  238 ++
 .../domain/ui/i18n/JSResources.properties       |    7 +
 .../domain/ui/i18n/Resources.properties         |    3 +
 .../web/validate-domain/css/validate_domain.css |   31 +
 .../docs/images/domain-validation.png           |  Bin 0 -> 56415 bytes
 .../web/validate-domain/docs/userguide.html     |   47 +
 .../web/validate-domain/images/ajax-loader.gif  |  Bin 0 -> 673 bytes
 .../web/validate-domain/images/right.gif        |  Bin 0 -> 924 bytes
 .../web/validate-domain/images/wrong.gif        |  Bin 0 -> 976 bytes
 .../web/validate-domain/js/validate_domain.js   |  151 ++
 .../submit_validate_domain_ajaxprocessor.jsp    |   36 +
 .../validate_domain_logged_in.jsp               |   22 +
 .../validate_domain_not_logged_in.jsp           |   22 +
 .../validate_domain_template.jsp                |  204 ++
 .../validate_with_dns_ajaxprocessor.jsp         |   22 +
 .../validate_with_text_ajaxprocessor.jsp        |   22 +
 .../2.1.0/pom.xml                               |   80 +
 .../ValidateDomainServiceComponent.java         |   87 +
 .../services/ValidateDomainAdminService.java    |   39 +
 .../domain/services/ValidateDomainService.java  |   82 +
 .../wso2/carbon/validate/domain/util/Util.java  |  320 +++
 .../src/main/resources/META-INF/services.xml    |   39 +
 components/stratos/domain-validator/pom.xml     |   41 +
 .../org.wso2.carbon.activation/2.1.0/pom.xml    |   94 +
 .../internal/ActivationServiceComponent.java    |  152 ++
 .../activation/module/ActivationHandler.java    |  154 ++
 .../activation/module/ActivationModule.java     |   65 +
 .../activation/service/ActivationService.java   |   85 +
 .../activation/utils/ActivationManager.java     |   96 +
 .../org/wso2/carbon/activation/utils/Util.java  |  138 +
 .../src/main/resources/META-INF/module.xml      |   33 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../org.wso2.carbon.activation/2.1.2/pom.xml    |   94 +
 .../internal/ActivationServiceComponent.java    |  152 ++
 .../activation/module/ActivationHandler.java    |  161 ++
 .../activation/module/ActivationModule.java     |   65 +
 .../activation/service/ActivationService.java   |   85 +
 .../activation/utils/ActivationManager.java     |   96 +
 .../org/wso2/carbon/activation/utils/Util.java  |  138 +
 .../src/main/resources/META-INF/module.xml      |   33 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../2.1.3/pom.xml                               |   85 +
 .../cartridge/mgt/ui/CartridgeAdminClient.java  |  275 ++
 .../cartridge/mgt/ui/CartridgeConstans.java     |    0
 .../wso2/carbon/cartridge/mgt/ui/Payload.java   |   14 +
 .../mgt/ui/RepoNotificationClient.java          |   52 +
 .../mgt/ui/RepoNotificationServlet.java         |   57 +
 .../carbon/cartridge/mgt/ui/Repository.java     |   14 +
 .../CartridgeManagementUIActivator.java         |   56 +
 .../src/main/resources/META-INF/component.xml   |   93 +
 .../cartridge/mgt/ui/i18n/Resources.properties  |   96 +
 .../web/cartridge-mgt/available_cartridges.jsp  |  186 ++
 .../web/cartridge-mgt/docs/userguide.html       |   41 +
 .../web/cartridge-mgt/images/ajax-loading.gif   |  Bin 0 -> 1849 bytes
 .../web/cartridge-mgt/images/cartridge.png      |  Bin 0 -> 463 bytes
 .../resources/web/cartridge-mgt/images/list.gif |  Bin 0 -> 216 bytes
 .../web/cartridge-mgt/images/search.gif         |  Bin 0 -> 578 bytes
 .../web/cartridge-mgt/images/subscribe.gif      |  Bin 0 -> 718 bytes
 .../web/cartridge-mgt/images/unsubscribe.png    |  Bin 0 -> 742 bytes
 .../resources/web/cartridge-mgt/js/common.js    |   76 +
 .../web/cartridge-mgt/js/jquery.blockUI-1.33.js |  361 +++
 .../main/resources/web/cartridge-mgt/list.jsp   |    0
 .../resources/web/cartridge-mgt/map_domain.jsp  |  118 +
 .../cartridge-mgt/map_domain_ajaxprocessor.jsp  |   67 +
 .../remove_domain_ajaxprocessor.jsp             |   60 +
 .../web/cartridge-mgt/styles/XMLSchema.dtd      |  418 +++
 .../web/cartridge-mgt/styles/XMLSchema.xsd      | 2383 ++++++++++++++++
 .../web/cartridge-mgt/styles/annotated-wsdl.xsl |  702 +++++
 .../cartridge-mgt/styles/annotated-wsdl2.xsl    |  721 +++++
 .../web/cartridge-mgt/styles/annotated-xsd.xsl  |  850 ++++++
 .../resources/web/cartridge-mgt/styles/atom.xsl |  130 +
 .../web/cartridge-mgt/styles/datatypes.dtd      |  216 ++
 .../resources/web/cartridge-mgt/styles/rss.xsl  |  116 +
 .../resources/web/cartridge-mgt/subscribe.jsp   |  303 +++
 .../cartridge-mgt/subscribe_ajaxprocessor.jsp   |   88 +
 .../web/cartridge-mgt/subscribed_cartridges.jsp |  174 ++
 .../subscribed_cartridges_ajaxprocessor.jsp     |  279 ++
 .../cartridge-mgt/sync_repo_ajaxprocessor.jsp   |   60 +
 .../cartridge-mgt/test_git_ajaxprocessor.jsp    |   71 +
 .../cartridge-mgt/unsubscribe_ajaxprocessor.jsp |   64 +
 .../org.wso2.carbon.db.keep.alive/2.1.0/pom.xml |  116 +
 .../alive/actions/AccessingBillingAction.java   |   39 +
 .../alive/actions/AccessingRegistryAction.java  |   41 +
 .../db/keep/alive/actions/UserMgtAction.java    |   43 +
 .../internal/DBKeepAliveServiceComponent.java   |   81 +
 .../carbon/db/keep/alive/util/KeepAliveJob.java |   58 +
 .../wso2/carbon/db/keep/alive/util/Util.java    |  115 +
 .../org.wso2.carbon.email.sender/2.1.0/pom.xml  |   86 +
 .../email/sender/api/BulkEmailSender.java       |  100 +
 .../email/sender/api/EmailDataHolder.java       |   26 +
 .../carbon/email/sender/api/EmailSender.java    |  108 +
 .../sender/api/EmailSenderConfiguration.java    |  131 +
 .../internal/EmailSenderServiceComponent.java   |   82 +
 .../org/wso2/carbon/email/sender/util/Util.java |  103 +
 .../2.1.0/pom.xml                               |  100 +
 .../ui/GAppRegistrationUIConstants.java         |    6 +
 .../ui/GoolgeAppsRegistrationClient.java        |  227 ++
 .../ui/InMemoryPasswordcallbackHandler.java     |   39 +
 .../src/main/resources/META-INF/component.xml   |   27 +
 .../registration/ui/i18n/Resources.properties   |    8 +
 .../src/main/resources/signonly-policy.xml      |  102 +
 .../web/gappregistration/done_ajaxprocessor.jsp |  165 ++
 .../openidaccept_ajaxprocessor.jsp              |   93 +
 .../gappregistration/setup_ajaxprocessor.jsp    |  320 +++
 .../2.1.0/pom.xml                               |   62 +
 .../GoogleAnalyticsUIServiceComponent.java      |   68 +
 .../ui/servlets/GoogleAnalyticsServlet.java     |   90 +
 .../src/main/resources/META-INF/component.xml   |   43 +
 .../js/googleAnalyticsProcessor.js              |   35 +
 .../web.googleanalytics/js/jquery.min.js        |  167 ++
 .../org.wso2.carbon.keystore.mgt/2.1.0/pom.xml  |  117 +
 .../carbon/keystore/mgt/KeyStoreGenerator.java  |  229 ++
 .../keystore/mgt/KeyStoreMgtException.java      |   39 +
 .../keystore/mgt/KeystoreTenantMgtListener.java |   79 +
 .../internal/KeyStoreMgtServiceComponent.java   |   87 +
 .../keystore/mgt/util/RealmServiceHolder.java   |   33 +
 .../mgt/util/RegistryServiceHolder.java         |   33 +
 .../2.1.0/pom.xml                               |   72 +
 .../balance/agent/LoadBalanceAgentService.java  |   55 +
 .../src/main/resources/META-INF/services.xml    |   29 +
 .../org.wso2.carbon.migration/2.1.0/pom.xml     |   99 +
 .../org/wso2/carbon/migration/impl/Alpha1.java  |  173 ++
 .../impl/ManagementPermissionsAdder.java        |  126 +
 .../internal/MigrationServiceComponent.java     |   81 +
 .../wso2/carbon/migration/util/Migrator.java    |   20 +
 .../org/wso2/carbon/migration/util/Util.java    |   72 +
 .../2.1.3/pom.xml                               |  324 +++
 .../controller/axiom/AxiomXpathParser.java      | 1263 +++++++++
 .../controller/concurrent/ThreadExecutor.java   |   53 +
 .../controller/consumers/TopologyBuilder.java   |  189 ++
 .../controller/deployers/CartridgeDeployer.java |  194 ++
 .../deployers/CloudControllerDeployer.java      |  110 +
 .../controller/deployers/ServiceDeployer.java   |  153 ++
 .../exception/CloudControllerException.java     |   32 +
 .../exception/DeserializationException.java     |   32 +
 .../InvalidCartridgeDefinitionException.java    |   32 +
 .../exception/InvalidXMLException.java          |   36 +
 .../MalformedConfigurationFileException.java    |   32 +
 .../exception/NoInstanceFoundException.java     |   38 +
 .../exception/SerializationException.java       |   32 +
 .../UnregisteredCartridgeException.java         |   32 +
 .../exception/UnregisteredServiceException.java |   32 +
 .../hector/CassandraDataRetriever.java          |  181 ++
 .../controller/hive/HiveQueryExecutor.java      |  167 ++
 .../cloud/controller/iaases/AWSEC2Iaas.java     |  275 ++
 .../controller/iaases/OpenstackNovaIaas.java    |  269 ++
 .../cloud/controller/iaases/VCloudIaas.java     |  164 ++
 .../impl/CloudControllerServiceImpl.java        | 1123 ++++++++
 .../interfaces/CloudControllerService.java      |  195 ++
 .../cloud/controller/interfaces/Iaas.java       |   73 +
 .../internal/CloudControllerDSComponent.java    |   85 +
 .../jcloud/ComputeServiceBuilderUtil.java       |  182 ++
 .../cloud/controller/persist/Deserializer.java  |   91 +
 .../cloud/controller/persist/Serializer.java    |   85 +
 .../CartridgeInstanceDataPublisherTask.java     |  476 ++++
 .../controller/registry/RegistryManager.java    |  101 +
 .../registry/RegistryManager.java.back          |   96 +
 .../runtime/FasterLookUpDataHolder.java         |  425 +++
 .../topic/ConfigurationPublisher.java           |   65 +
 .../topic/TopologySynchronizerTask.java         |   78 +
 .../stratos/cloud/controller/util/AppType.java  |   44 +
 .../cloud/controller/util/Cartridge.java        |  254 ++
 .../cloud/controller/util/CartridgeInfo.java    |  162 ++
 .../controller/util/CartridgeInstanceData.java  |  129 +
 .../util/CloudControllerConstants.java          |  216 ++
 .../controller/util/CloudControllerUtil.java    |  102 +
 .../util/DeclarativeServiceReferenceHolder.java |   69 +
 .../cloud/controller/util/IaasContext.java      |  149 +
 .../cloud/controller/util/IaasProvider.java     |  263 ++
 .../cloud/controller/util/PortMapping.java      |   46 +
 .../cloud/controller/util/Properties.java       |   36 +
 .../stratos/cloud/controller/util/Property.java |   35 +
 .../cloud/controller/util/ServiceContext.java   |  283 ++
 .../src/main/resources/META-INF/component.xml   |   36 +
 .../src/main/resources/META-INF/services.xml    |    9 +
 .../2.1.3/src/main/resources/cartridge.xsd      |  133 +
 .../2.1.3/src/main/resources/cartridges.xsd     |  144 +
 .../2.1.3/src/main/resources/service.xsd        |   46 +
 .../2.1.3/src/main/resources/services.xsd       |   51 +
 .../service/axiom/AxiomValidationTest.java      |  125 +
 .../service/axiom/AxiomXpathParserTest.java     |   51 +
 .../service/util/ServiceContextTest.java        |   49 +
 .../2.1.3/src/test/resources/cartridges-1.xml   |   33 +
 .../2.1.3/src/test/resources/cartridges-2.xml   |   34 +
 .../2.1.3/src/test/resources/cartridges-3.xml   |   16 +
 .../2.1.3/src/test/resources/cartridges-4.xml   |   32 +
 .../2.1.3/src/test/resources/cartridges-5.xml   |   29 +
 .../2.1.3/src/test/resources/cartridges-6.xml   |   19 +
 .../2.1.3/src/test/resources/cartridges-7.xml   |   40 +
 .../2.1.3/src/test/resources/cartridges-8.xml   |   72 +
 .../2.1.3/src/test/resources/cartridges-9.xml   |   66 +
 .../src/test/resources/cloud-controller.xml     |   73 +
 .../2.1.0/pom.xml                               |   87 +
 .../stratos/common/TenantBillingService.java    |   24 +
 .../stratos/common/beans/TenantInfoBean.java    |  137 +
 .../common/config/CloudServiceConfig.java       |  163 ++
 .../common/config/CloudServiceConfigParser.java |   48 +
 .../common/config/CloudServicesDescConfig.java  |   58 +
 .../stratos/common/config/PermissionConfig.java |   68 +
 .../common/constants/StratosConstants.java      |  143 +
 .../common/constants/UsageConstants.java        |   53 +
 .../common/exception/StratosException.java      |   41 +
 .../internal/CloudCommonServiceComponent.java   |  121 +
 .../common/listeners/TenantMgtListener.java     |   39 +
 .../stratos/common/packages/PackageInfo.java    |   93 +
 .../common/packages/PackageInfoHolder.java      |  161 ++
 .../common/services/PackageInfoService.java     |   16 +
 .../stratos/common/util/ClaimsMgtUtil.java      |  263 ++
 .../stratos/common/util/CloudServicesUtil.java  |  182 ++
 .../carbon/stratos/common/util/CommonUtil.java  |  620 +++++
 .../util/MeteringAccessValidationUtils.java     |   51 +
 .../common/util/StratosConfiguration.java       |  319 +++
 .../src/main/resources/META-INF/services.xml    |   32 +
 .../src/main/resources/cloud-services-desc.xml  |  109 +
 .../org/wso2/carbon/common/test/CommonTest.java |   48 +
 .../2.1.1/pom.xml                               |   87 +
 .../stratos/common/TenantBillingService.java    |   24 +
 .../stratos/common/beans/TenantInfoBean.java    |  137 +
 .../common/config/CloudServiceConfig.java       |  163 ++
 .../common/config/CloudServiceConfigParser.java |   48 +
 .../common/config/CloudServicesDescConfig.java  |   58 +
 .../stratos/common/config/PermissionConfig.java |   68 +
 .../common/constants/StratosConstants.java      |  143 +
 .../common/constants/UsageConstants.java        |   55 +
 .../common/exception/StratosException.java      |   41 +
 .../internal/CloudCommonServiceComponent.java   |  121 +
 .../common/listeners/TenantMgtListener.java     |   39 +
 .../stratos/common/packages/PackageInfo.java    |   93 +
 .../common/packages/PackageInfoHolder.java      |  161 ++
 .../common/services/PackageInfoService.java     |   16 +
 .../stratos/common/util/ClaimsMgtUtil.java      |  263 ++
 .../stratos/common/util/CloudServicesUtil.java  |  182 ++
 .../carbon/stratos/common/util/CommonUtil.java  |  620 +++++
 .../util/MeteringAccessValidationUtils.java     |   51 +
 .../common/util/StratosConfiguration.java       |  319 +++
 .../src/main/resources/META-INF/services.xml    |   32 +
 .../src/main/resources/cloud-services-desc.xml  |  109 +
 .../org/wso2/carbon/common/test/CommonTest.java |   48 +
 .../2.1.2/pom.xml                               |   87 +
 .../stratos/common/TenantBillingService.java    |   24 +
 .../stratos/common/beans/TenantInfoBean.java    |  137 +
 .../common/config/CloudServiceConfig.java       |  163 ++
 .../common/config/CloudServiceConfigParser.java |   48 +
 .../common/config/CloudServicesDescConfig.java  |   58 +
 .../stratos/common/config/PermissionConfig.java |   68 +
 .../common/constants/StratosConstants.java      |  143 +
 .../common/constants/UsageConstants.java        |   55 +
 .../common/exception/StratosException.java      |   41 +
 .../internal/CloudCommonServiceComponent.java   |  121 +
 .../common/listeners/TenantMgtListener.java     |   39 +
 .../stratos/common/packages/PackageInfo.java    |   93 +
 .../common/packages/PackageInfoHolder.java      |  161 ++
 .../common/services/PackageInfoService.java     |   16 +
 .../stratos/common/util/ClaimsMgtUtil.java      |  263 ++
 .../stratos/common/util/CloudServicesUtil.java  |  182 ++
 .../carbon/stratos/common/util/CommonUtil.java  |  620 +++++
 .../util/MeteringAccessValidationUtils.java     |   51 +
 .../common/util/StratosConfiguration.java       |  319 +++
 .../src/main/resources/META-INF/services.xml    |   32 +
 .../src/main/resources/cloud-services-desc.xml  |  109 +
 .../org/wso2/carbon/common/test/CommonTest.java |   48 +
 .../2.1.0/pom.xml                               |  102 +
 .../deployment/CloudDeploymentInterceptor.java  |   88 +
 .../deployment/SuperTenantRolePlayer.java       |   43 +
 .../CloudDeploymentServiceComponent.java        |   70 +
 .../stratos/deployment/internal/DataHolder.java |   42 +
 .../2.1.0/pom.xml                               |   92 +
 .../deployer/LandingPageWebappDeployer.java     |  109 +
 .../page/deployer/internal/DataHolder.java      |   37 +
 ...ndingPageWebappDeployerServiceComponent.java |   44 +
 .../src/main/resources/META-INF/component.xml   |   23 +
 .../2.1.0/pom.xml                               |   90 +
 .../dispatcher/MultitenantDispatcher.java       |   65 +
 .../TenantDispatcherServiceComponent.java       |  143 +
 .../2.1.0/pom.xml                               |   90 +
 .../org/wso2/carbon/ui/menu/stratos/Util.java   |   88 +
 .../StratosUIGeneralMenuDSComponent.java        |   52 +
 .../src/main/resources/META-INF/component.xml   |   45 +
 .../ui/menu/general/i18n/Resources.properties   |    2 +
 .../web/manager-home/images/services.gif        |  Bin 0 -> 604 bytes
 .../manager-home/load_manager_ajaxprocessor.jsp |   30 +
 .../2.1.0/pom.xml                               |   65 +
 .../wso2/carbon/payment/paypal/dto/Address.java |  101 +
 .../payment/paypal/dto/ECDetailResponse.java    |   51 +
 .../carbon/payment/paypal/dto/ECResponse.java   |   69 +
 .../wso2/carbon/payment/paypal/dto/Payer.java   |   90 +
 .../carbon/payment/paypal/dto/PaypalError.java  |   52 +
 .../payment/paypal/dto/TransactionResponse.java |   60 +
 .../internal/PaymentServiceComponent.java       |   63 +
 .../payment/paypal/services/PaypalService.java  |  161 ++
 .../payment/paypal/util/PaymentConstants.java   |   30 +
 .../payment/paypal/util/ResponsePopulator.java  |  156 ++
 .../src/main/resources/META-INF/services.xml    |   12 +
 .../2.1.0/src/main/resources/paypal.properties  |    5 +
 .../org.wso2.carbon.payment.ui/2.1.0/pom.xml    |   71 +
 .../payment/ui/client/PaymentServiceClient.java |   85 +
 .../src/main/resources/StratosPayment.wsdl      |  308 +++
 .../carbon/payment/ui/i18n/Resources.properties |    3 +
 .../main/resources/web/payment/completed.jsp    |  155 ++
 .../main/resources/web/payment/css/billing.css  |   58 +
 .../web/payment/doEC-ajaxprocessor.jsp          |   58 +
 .../main/resources/web/payment/images/logo.png  |  Bin 0 -> 5977 bytes
 .../print_payment_completed_ajaxprocessor.jsp   |  132 +
 .../web/payment/registration_payment.jsp        |  172 ++
 .../payment/registration_payment_completed.jsp  |  147 +
 .../web/payment/setEC-ajaxprocessor.jsp         |   54 +
 .../src/main/resources/web/payment/success.jsp  |  165 ++
 ...de_registration_usage_plan_ajaxprocessor.jsp |   59 +
 components/stratos/payment/pom.xml              |   41 +
 components/stratos/pom.xml                      |  603 +++++
 .../2.1.0/pom.xml                               |  105 +
 .../clients/RedirectorServletServiceClient.java |   90 +
 .../servlet/ui/filters/AllPagesFilter.java      |  164 ++
 .../internal/RedirectorServletUIComponent.java  |   44 +
 .../carbon/redirector/servlet/ui/util/Util.java |   64 +
 .../resources/RedirectorServletService.wsdl     |  102 +
 .../2.1.0/pom.xml                               |   97 +
 .../RedirectorServletServiceComponent.java      |   80 +
 .../services/RedirectorServletService.java      |   37 +
 .../carbon/redirector/servlet/util/Util.java    |   84 +
 .../src/main/resources/META-INF/services.xml    |   28 +
 .../2.1.0/pom.xml                               |   85 +
 .../ui/internal/RedirectorJSPFilter.java        |   59 +
 .../internal/SSORedirectorServiceComponent.java |   65 +
 .../sso/redirector/ui/i18n/Resources.properties |   32 +
 .../web/stratos-auth/css/stratos-loginpage.css  |   94 +
 .../images/cloud-identity-sso-config-ok.png     |  Bin 0 -> 38465 bytes
 .../images/cloud-identity-sso-config.png        |  Bin 0 -> 32929 bytes
 .../stratos-auth/images/cloud-sso-config.png    |  Bin 0 -> 29222 bytes
 .../web/stratos-auth/images/delete.gif          |  Bin 0 -> 555 bytes
 .../web/stratos-auth/images/import.gif          |  Bin 0 -> 1051 bytes
 .../web/stratos-auth/images/loading.gif         |  Bin 0 -> 14367 bytes
 .../resources/web/stratos-auth/images/logo.gif  |  Bin 0 -> 17603 bytes
 .../web/stratos-auth/images/policy.gif          |  Bin 0 -> 1017 bytes
 .../web/stratos-auth/images/powered.gif         |  Bin 0 -> 1773 bytes
 .../web/stratos-auth/images/register.gif        |  Bin 0 -> 4099 bytes
 .../resources/web/stratos-auth/images/sso.gif   |  Bin 0 -> 394 bytes
 .../stratos-auth/images/st-login-body-bg.gif    |  Bin 0 -> 2215 bytes
 .../stratos-auth/images/st-login-content-bg.gif |  Bin 0 -> 1060 bytes
 .../stratos-auth/images/st-login-footer-bg.gif  |  Bin 0 -> 749 bytes
 .../stratos-auth/images/st-login-header-bg.gif  |  Bin 0 -> 64503 bytes
 .../web/stratos-auth/redirect_ajaxprocessor.jsp |  176 ++
 components/stratos/redirector/pom.xml           |   42 +
 .../2.1.0/pom.xml                               |  104 +
 .../installer/ui/SampleDeployerClient.java      |  400 +++
 .../sample/installer/ui/ServerInfoBean.java     |   46 +
 .../wso2/carbon/sample/installer/ui/Util.java   |  128 +
 .../src/main/resources/META-INF/component.xml   |   33 +
 .../src/main/resources/SampleDeployer.wsdl      |  284 ++
 .../installer/ui/i18n/Resources.properties      |   16 +
 .../web/sample-installer/images/all.gif         |  Bin 0 -> 234 bytes
 .../web/sample-installer/images/installer.gif   |  Bin 0 -> 581 bytes
 .../web/sample-installer/images/services.gif    |  Bin 0 -> 638 bytes
 .../resources/web/sample-installer/index.jsp    |  162 ++
 .../web/sample-installer/installer.jsp          |   77 +
 .../2.1.0/pom.xml                               |  117 +
 .../carbon/sample/installer/SampleDeployer.java |  244 ++
 .../installer/beans/SampleInformation.java      |  118 +
 .../sample/installer/config/SampleConfig.java   |  111 +
 .../installer/config/SamplesDescConfig.java     |   70 +
 .../SampleInstallerServiceComponent.java        |  101 +
 .../carbon/sample/installer/utils/Util.java     |  334 +++
 .../src/main/resources/META-INF/services.xml    |   30 +
 components/stratos/sample-installer/pom.xml     |   41 +
 .../2.1.0/pom.xml                               |  122 +
 .../saml2/sso/mgt/ui/SSOLoginPageFilter.java    |   51 +
 .../saml2/sso/mgt/ui/SSORedirectPageFilter.java |   57 +
 .../stratos/identity/saml2/sso/mgt/ui/Util.java |  155 ++
 .../StratosSSOMgtUIServiceComponent.java        |  108 +
 .../src/main/resources/META-INF/component.xml   |   31 +
 .../saml2/sso/mgt/ui/i18n/Resources.properties  |   36 +
 .../web/stratos-as/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-as/images/body-bg.gif |  Bin 0 -> 923 bytes
 .../web/stratos-as/images/feature-01-icon.gif   |  Bin 0 -> 3412 bytes
 .../web/stratos-as/images/feature-02-icon.gif   |  Bin 0 -> 3253 bytes
 .../web/stratos-as/images/feature-03-icon.gif   |  Bin 0 -> 3374 bytes
 .../web/stratos-as/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-as/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-as/images/login-bg.gif          |  Bin 0 -> 56861 bytes
 .../web/stratos-as/images/paas-login-1pix.gif   |  Bin 0 -> 43 bytes
 .../web/stratos-as/images/powered-logo.gif      |  Bin 0 -> 1574 bytes
 .../web/stratos-as/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-as/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../stratos-as/images/stratos-login-v3_06.gif   |  Bin 0 -> 3412 bytes
 .../web/stratos-as/login_ajaxprocessor.jsp      |  244 ++
 .../web/stratos-bam/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-bam/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-bam/images/feature-01-icon.gif  |  Bin 0 -> 2856 bytes
 .../web/stratos-bam/images/feature-02-icon.gif  |  Bin 0 -> 2738 bytes
 .../web/stratos-bam/images/feature-03-icon.gif  |  Bin 0 -> 3511 bytes
 .../stratos-bam/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-bam/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-bam/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-bam/images/login-bg.gif         |  Bin 0 -> 51582 bytes
 .../stratos-bam/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-bam/images/powered-logo.gif     |  Bin 0 -> 1808 bytes
 .../web/stratos-bam/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-bam/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../stratos-bam/images/stratos-login-v3_06.gif  |  Bin 0 -> 3201 bytes
 .../web/stratos-bam/login_ajaxprocessor.jsp     |  244 ++
 .../web/stratos-bps/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-bps/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-bps/images/feature-01-icon.gif  |  Bin 0 -> 2860 bytes
 .../web/stratos-bps/images/feature-02-icon.gif  |  Bin 0 -> 3044 bytes
 .../web/stratos-bps/images/feature-03-icon.gif  |  Bin 0 -> 3159 bytes
 .../stratos-bps/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-bps/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-bps/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-bps/images/login-bg.gif         |  Bin 0 -> 55359 bytes
 .../stratos-bps/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-bps/images/powered-logo.gif     |  Bin 0 -> 1725 bytes
 .../web/stratos-bps/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-bps/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-bps/login_ajaxprocessor.jsp     |  244 ++
 .../web/stratos-brs/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-brs/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-brs/images/feature-01-icon.gif  |  Bin 0 -> 3371 bytes
 .../web/stratos-brs/images/feature-02-icon.gif  |  Bin 0 -> 3018 bytes
 .../web/stratos-brs/images/feature-03-icon.gif  |  Bin 0 -> 3205 bytes
 .../stratos-brs/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-brs/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-brs/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-brs/images/login-bg.gif         |  Bin 0 -> 54810 bytes
 .../stratos-brs/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-brs/images/powered-logo.gif     |  Bin 0 -> 1683 bytes
 .../web/stratos-brs/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-brs/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-brs/login_ajaxprocessor.jsp     |  245 ++
 .../web/stratos-cep/css/stratos-loginpage.css   |  271 ++
 .../web/stratos-cep/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-cep/images/feature-01-icon.gif  |  Bin 0 -> 2240 bytes
 .../web/stratos-cep/images/feature-02-icon.gif  |  Bin 0 -> 4258 bytes
 .../web/stratos-cep/images/feature-03-icon.gif  |  Bin 0 -> 6022 bytes
 .../stratos-cep/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-cep/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-cep/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-cep/images/login-bg.gif         |  Bin 0 -> 58190 bytes
 .../stratos-cep/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-cep/images/powered-logo.gif     |  Bin 0 -> 2995 bytes
 .../web/stratos-cep/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-cep/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-cep/login_ajaxprocessor.jsp     |  245 ++
 .../web/stratos-csg/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-csg/images/body-bg.gif          |  Bin 0 -> 1366 bytes
 .../web/stratos-csg/images/feature-01-icon.gif  |  Bin 0 -> 2418 bytes
 .../web/stratos-csg/images/feature-02-icon.gif  |  Bin 0 -> 3021 bytes
 .../web/stratos-csg/images/feature-03-icon.gif  |  Bin 0 -> 2926 bytes
 .../stratos-csg/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-csg/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-csg/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-csg/images/login-bg.gif         |  Bin 0 -> 31262 bytes
 .../stratos-csg/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-csg/images/powered-logo.gif     |  Bin 0 -> 1492 bytes
 .../web/stratos-csg/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-csg/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-csg/login_ajaxprocessor.jsp     |  244 ++
 .../web/stratos-dss/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-dss/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-dss/images/feature-01-icon.gif  |  Bin 0 -> 3394 bytes
 .../web/stratos-dss/images/feature-02-icon.gif  |  Bin 0 -> 2981 bytes
 .../web/stratos-dss/images/feature-03-icon.gif  |  Bin 0 -> 3291 bytes
 .../stratos-dss/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-dss/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-dss/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-dss/images/login-bg.gif         |  Bin 0 -> 56380 bytes
 .../stratos-dss/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-dss/images/powered-logo.gif     |  Bin 0 -> 1686 bytes
 .../web/stratos-dss/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-dss/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-dss/login_ajaxprocessor.jsp     |  243 ++
 .../web/stratos-esb/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-esb/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-esb/images/feature-01-icon.gif  |  Bin 0 -> 3121 bytes
 .../web/stratos-esb/images/feature-02-icon.gif  |  Bin 0 -> 2462 bytes
 .../web/stratos-esb/images/feature-03-icon.gif  |  Bin 0 -> 1834 bytes
 .../stratos-esb/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-esb/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-esb/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-esb/images/login-bg.gif         |  Bin 0 -> 54491 bytes
 .../stratos-esb/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-esb/images/powered-logo.gif     |  Bin 0 -> 1714 bytes
 .../web/stratos-esb/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-esb/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-esb/login_ajaxprocessor.jsp     |  244 ++
 .../web/stratos-gov/css/stratos-loginpage.css   |  265 ++
 .../web/stratos-gov/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../web/stratos-gov/images/feature-01-icon.gif  |  Bin 0 -> 2587 bytes
 .../web/stratos-gov/images/feature-02-icon.gif  |  Bin 0 -> 3125 bytes
 .../web/stratos-gov/images/feature-03-icon.gif  |  Bin 0 -> 2844 bytes
 .../stratos-gov/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../web/stratos-gov/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-gov/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-gov/images/login-bg.gif         |  Bin 0 -> 54800 bytes
 .../stratos-gov/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-gov/images/powered-logo.gif     |  Bin 0 -> 1657 bytes
 .../web/stratos-gov/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-gov/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-gov/login_ajaxprocessor.jsp     |  244 ++
 .../web/stratos-gs/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-gs/images/body-bg.gif |  Bin 0 -> 923 bytes
 .../web/stratos-gs/images/feature-01-icon.gif   |  Bin 0 -> 3400 bytes
 .../web/stratos-gs/images/feature-02-icon.gif   |  Bin 0 -> 2879 bytes
 .../web/stratos-gs/images/feature-03-icon.gif   |  Bin 0 -> 3273 bytes
 .../web/stratos-gs/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-gs/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-gs/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-gs/images/login-bg.gif          |  Bin 0 -> 47812 bytes
 .../web/stratos-gs/images/paas-login-1pix-1.gif |  Bin 0 -> 43 bytes
 .../web/stratos-gs/images/powered-logo.gif      |  Bin 0 -> 1556 bytes
 .../web/stratos-gs/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-gs/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-gs/login_ajaxprocessor.jsp      |  244 ++
 .../web/stratos-is/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-is/images/body-bg.gif |  Bin 0 -> 923 bytes
 .../web/stratos-is/images/feature-01-icon.gif   |  Bin 0 -> 2576 bytes
 .../web/stratos-is/images/feature-02-icon.gif   |  Bin 0 -> 914 bytes
 .../web/stratos-is/images/feature-03-icon.gif   |  Bin 0 -> 2653 bytes
 .../web/stratos-is/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-is/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-is/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-is/images/login-bg.gif          |  Bin 0 -> 46601 bytes
 .../web/stratos-is/images/paas-login-1pix.gif   |  Bin 0 -> 43 bytes
 .../web/stratos-is/images/powered-logo.gif      |  Bin 0 -> 1499 bytes
 .../web/stratos-is/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-is/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-is/login_ajaxprocessor.jsp      |  253 ++
 .../web/stratos-mb/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-mb/images/body-bg.gif |  Bin 0 -> 923 bytes
 .../web/stratos-mb/images/feature-01-icon.gif   |  Bin 0 -> 2768 bytes
 .../web/stratos-mb/images/feature-02-icon.gif   |  Bin 0 -> 2240 bytes
 .../web/stratos-mb/images/feature-03-icon.gif   |  Bin 0 -> 2259 bytes
 .../web/stratos-mb/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-mb/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-mb/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-mb/images/login-bg.gif          |  Bin 0 -> 57103 bytes
 .../web/stratos-mb/images/paas-login-1pix-1.gif |  Bin 0 -> 43 bytes
 .../web/stratos-mb/images/powered-logo.gif      |  Bin 0 -> 2535 bytes
 .../web/stratos-mb/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-mb/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-mb/login_ajaxprocessor.jsp      |  244 ++
 .../web/stratos-ms/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-ms/images/body-bg.gif |  Bin 0 -> 923 bytes
 .../web/stratos-ms/images/feature-01-icon.gif   |  Bin 0 -> 3148 bytes
 .../web/stratos-ms/images/feature-02-icon.gif   |  Bin 0 -> 3159 bytes
 .../web/stratos-ms/images/feature-03-icon.gif   |  Bin 0 -> 2580 bytes
 .../web/stratos-ms/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-ms/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-ms/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-ms/images/login-bg.gif          |  Bin 0 -> 52737 bytes
 .../web/stratos-ms/images/paas-login-1pix-1.gif |  Bin 0 -> 43 bytes
 .../web/stratos-ms/images/powered-logo.gif      |  Bin 0 -> 1508 bytes
 .../web/stratos-ms/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-ms/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-ms/login_ajaxprocessor.jsp      |  243 ++
 .../web/stratos-ss/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-ss/images/body-bg.gif |  Bin 0 -> 1950 bytes
 .../web/stratos-ss/images/feature-01-icon.gif   |  Bin 0 -> 3146 bytes
 .../web/stratos-ss/images/feature-02-icon.gif   |  Bin 0 -> 3498 bytes
 .../web/stratos-ss/images/feature-03-icon.gif   |  Bin 0 -> 3202 bytes
 .../web/stratos-ss/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-ss/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-ss/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-ss/images/login-bg.gif          |  Bin 0 -> 30216 bytes
 .../web/stratos-ss/images/paas-login-1pix-1.gif |  Bin 0 -> 43 bytes
 .../web/stratos-ss/images/powered-logo.gif      |  Bin 0 -> 2274 bytes
 .../web/stratos-ss/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-ss/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-ss/login_ajaxprocessor.jsp      |  243 ++
 .../web/stratos-sso/css/stratos-loginpage.css   |  265 ++
 .../docs/images/sign-in-no-domain.png           |  Bin 0 -> 10682 bytes
 .../docs/images/sign-in-with-domain.png         |  Bin 0 -> 8233 bytes
 .../web/stratos-sso/docs/userguide.html         |   78 +
 .../web/stratos-sso/images/body-bg.gif          |  Bin 0 -> 923 bytes
 .../images/cloud-identity-sso-config-ok.png     |  Bin 0 -> 38465 bytes
 .../images/cloud-identity-sso-config.png        |  Bin 0 -> 32929 bytes
 .../web/stratos-sso/images/cloud-sso-config.png |  Bin 0 -> 29222 bytes
 .../resources/web/stratos-sso/images/delete.gif |  Bin 0 -> 555 bytes
 .../web/stratos-sso/images/feature-01-icon.gif  |  Bin 0 -> 2825 bytes
 .../web/stratos-sso/images/feature-02-icon.gif  |  Bin 0 -> 3361 bytes
 .../web/stratos-sso/images/feature-03-icon.gif  |  Bin 0 -> 3285 bytes
 .../stratos-sso/images/google-apps-login.gif    |  Bin 0 -> 4189 bytes
 .../resources/web/stratos-sso/images/import.gif |  Bin 0 -> 1051 bytes
 .../web/stratos-sso/images/link-icon.gif        |  Bin 0 -> 118 bytes
 .../web/stratos-sso/images/loading.gif          |  Bin 0 -> 14367 bytes
 .../web/stratos-sso/images/login-ad.gif         |  Bin 0 -> 14510 bytes
 .../web/stratos-sso/images/login-bg.gif         |  Bin 0 -> 56795 bytes
 .../resources/web/stratos-sso/images/logo.gif   |  Bin 0 -> 17603 bytes
 .../stratos-sso/images/paas-login-1pix-1.gif    |  Bin 0 -> 43 bytes
 .../web/stratos-sso/images/paas-login-1pix.gif  |  Bin 0 -> 43 bytes
 .../web/stratos-sso/images/paas-login-bg.gif    |  Bin 0 -> 65639 bytes
 .../images/paas-login-register-bg.gif           |  Bin 0 -> 5403 bytes
 .../images/paas-login-register-button.gif       |  Bin 0 -> 2617 bytes
 .../images/paas-login-register-hover.gif        |  Bin 0 -> 2697 bytes
 .../web/stratos-sso/images/paas-sign-in-bg.gif  |  Bin 0 -> 4352 bytes
 .../resources/web/stratos-sso/images/policy.gif |  Bin 0 -> 1017 bytes
 .../web/stratos-sso/images/powered-logo.gif     |  Bin 0 -> 1280 bytes
 .../web/stratos-sso/images/powered.gif          |  Bin 0 -> 1773 bytes
 .../web/stratos-sso/images/reg-button-hover.gif |  Bin 0 -> 3824 bytes
 .../web/stratos-sso/images/reg-button.gif       |  Bin 0 -> 3852 bytes
 .../web/stratos-sso/images/register.gif         |  Bin 0 -> 4099 bytes
 .../resources/web/stratos-sso/images/sso.gif    |  Bin 0 -> 394 bytes
 .../web/stratos-sso/images/st-login-body-bg.gif |  Bin 0 -> 2215 bytes
 .../stratos-sso/images/st-login-content-bg.gif  |  Bin 0 -> 1060 bytes
 .../stratos-sso/images/st-login-footer-bg.gif   |  Bin 0 -> 749 bytes
 .../stratos-sso/images/st-login-header-bg.gif   |  Bin 0 -> 64503 bytes
 .../web/stratos-sso/images/stratos_logo_h23.gif |  Bin 0 -> 1280 bytes
 .../web/stratos-sso/login_ajaxprocessor.jsp     |  255 ++
 .../web/stratos-sso/redirect_ajaxprocessor.jsp  |  168 ++
 .../web/stratos-ts/css/stratos-loginpage.css    |  265 ++
 .../resources/web/stratos-ts/images/body-bg.gif |  Bin 0 -> 1959 bytes
 .../web/stratos-ts/images/feature-01-icon.gif   |  Bin 0 -> 3138 bytes
 .../web/stratos-ts/images/feature-02-icon.gif   |  Bin 0 -> 3033 bytes
 .../web/stratos-ts/images/feature-03-icon.gif   |  Bin 0 -> 2259 bytes
 .../web/stratos-ts/images/google-apps-login.gif |  Bin 0 -> 4189 bytes
 .../web/stratos-ts/images/link-icon.gif         |  Bin 0 -> 118 bytes
 .../web/stratos-ts/images/login-ad.gif          |  Bin 0 -> 14510 bytes
 .../web/stratos-ts/images/login-bg.gif          |  Bin 0 -> 29105 bytes
 .../web/stratos-ts/images/paas-login-1pix-1.gif |  Bin 0 -> 43 bytes
 .../web/stratos-ts/images/powered-logo.gif      |  Bin 0 -> 2535 bytes
 .../web/stratos-ts/images/reg-button-hover.gif  |  Bin 0 -> 3824 bytes
 .../web/stratos-ts/images/reg-button.gif        |  Bin 0 -> 3852 bytes
 .../web/stratos-ts/login_ajaxprocessor.jsp      |  244 ++
 .../2.1.0/pom.xml                               |   88 +
 .../identity/saml2/sso/mgt/SSOMgtConstants.java |   27 +
 .../mgt/SSOServiceProviderUpdateManager.java    |  129 +
 .../internal/StratosSSOMgtServiceComponent.java |   71 +
 components/stratos/sso-mgt/pom.xml              |   37 +
 .../2.1.0/pom.xml                               |  105 +
 .../agent/clients/ClientThreadsInitializer.java |  147 +
 .../clients/common/LoadBalanceAgentClient.java  |   91 +
 .../clients/common/ServiceLoginClient.java      |   98 +
 .../service/ApplicationServerClient.java        |  250 ++
 .../agent/clients/service/BAMServerClient.java  |   71 +
 .../agent/clients/service/BPSServerClient.java  |  125 +
 .../agent/clients/service/BRSServerClient.java  |  135 +
 .../agent/clients/service/CEPServerClient.java  |  151 ++
 .../agent/clients/service/DataServerClient.java |  187 ++
 .../agent/clients/service/ESBServerClient.java  |  241 ++
 .../clients/service/GadgetServerClient.java     |  108 +
 .../service/GovernanceRegistryServerClient.java |  179 ++
 .../clients/service/IdentityServerClient.java   |  114 +
 .../clients/service/ManagerServiceClient.java   |  111 +
 .../clients/service/MashupServerClient.java     |  189 ++
 .../service/MessageBrokerServiceClient.java     |  155 ++
 .../constants/StatusMonitorAgentConstants.java  |   52 +
 .../internal/StatusMonitorAgentComponent.java   |  109 +
 .../agent/internal/core/MySQLConnector.java     |  274 ++
 .../2.1.0/pom.xml                               |   78 +
 .../core/StatusMonitorConfigurationBuilder.java |  244 ++
 .../monitor/core/beans/AuthConfigBean.java      |   58 +
 .../core/beans/SampleTenantConfigBean.java      |   31 +
 .../core/constants/StatusMonitorConstants.java  |  149 +
 .../core/exception/StatusMonitorException.java  |   33 +
 .../internal/StatusMonitorCoreComponent.java    |   91 +
 .../core/jdbc/MySQLConnectionInitializer.java   |  244 ++
 .../monitor/core/util/StatusMonitorUtil.java    |   69 +
 .../src/main/resources/META-INF/component.xml   |   41 +
 .../resources/database/wso2_slive_status.sql    |  148 +
 .../2.1.0/pom.xml                               |   80 +
 .../ui/clients/HealthMonitorServiceClient.java  |  104 +
 .../monitor/ui/utils/StatusMonitorUtil.java     |  107 +
 .../src/main/resources/META-INF/component.xml   |   48 +
 .../monitor/ui/i18n/JSResources.properties      |    0
 .../status/monitor/ui/i18n/Resources.properties |   12 +
 .../resources/web/status-monitor/css/status.css |   62 +
 .../status-monitor/docs/images/view-details.png |  Bin 0 -> 121916 bytes
 .../status-monitor/docs/images/view-status.png  |  Bin 0 -> 149085 bytes
 .../web/status-monitor/docs/userguide.html      |   56 +
 .../web/status-monitor/images/services.gif      |  Bin 0 -> 604 bytes
 .../web/status-monitor/images/services1.gif     |  Bin 0 -> 608 bytes
 .../web/status-monitor/service-status.jsp       |  126 +
 .../web/status-monitor/status-details.jsp       |  137 +
 .../2.1.0/pom.xml                               |   79 +
 .../beans/ServiceStateDetailInfoBean.java       |   59 +
 .../monitor/beans/ServiceStateInfoBean.java     |   58 +
 .../internal/StatusMonitorServiceComponent.java |  102 +
 .../monitor/internal/core/MySQLConnector.java   |  168 ++
 .../monitor/services/HealthMonitorService.java  |   65 +
 .../src/main/resources/META-INF/component.xml   |   41 +
 .../src/main/resources/META-INF/services.xml    |   34 +
 components/stratos/status-monitor/pom.xml       |   42 +
 .../2.1.0/pom.xml                               |  132 +
 .../ui/clients/TenantActivityServiceClient.java |  155 ++
 .../TenantActivityUIServiceComponent.java       |   57 +
 .../ui/utils/ManagerConfigurations.java         |  148 +
 .../activity/ui/utils/TenantMonitorUtil.java    |  143 +
 .../src/main/resources/META-INF/component.xml   |   35 +
 .../activity/ui/i18n/JSResources.properties     |    1 +
 .../activity/ui/i18n/Resources.properties       |   11 +
 .../web/tenant-activity/css/tenant-usage.css    |   28 +
 .../tenant-activity/docs/images/view-usage.png  |  Bin 0 -> 44786 bytes
 .../web/tenant-activity/docs/userguide.html     |   76 +
 .../find-tenant-ajaxprocessor.jsp               |   59 +
 .../web/tenant-activity/find-tenant.jsp         |  110 +
 .../tenant-activity/get-data-ajaxprocessor.jsp  |   66 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../web/tenant-activity/images/search.gif       |  Bin 0 -> 191 bytes
 .../images/tenant-usage-report.gif              |  Bin 0 -> 1008 bytes
 .../images/user-usage-report.gif                |  Bin 0 -> 1033 bytes
 .../web/tenant-activity/show-active-tenants.jsp |  129 +
 .../web/tenant-activity/tenant-activity.jsp     |  174 ++
 .../2.1.0/pom.xml                               |  144 +
 .../activity/beans/PaginatedTenantDataBean.java |   52 +
 .../tenant/activity/beans/TenantDataBean.java   |   98 +
 .../GetActiveTenantsInMemberRequest.java        |   59 +
 .../GetActiveTenantsInMemberResponse.java       |   54 +
 .../TenantActivityServiceComponent.java         |   99 +
 .../services/TenantActivityService.java         |   83 +
 .../activity/util/TenantActivityUtil.java       |   79 +
 .../wso2/carbon/tenant/activity/util/Util.java  |   85 +
 .../src/main/resources/META-INF/component.xml   |   37 +
 .../src/main/resources/META-INF/services.xml    |   42 +
 components/stratos/tenant-activity/pom.xml      |   41 +
 .../2.1.0/pom.xml                               |   81 +
 .../tenant/mgt/core/DefaultTenantPersistor.java |  340 +++
 .../internal/TenantMgtCoreServiceComponent.java |  129 +
 .../tenant/mgt/core/util/TenantCoreUtil.java    |   80 +
 .../2.1.0/pom.xml                               |   97 +
 .../mgt/email/sender/internal/DataHolder.java   |  104 +
 .../TenantMgtEmailSenderServiceComponent.java   |  105 +
 .../sender/listener/EmailSenderListener.java    |   70 +
 .../sender/util/TenantMgtEmailSenderUtil.java   |  482 ++++
 .../org.wso2.carbon.tenant.mgt.ui/2.1.0/pom.xml |  117 +
 .../ui/clients/PackageInfoServiceClient.java    |   79 +
 .../mgt/ui/clients/TenantServiceClient.java     |  120 +
 .../tenant/mgt/ui/utils/TenantMgtUtil.java      |  217 ++
 .../src/main/resources/META-INF/component.xml   |   61 +
 .../tenant/mgt/ui/i18n/JSResources.properties   |    4 +
 .../tenant/mgt/ui/i18n/Resources.properties     |   56 +
 .../activate_tenant_ajaxprocessor.jsp           |   57 +
 .../resources/web/tenant-mgt/add_tenant.jsp     |  386 +++
 .../check_domain_availability_ajaxprocessor.jsp |   19 +
 .../resources/web/tenant-mgt/css/tenant.css     |   62 +
 .../web/tenant-mgt/docs/aboutUsagePlans.html    |  104 +
 .../web/tenant-mgt/docs/images/add-org.png      |  Bin 0 -> 49926 bytes
 .../web/tenant-mgt/docs/images/add-tenant.png   |  Bin 0 -> 28704 bytes
 .../web/tenant-mgt/docs/images/view-tenants.png |  Bin 0 -> 11896 bytes
 .../web/tenant-mgt/docs/userguide.html          |   56 +
 .../get_package_info_ajaxprocessor.jsp          |   39 +
 .../web/tenant-mgt/images/multi_tenancy.png     |  Bin 0 -> 768 bytes
 .../web/tenant-mgt/images/services.gif          |  Bin 0 -> 604 bytes
 .../web/tenant-mgt/images/services1.gif         |  Bin 0 -> 608 bytes
 .../web/tenant-mgt/js/tenant_config.js          |  218 ++
 .../web/tenant-mgt/js/theme_resource_util.js    |    0
 .../tenant-mgt/submit_tenant_ajaxprocessor.jsp  |   84 +
 .../resources/web/tenant-mgt/view_tenants.jsp   |  236 ++
 .../org.wso2.carbon.tenant.mgt/2.1.0/pom.xml    |  120 +
 .../mgt/beans/PaginatedTenantInfoBean.java      |   52 +
 .../exception/TenantManagementException.java    |   33 +
 .../mgt/internal/TenantMgtServiceComponent.java |  261 ++
 .../mgt/internal/util/TenantMgtRampartUtil.java |   48 +
 .../mgt/realm/CloudWSRealmConfigBuilder.java    |  138 +
 .../mgt/realm/IdaasWSRealmConfigBuilder.java    |   87 +
 .../services/GAppTenantRegistrationService.java |  120 +
 .../InMemoryPasswordcallbackHandler.java        |   38 +
 .../mgt/services/TenantMgtAdminService.java     |  497 ++++
 .../services/TenantSelfRegistrationService.java |  193 ++
 .../carbon/tenant/mgt/util/TenantMgtUtil.java   |  443 +++
 .../util/TenantRegistryDataDeletionUtil.java    |  119 +
 .../mgt/util/TenantUMDataDeletionUtil.java      |  112 +
 .../src/main/resources/META-INF/component.xml   |   41 +
 .../src/main/resources/META-INF/services.xml    |  155 ++
 .../2.1.0/pom.xml                               |  123 +
 .../ui/clients/PackageInfoServiceClient.java    |   77 +
 .../clients/TenantSelfRegistrationClient.java   |  107 +
 .../register/ui/utils/TenantConfigUtil.java     |  248 ++
 .../src/main/resources/META-INF/component.xml   |   70 +
 .../register/ui/i18n/JSResources.properties     |    6 +
 .../register/ui/i18n/Resources.properties       |   62 +
 .../web/tenant-register/css/tenant-register.css |   78 +
 .../tenant-register/docs/aboutUsagePlans.html   |  104 +
 .../web/tenant-register/docs/images/add-org.png |  Bin 0 -> 62035 bytes
 .../web/tenant-register/docs/userguide.html     |  104 +
 .../domain_availability_ajaxprocessor.jsp       |   50 +
 .../get_package_info_ajaxprocessor.jsp          |   39 +
 .../web/tenant-register/images/ajax-loader.gif  |  Bin 0 -> 673 bytes
 .../web/tenant-register/images/body-bg.gif      |  Bin 0 -> 419 bytes
 .../web/tenant-register/images/button-back.gif  |  Bin 0 -> 819 bytes
 .../images/content-back-left.jpg                |  Bin 0 -> 2240 bytes
 .../web/tenant-register/images/content-back.jpg |  Bin 0 -> 852 bytes
 .../images/create-org-button.gif                |  Bin 0 -> 2576 bytes
 .../tenant-register/images/feature-01-icon.gif  |  Bin 0 -> 2825 bytes
 .../tenant-register/images/feature-02-icon.gif  |  Bin 0 -> 3361 bytes
 .../tenant-register/images/feature-03-icon.gif  |  Bin 0 -> 3285 bytes
 .../web/tenant-register/images/features-bg.gif  |  Bin 0 -> 4449 bytes
 .../web/tenant-register/images/footer.jpg       |  Bin 0 -> 836 bytes
 .../web/tenant-register/images/forum.gif        |  Bin 0 -> 1977 bytes
 .../web/tenant-register/images/header.jpg       |  Bin 0 -> 5837 bytes
 .../web/tenant-register/images/help.gif         |  Bin 0 -> 1229 bytes
 .../web/tenant-register/images/images.gif       |  Bin 0 -> 1067 bytes
 .../tenant-register/images/issue-tracker.gif    |  Bin 0 -> 1821 bytes
 .../web/tenant-register/images/logo.jpg         |  Bin 0 -> 7171 bytes
 .../web/tenant-register/images/mailing-list.gif |  Bin 0 -> 2064 bytes
 .../web/tenant-register/images/page-back.jpg    |  Bin 0 -> 871 bytes
 .../web/tenant-register/images/people.gif       |  Bin 0 -> 22151 bytes
 .../web/tenant-register/images/services.gif     |  Bin 0 -> 604 bytes
 .../tenant-register/images/signup-new-org.gif   |  Bin 0 -> 356 bytes
 .../web/tenant-register/images/thememgt.gif     |  Bin 0 -> 1030 bytes
 .../web/tenant-register/images/user-guide.gif   |  Bin 0 -> 2161 bytes
 .../init_payment_ajaxprocessor.jsp              |  101 +
 .../web/tenant-register/js/register_config.js   |  147 +
 .../web/tenant-register/js/select_domain.js     |   75 +
 .../web/tenant-register/select_domain.jsp       |  389 +++
 .../web/tenant-register/select_usage_plan.jsp   |  279 ++
 .../submit_tenant_ajaxprocessor.jsp             |   66 +
 .../web/tenant-register/success_register.jsp    |   77 +
 .../2.1.1/pom.xml                               |  124 +
 .../ui/clients/PackageInfoServiceClient.java    |   77 +
 .../clients/TenantSelfRegistrationClient.java   |  107 +
 .../register/ui/utils/TenantConfigUtil.java     |  248 ++
 .../src/main/resources/META-INF/component.xml   |   70 +
 .../register/ui/i18n/JSResources.properties     |    6 +
 .../register/ui/i18n/Resources.properties       |   62 +
 .../web/tenant-register/css/tenant-register.css |   78 +
 .../tenant-register/docs/aboutUsagePlans.html   |  104 +
 .../web/tenant-register/docs/images/add-org.png |  Bin 0 -> 62035 bytes
 .../web/tenant-register/docs/userguide.html     |  104 +
 .../domain_availability_ajaxprocessor.jsp       |   50 +
 .../get_package_info_ajaxprocessor.jsp          |   39 +
 .../web/tenant-register/images/ajax-loader.gif  |  Bin 0 -> 673 bytes
 .../web/tenant-register/images/body-bg.gif      |  Bin 0 -> 419 bytes
 .../web/tenant-register/images/button-back.gif  |  Bin 0 -> 819 bytes
 .../images/content-back-left.jpg                |  Bin 0 -> 2240 bytes
 .../web/tenant-register/images/content-back.jpg |  Bin 0 -> 852 bytes
 .../images/create-org-button.gif                |  Bin 0 -> 2576 bytes
 .../tenant-register/images/feature-01-icon.gif  |  Bin 0 -> 2825 bytes
 .../tenant-register/images/feature-02-icon.gif  |  Bin 0 -> 3361 bytes
 .../tenant-register/images/feature-03-icon.gif  |  Bin 0 -> 3285 bytes
 .../web/tenant-register/images/features-bg.gif  |  Bin 0 -> 4449 bytes
 .../web/tenant-register/images/footer.jpg       |  Bin 0 -> 836 bytes
 .../web/tenant-register/images/forum.gif        |  Bin 0 -> 1977 bytes
 .../web/tenant-register/images/header.jpg       |  Bin 0 -> 5837 bytes
 .../web/tenant-register/images/help.gif         |  Bin 0 -> 1229 bytes
 .../web/tenant-register/images/images.gif       |  Bin 0 -> 1067 bytes
 .../tenant-register/images/issue-tracker.gif    |  Bin 0 -> 1821 bytes
 .../web/tenant-register/images/logo.jpg         |  Bin 0 -> 7171 bytes
 .../web/tenant-register/images/mailing-list.gif |  Bin 0 -> 2064 bytes
 .../web/tenant-register/images/page-back.jpg    |  Bin 0 -> 871 bytes
 .../web/tenant-register/images/people.gif       |  Bin 0 -> 22151 bytes
 .../web/tenant-register/images/services.gif     |  Bin 0 -> 604 bytes
 .../tenant-register/images/signup-new-org.gif   |  Bin 0 -> 356 bytes
 .../web/tenant-register/images/thememgt.gif     |  Bin 0 -> 1030 bytes
 .../web/tenant-register/images/user-guide.gif   |  Bin 0 -> 2161 bytes
 .../init_payment_ajaxprocessor.jsp              |  101 +
 .../web/tenant-register/js/register_config.js   |  147 +
 .../web/tenant-register/js/select_domain.js     |   75 +
 .../web/tenant-register/select_domain.jsp       |  389 +++
 .../web/tenant-register/select_usage_plan.jsp   |  279 ++
 .../submit_tenant_ajaxprocessor.jsp             |   66 +
 .../web/tenant-register/success_register.jsp    |   77 +
 components/stratos/tenant-mgt/pom.xml           |   44 +
 .../org.wso2.carbon.theme.mgt.ui/2.1.0/pom.xml  |  148 +
 .../mgt/ui/clients/ThemeMgtServiceClient.java   |  424 +++
 .../processors/AddThemeResourceProcessor.java   |  240 ++
 .../mgt/ui/servlets/ThemeResourceSevelet.java   |  124 +
 .../carbon/theme/mgt/ui/utils/ThemeUtil.java    |   67 +
 .../src/main/resources/META-INF/component.xml   |   68 +
 .../theme/mgt/ui/i18n/JSResources.properties    |    2 +
 .../theme/mgt/ui/i18n/Resources.properties      |   51 +
 .../add_collection_ajaxprocessor.jsp            |   49 +
 .../add_text_resource_ajaxprocessor.jsp         |   57 +
 .../web/tenant-theme/content_ajaxprocessor.jsp  |  241 ++
 .../resources/web/tenant-theme/css-editor.jsp   |   58 +
 .../web/tenant-theme/css/loginpage.css          |  110 +
 .../resources/web/tenant-theme/css/tenant.css   |   74 +
 .../web/tenant-theme/css/tenent-theme.css       |   32 +
 .../web/tenant-theme/css/theme-mgt.css          |   16 +
 .../web/tenant-theme/delete_ajaxprocessor.jsp   |   47 +
 .../display_text_content_ajaxprocessor.jsp      |   47 +
 .../tenant-theme/docs/images/change-logo.png    |  Bin 0 -> 14821 bytes
 .../web/tenant-theme/docs/images/edit-theme.png |  Bin 0 -> 83056 bytes
 .../tenant-theme/docs/images/select-theme.png   |  Bin 0 -> 61602 bytes
 .../web/tenant-theme/docs/userguide.html        |   77 +
 .../edit_text_content_ajaxprocessor.jsp         |   96 +
 .../web/tenant-theme/images/ajax-loader.gif     |  Bin 0 -> 673 bytes
 .../web/tenant-theme/images/button-back.gif     |  Bin 0 -> 819 bytes
 .../tenant-theme/images/content-back-left.jpg   |  Bin 0 -> 2240 bytes
 .../web/tenant-theme/images/content-back.jpg    |  Bin 0 -> 852 bytes
 .../tenant-theme/images/create-org-button.gif   |  Bin 0 -> 2576 bytes
 .../web/tenant-theme/images/footer.jpg          |  Bin 0 -> 836 bytes
 .../resources/web/tenant-theme/images/forum.gif |  Bin 0 -> 1977 bytes
 .../web/tenant-theme/images/header.jpg          |  Bin 0 -> 5837 bytes
 .../resources/web/tenant-theme/images/help.gif  |  Bin 0 -> 1229 bytes
 .../web/tenant-theme/images/images.gif          |  Bin 0 -> 1067 bytes
 .../web/tenant-theme/images/issue-tracker.gif   |  Bin 0 -> 1821 bytes
 .../resources/web/tenant-theme/images/logo.jpg  |  Bin 0 -> 7171 bytes
 .../web/tenant-theme/images/logomgt.gif         |  Bin 0 -> 596 bytes
 .../web/tenant-theme/images/mailing-list.gif    |  Bin 0 -> 2064 bytes
 .../web/tenant-theme/images/page-back.jpg       |  Bin 0 -> 871 bytes
 .../web/tenant-theme/images/people.gif          |  Bin 0 -> 22151 bytes
 .../web/tenant-theme/images/sel-02.jpg          |  Bin 0 -> 809 bytes
 .../web/tenant-theme/images/services.gif        |  Bin 0 -> 604 bytes
 .../web/tenant-theme/images/thememgt.gif        |  Bin 0 -> 1030 bytes
 .../web/tenant-theme/images/user-guide.gif      |  Bin 0 -> 2161 bytes
 .../import_resource_ajaxprocessor.jsp           |  100 +
 .../web/tenant-theme/js/editarea/change_log.txt |  281 ++
 .../js/editarea/edit_area/autocompletion.js     |  491 ++++
 .../js/editarea/edit_area/edit_area.css         |  530 ++++
 .../js/editarea/edit_area/edit_area.js          |  525 ++++
 .../js/editarea/edit_area/edit_area_full.js     |   38 +
 .../editarea/edit_area/edit_area_functions.js   | 1203 ++++++++
 .../js/editarea/edit_area/edit_area_loader.js   | 1080 ++++++++
 .../js/editarea/edit_area/elements_functions.js |  333 +++
 .../js/editarea/edit_area/highlight.js          |  391 +++
 .../edit_area/images/autocompletion.gif         |  Bin 0 -> 359 bytes
 .../js/editarea/edit_area/images/close.gif      |  Bin 0 -> 102 bytes
 .../js/editarea/edit_area/images/fullscreen.gif |  Bin 0 -> 198 bytes
 .../js/editarea/edit_area/images/go_to_line.gif |  Bin 0 -> 1053 bytes
 .../js/editarea/edit_area/images/help.gif       |  Bin 0 -> 295 bytes
 .../js/editarea/edit_area/images/highlight.gif  |  Bin 0 -> 256 bytes
 .../js/editarea/edit_area/images/load.gif       |  Bin 0 -> 1041 bytes
 .../js/editarea/edit_area/images/move.gif       |  Bin 0 -> 257 bytes
 .../editarea/edit_area/images/newdocument.gif   |  Bin 0 -> 170 bytes
 .../js/editarea/edit_area/images/opacity.png    |  Bin 0 -> 147 bytes
 .../js/editarea/edit_area/images/processing.gif |  Bin 0 -> 825 bytes
 .../js/editarea/edit_area/images/redo.gif       |  Bin 0 -> 169 bytes
 .../edit_area/images/reset_highlight.gif        |  Bin 0 -> 168 bytes
 .../js/editarea/edit_area/images/save.gif       |  Bin 0 -> 285 bytes
 .../js/editarea/edit_area/images/search.gif     |  Bin 0 -> 191 bytes
 .../edit_area/images/smooth_selection.gif       |  Bin 0 -> 174 bytes
 .../js/editarea/edit_area/images/spacer.gif     |  Bin 0 -> 43 bytes
 .../edit_area/images/statusbar_resize.gif       |  Bin 0 -> 79 bytes
 .../js/editarea/edit_area/images/undo.gif       |  Bin 0 -> 175 bytes
 .../js/editarea/edit_area/images/word_wrap.gif  |  Bin 0 -> 951 bytes
 .../js/editarea/edit_area/keyboard.js           |  145 +
 .../js/editarea/edit_area/langs/en.js           |   67 +
 .../js/editarea/edit_area/license_apache.txt    |    7 +
 .../js/editarea/edit_area/license_bsd.txt       |   10 +
 .../js/editarea/edit_area/license_lgpl.txt      |  458 ++++
 .../js/editarea/edit_area/manage_area.js        |  623 +++++
 .../js/editarea/edit_area/reg_syntax.js         |  166 ++
 .../js/editarea/edit_area/reg_syntax/basic.js   |   69 +
 .../editarea/edit_area/reg_syntax/brainfuck.js  |   44 +
 .../js/editarea/edit_area/reg_syntax/c.js       |   62 +
 .../editarea/edit_area/reg_syntax/coldfusion.js |  119 +
 .../js/editarea/edit_area/reg_syntax/cpp.js     |   65 +
 .../js/editarea/edit_area/reg_syntax/css.js     |   84 +
 .../js/editarea/edit_area/reg_syntax/html.js    |   50 +
 .../js/editarea/edit_area/reg_syntax/java.js    |   56 +
 .../js/editarea/edit_area/reg_syntax/js.js      |   93 +
 .../js/editarea/edit_area/reg_syntax/pas.js     |   82 +
 .../js/editarea/edit_area/reg_syntax/perl.js    |   88 +
 .../js/editarea/edit_area/reg_syntax/php.js     |  156 ++
 .../js/editarea/edit_area/reg_syntax/python.js  |  144 +
 .../editarea/edit_area/reg_syntax/robotstxt.js  |   24 +
 .../js/editarea/edit_area/reg_syntax/ruby.js    |   67 +
 .../js/editarea/edit_area/reg_syntax/sql.js     |   55 +
 .../js/editarea/edit_area/reg_syntax/tsql.js    |   87 +
 .../js/editarea/edit_area/reg_syntax/vb.js      |   52 +
 .../js/editarea/edit_area/reg_syntax/xml.js     |   56 +
 .../js/editarea/edit_area/regexp.js             |  139 +
 .../js/editarea/edit_area/resize_area.js        |   73 +
 .../js/editarea/edit_area/search_replace.js     |  174 ++
 .../js/editarea/edit_area/template.html         |  117 +
 .../tenant-theme/js/editarea/license_apache.txt |    7 +
 .../tenant-theme/js/editarea/license_bsd.txt    |   10 +
 .../tenant-theme/js/editarea/license_lgpl.txt   |  458 ++++
 .../web/tenant-theme/js/editarea/todo.txt       |   71 +
 .../web/tenant-theme/js/theme_resource_util.js  |  828 ++++++
 .../resources/web/tenant-theme/logo_mgt.jsp     |  220 ++
 .../web/tenant-theme/metadata_resourcepath.jsp  |  106 +
 .../web/tenant-theme/raw-collection-content.jsp |  755 ++++++
 .../rename_resource_ajaxprocessor.jsp           |   41 +
 .../web/tenant-theme/theme_advanced.jsp         |  139 +
 .../resources/web/tenant-theme/theme_mgt.jsp    |  239 ++
 .../tenant-theme/theme_mgt_ajaxprocessor.jsp    |   48 +
 .../web/tenant-theme/update_text_content.jsp    |   51 +
 .../org.wso2.carbon.theme.mgt/2.1.0/pom.xml     |  102 +
 .../TenantThemeMgtServiceComponent.java         |   99 +
 .../theme/mgt/services/ThemeMgtService.java     |  195 ++
 .../theme/mgt/util/ThemeLoadingListener.java    |   73 +
 .../wso2/carbon/theme/mgt/util/ThemeUtil.java   |  302 +++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |  103 +
 components/stratos/theme-mgt/pom.xml            |   41 +
 .../2.1.0/pom.xml                               |  136 +
 .../throttling/agent/ThrottlingAgent.java       |  244 ++
 .../Axis2ConfigurationContextObserverImpl.java  |   42 +
 .../agent/cache/TenantThrottlingInfo.java       |   53 +
 .../agent/cache/ThrottlingActionInfo.java       |   37 +
 .../agent/cache/ThrottlingInfoCache.java        |  118 +
 .../cache/ThrottlingInfoCacheUpdaterTask.java   |   79 +
 .../MultitenancyThrottlingServiceClient.java    |   62 +
 .../agent/client/ThrottlingRuleInvoker.java     |   20 +
 .../conf/ThrottlingAgentConfiguration.java      |   85 +
 .../ThrottlingAgentServiceComponent.java        |  193 ++
 .../listeners/PerRegistryRequestListener.java   |  116 +
 .../agent/listeners/PerUserAddListener.java     |   87 +
 .../agent/listeners/ServiceRequestListener.java |  113 +
 .../agent/listeners/ThrottlingModule.java       |   49 +
 .../agent/listeners/WebAppRequestListener.java  |  179 ++
 .../agent/validation/ValidationException.java   |   25 +
 .../agent/validation/ValidationInfo.java        |   39 +
 .../validation/ValidationInfoRetriever.java     |  109 +
 .../src/main/resources/META-INF/module.xml      |   33 +
 .../MultitenancyThrottlingService.wsdl          |   82 +
 .../2.1.0/pom.xml                               |  170 ++
 .../manager/conf/ThrottlingConfiguration.java   |  104 +
 .../conf/ThrottlingTaskConfiguration.java       |  117 +
 ...ThrottlingTaskDataProviderConfiguration.java |  114 +
 .../dataobjects/ThrottlingAccessValidation.java |   70 +
 .../dataobjects/ThrottlingDataContext.java      |  145 +
 .../dataobjects/ThrottlingDataEntry.java        |   84 +
 .../ThrottlingDataEntryConstants.java           |   41 +
 .../dataproviders/BillingDataProvider.java      |   52 +
 .../manager/dataproviders/DataProvider.java     |   35 +
 .../dataproviders/UsageDataProvider.java        |  103 +
 .../manager/exception/ThrottlingException.java  |   25 +
 .../ThrottlingManagerServiceComponent.java      |  129 +
 .../manager/rules/KnowledgeBaseManager.java     |   70 +
 .../throttling/manager/rules/RuleInvoker.java   |   89 +
 .../throttling/manager/rules/RuleProperty.java  |   42 +
 .../manager/scheduling/ThrottlingJob.java       |  117 +
 .../services/MultitenancyThrottlingService.java |   58 +
 .../services/ThrottlingRuleEditorService.java   |   87 +
 .../carbon/throttling/manager/tasks/Task.java   |   91 +
 .../manager/utils/DataProviderIterator.java     |   69 +
 .../carbon/throttling/manager/utils/Util.java   |  461 ++++
 .../validation/ValidationInfoManager.java       |  119 +
 .../src/main/resources/META-INF/component.xml   |   37 +
 .../src/main/resources/META-INF/services.xml    |   49 +
 .../carbon/throttling/test/ThrottlingTest.java  |  226 ++
 .../throttling/test/utils/BaseTestCase.java     |  113 +
 .../test/utils/CustomDataProvider.java          |   43 +
 .../resources/carbon-home/dbscripts/db2.sql     |  450 +++
 .../resources/carbon-home/dbscripts/derby.sql   |  364 +++
 .../test/resources/carbon-home/dbscripts/h2.sql |  337 +++
 .../resources/carbon-home/dbscripts/mssql.sql   |  494 ++++
 .../resources/carbon-home/dbscripts/mysql.sql   |  370 +++
 .../resources/carbon-home/dbscripts/oracle.sql  |  644 +++++
 .../carbon-home/dbscripts/oracle_rac.sql        |  644 +++++
 .../carbon-home/dbscripts/postgresql.sql        |  427 +++
 .../resources/carbon-home/repository/README     |   22 +
 .../carbon-home/repository/conf/README          |   39 +
 .../carbon-home/repository/conf/axis2.xml       |  630 +++++
 .../repository/conf/axis2_client.xml            |  280 ++
 .../repository/conf/broker-config.xml           |   52 +
 .../carbon-home/repository/conf/carbon.xml      |  351 +++
 .../repository/conf/cipher-text.properties      |    8 +
 .../repository/conf/mgt-transports.xml          |   84 +
 .../carbon-home/repository/conf/mime.types      |  727 +++++
 .../repository/conf/node/registry.xml           |   81 +
 .../repository/conf/node/user-mgt.xml           |  105 +
 .../repository/conf/ports-config.xml            |   55 +
 .../carbon-home/repository/conf/registry.xml    |   99 +
 .../repository/conf/secret-conf.properties      |   37 +
 .../carbon-home/repository/conf/synapse.xml     |   30 +
 .../repository/conf/throttling-config1.xml      |   47 +
 .../repository/conf/throttling-config2.xml      |   47 +
 .../repository/conf/throttling-config3.xml      |   47 +
 .../repository/conf/throttling-rules1.drl       |   60 +
 .../repository/conf/throttling-rules2.drl       |   18 +
 .../repository/conf/throttling-rules3.drl       |   17 +
 .../carbon-home/repository/conf/user-mgt.xml    |  114 +
 .../carbon-home/repository/conf/wrapper.conf    |  125 +
 .../carbon-home/repository/logs/README          |    1 +
 .../2.1.0/src/test/resources/registry.xml       |  247 ++
 .../user-test/adv-jdbc-readonly-test.xml        |   59 +
 .../resources/user-test/jdbc-readonly-test.xml  |   59 +
 .../user-test/user-mgt-registry-test.xml        |   94 +
 .../test/resources/user-test/user-mgt-test.xml  |   95 +
 .../org.wso2.carbon.throttling.ui/2.1.0/pom.xml |  120 +
 .../ui/clients/ThrottlingRuleEditorClient.java  |   97 +
 .../src/main/resources/META-INF/component.xml   |   36 +
 .../resources/ThrottlingRuleEditorService.wsdl  |  148 +
 .../throttling/ui/i18n/JSResources.properties   |    1 +
 .../throttling/ui/i18n/Resources.properties     |    2 +
 .../web/mt-throttling/docs/images/add-org.png   |  Bin 0 -> 49926 bytes
 .../web/mt-throttling/docs/userguide.html       |   35 +
 .../web/mt-throttling/images/throttling.gif     |  Bin 0 -> 1008 bytes
 .../resources/web/mt-throttling/throttling.jsp  |  103 +
 .../mt-throttling/throttling_ajaxprocessor.jsp  |   29 +
 components/stratos/throttling/pom.xml           |   42 +
 .../org.wso2.carbon.usage.agent/2.1.0/pom.xml   |  141 +
 .../usage/agent/api/CustomMeteringAgent.java    |  222 ++
 .../usage/agent/beans/BandwidthUsage.java       |   60 +
 .../agent/config/UsageAgentConfiguration.java   |  116 +
 .../usage/agent/exception/UsageException.java   |   28 +
 .../internal/UsageAgentServiceComponent.java    |  204 ++
 .../agent/listeners/RegistryUsageListener.java  |  362 +++
 .../RegistryUsagePersistingListener.java        |  312 +++
 .../agent/listeners/StatisticsInHandler.java    |   56 +
 .../agent/listeners/StatisticsOutHandler.java   |   67 +
 ...eStatsAxis2ConfigurationContextObserver.java |   31 +
 .../listeners/axis2/RequestMeteringHandler.java |  108 +
 .../listeners/axis2/RequestMeteringModule.java  |   44 +
 .../usage/agent/persist/BandwidthPersistor.java |   55 +
 .../BandwidthUsageDataRetrievalTask.java        |  115 +
 .../agent/persist/RegistryUsagePersister.java   |   73 +
 .../agent/persist/ServiceDataPersistor.java     |   69 +
 .../persist/UsageDataPersistenceManager.java    |   88 +
 .../agent/persist/UsageDataPersistenceTask.java |  163 ++
 .../agent/services/CustomMeteringService.java   |   92 +
 .../usage/agent/util/MonitoredReader.java       |   47 +
 .../usage/agent/util/MonitoredWriter.java       |   50 +
 .../carbon/usage/agent/util/PublisherUtils.java |  395 +++
 .../usage/agent/util/UsageAgentConstants.java   |   49 +
 .../org/wso2/carbon/usage/agent/util/Util.java  |  175 ++
 .../src/main/resources/META-INF/component.xml   |   33 +
 .../src/main/resources/META-INF/module.xml      |   50 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../META-INF/usage-throttling-agent-config.xml  |   15 +
 .../org.wso2.carbon.usage.agent/2.1.1/pom.xml   |  143 +
 .../usage/agent/api/CustomMeteringAgent.java    |  222 ++
 .../agent/beans/APIManagerRequestStats.java     |   97 +
 .../usage/agent/beans/BandwidthUsage.java       |   60 +
 .../agent/config/UsageAgentConfiguration.java   |  116 +
 .../usage/agent/exception/UsageException.java   |   28 +
 .../internal/UsageAgentServiceComponent.java    |  204 ++
 .../agent/listeners/RegistryUsageListener.java  |  362 +++
 .../RegistryUsagePersistingListener.java        |  312 +++
 .../agent/listeners/StatisticsInHandler.java    |   56 +
 .../agent/listeners/StatisticsOutHandler.java   |   67 +
 ...eStatsAxis2ConfigurationContextObserver.java |   31 +
 .../listeners/axis2/RequestMeteringHandler.java |  108 +
 .../listeners/axis2/RequestMeteringModule.java  |   44 +
 .../usage/agent/persist/BandwidthPersistor.java |   55 +
 .../BandwidthUsageDataRetrievalTask.java        |  115 +
 .../agent/persist/RegistryUsagePersister.java   |   73 +
 .../agent/persist/ServiceDataPersistor.java     |   69 +
 .../persist/UsageDataPersistenceManager.java    |   88 +
 .../agent/persist/UsageDataPersistenceTask.java |  163 ++
 .../agent/services/CustomMeteringService.java   |   92 +
 .../usage/agent/util/MonitoredReader.java       |   47 +
 .../usage/agent/util/MonitoredWriter.java       |   50 +
 .../carbon/usage/agent/util/PublisherUtils.java |  451 +++
 .../usage/agent/util/UsageAgentConstants.java   |   49 +
 .../org/wso2/carbon/usage/agent/util/Util.java  |  175 ++
 .../src/main/resources/META-INF/component.xml   |   33 +
 .../src/main/resources/META-INF/module.xml      |   50 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../META-INF/usage-throttling-agent-config.xml  |   15 +
 .../org.wso2.carbon.usage.agent/2.1.2/pom.xml   |  144 +
 .../usage/agent/api/CustomMeteringAgent.java    |  222 ++
 .../agent/beans/APIManagerRequestStats.java     |   97 +
 .../usage/agent/beans/BandwidthUsage.java       |   60 +
 .../agent/config/UsageAgentConfiguration.java   |  116 +
 .../usage/agent/exception/UsageException.java   |   28 +
 .../internal/UsageAgentServiceComponent.java    |  204 ++
 .../agent/listeners/RegistryUsageListener.java  |  362 +++
 .../RegistryUsagePersistingListener.java        |  312 +++
 .../agent/listeners/StatisticsInHandler.java    |   56 +
 .../agent/listeners/StatisticsOutHandler.java   |   67 +
 ...eStatsAxis2ConfigurationContextObserver.java |   31 +
 .../listeners/axis2/RequestMeteringHandler.java |  108 +
 .../listeners/axis2/RequestMeteringModule.java  |   44 +
 .../usage/agent/persist/BandwidthPersistor.java |   55 +
 .../BandwidthUsageDataRetrievalTask.java        |  115 +
 .../agent/persist/RegistryUsagePersister.java   |   73 +
 .../agent/persist/ServiceDataPersistor.java     |   69 +
 .../persist/UsageDataPersistenceManager.java    |   88 +
 .../agent/persist/UsageDataPersistenceTask.java |  163 ++
 .../agent/services/CustomMeteringService.java   |   92 +
 .../usage/agent/util/MonitoredReader.java       |   47 +
 .../usage/agent/util/MonitoredWriter.java       |   50 +
 .../carbon/usage/agent/util/PublisherUtils.java |  451 +++
 .../usage/agent/util/UsageAgentConstants.java   |   49 +
 .../org/wso2/carbon/usage/agent/util/Util.java  |  175 ++
 .../src/main/resources/META-INF/component.xml   |   33 +
 .../src/main/resources/META-INF/module.xml      |   50 +
 .../src/main/resources/META-INF/services.xml    |   30 +
 .../META-INF/usage-throttling-agent-config.xml  |   15 +
 .../2.1.0/pom.xml                               |  136 +
 .../DailyServiceStatsSummarizerHelper.java      |   57 +
 .../summary/helper/DailySummarizerHelper.java   |   57 +
 .../HourlyServiceStatsSummarizerHelper.java     |   54 +
 .../summary/helper/HourlySummarizerHelper.java  |   54 +
 .../MonthlyServiceStatsSummarizerHelper.java    |   59 +
 .../summary/helper/MonthlySummarizerHelper.java |   59 +
 .../UsageSummaryHelperServiceComponent.java     |   83 +
 .../summary/helper/util/DataAccessObject.java   |  291 ++
 .../usage/summary/helper/util/DataHolder.java   |   50 +
 .../2.1.3/pom.xml                               |  136 +
 .../DailyCartridgeStatsSummarizerHelper.java    |   57 +
 .../DailyServiceStatsSummarizerHelper.java      |   57 +
 .../summary/helper/DailySummarizerHelper.java   |   57 +
 .../HourlyCartridgeStatsSummarizerHelper.java   |   54 +
 .../HourlyServiceStatsSummarizerHelper.java     |   54 +
 .../summary/helper/HourlySummarizerHelper.java  |   54 +
 .../MonthlyCartridgeStatsSummarizerHelper.java  |   59 +
 .../MonthlyServiceStatsSummarizerHelper.java    |   59 +
 .../summary/helper/MonthlySummarizerHelper.java |   59 +
 .../UsageSummaryHelperServiceComponent.java     |   83 +
 .../summary/helper/util/DataAccessObject.java   |  399 +++
 .../usage/summary/helper/util/DataHolder.java   |   50 +
 .../org.wso2.carbon.usage.ui/2.1.0/pom.xml      |  130 +
 .../usage/ui/clients/UsageServiceClient.java    |  115 +
 .../usage/ui/report/AllTenantUsageData.java     |   93 +
 .../usage/ui/report/AllTenantUsageReport.java   |  110 +
 .../carbon/usage/ui/report/UsageReport.java     |  194 ++
 .../wso2/carbon/usage/ui/utils/UsageUtil.java   |  245 ++
 .../src/main/resources/META-INF/component.xml   |   73 +
 .../2.1.0/src/main/resources/UsageService.wsdl  |  604 +++++
 .../carbon/usage/ui/i18n/JSResources.properties |    2 +
 .../carbon/usage/ui/i18n/Resources.properties   |   51 +
 .../tenant-usage/all_tenant_instance_usage.jsp  |  216 ++
 .../web/tenant-usage/all_tenant_usage.jsp       |  208 ++
 .../tenant-usage/all_tenant_usage_report.jsp    |   25 +
 .../web/tenant-usage/any_tenant_usage.jsp       |  390 +++
 .../web/tenant-usage/css/tenant-usage.css       |   28 +
 .../web/tenant-usage/docs/images/view-usage.png |  Bin 0 -> 61024 bytes
 .../web/tenant-usage/docs/userguide.html        |   77 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../tenant-usage/images/tenant-usage-report.gif |  Bin 0 -> 1008 bytes
 .../tenant-usage/images/user-usage-report.gif   |  Bin 0 -> 1033 bytes
 .../tenant-usage/js/all-tenant-usage-report.js  |   49 +
 .../web/tenant-usage/js/tenant-usage.js         |    7 +
 .../web/tenant-usage/js/usage-report.js         |   48 +
 .../resources/web/tenant-usage/tenant_usage.jsp |  408 +++
 .../resources/web/tenant-usage/usage_report.jsp |   28 +
 .../org.wso2.carbon.usage.ui/2.1.1/pom.xml      |  130 +
 .../usage/ui/clients/UsageServiceClient.java    |  115 +
 .../usage/ui/report/AllTenantUsageData.java     |   93 +
 .../usage/ui/report/AllTenantUsageReport.java   |  110 +
 .../carbon/usage/ui/report/UsageReport.java     |  194 ++
 .../wso2/carbon/usage/ui/utils/UsageUtil.java   |  251 ++
 .../src/main/resources/META-INF/component.xml   |   73 +
 .../2.1.1/src/main/resources/UsageService.wsdl  |  604 +++++
 .../carbon/usage/ui/i18n/JSResources.properties |    2 +
 .../carbon/usage/ui/i18n/Resources.properties   |   53 +
 .../tenant-usage/all_tenant_instance_usage.jsp  |  216 ++
 .../web/tenant-usage/all_tenant_usage.jsp       |  208 ++
 .../tenant-usage/all_tenant_usage_report.jsp    |   25 +
 .../web/tenant-usage/any_tenant_usage.jsp       |  414 +++
 .../web/tenant-usage/css/tenant-usage.css       |   28 +
 .../web/tenant-usage/docs/images/view-usage.png |  Bin 0 -> 61024 bytes
 .../web/tenant-usage/docs/userguide.html        |   77 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../tenant-usage/images/tenant-usage-report.gif |  Bin 0 -> 1008 bytes
 .../tenant-usage/images/user-usage-report.gif   |  Bin 0 -> 1033 bytes
 .../tenant-usage/js/all-tenant-usage-report.js  |   49 +
 .../web/tenant-usage/js/tenant-usage.js         |    7 +
 .../web/tenant-usage/js/usage-report.js         |   48 +
 .../resources/web/tenant-usage/tenant_usage.jsp |  427 +++
 .../resources/web/tenant-usage/usage_report.jsp |   28 +
 .../org.wso2.carbon.usage.ui/2.1.2/pom.xml      |  131 +
 .../usage/ui/clients/UsageServiceClient.java    |  115 +
 .../usage/ui/report/AllTenantUsageData.java     |   93 +
 .../usage/ui/report/AllTenantUsageReport.java   |  110 +
 .../carbon/usage/ui/report/UsageReport.java     |  194 ++
 .../wso2/carbon/usage/ui/utils/UsageUtil.java   |  251 ++
 .../src/main/resources/META-INF/component.xml   |   73 +
 .../2.1.2/src/main/resources/UsageService.wsdl  |  604 +++++
 .../carbon/usage/ui/i18n/JSResources.properties |    2 +
 .../carbon/usage/ui/i18n/Resources.properties   |   53 +
 .../tenant-usage/all_tenant_instance_usage.jsp  |  216 ++
 .../web/tenant-usage/all_tenant_usage.jsp       |  208 ++
 .../tenant-usage/all_tenant_usage_report.jsp    |   25 +
 .../web/tenant-usage/any_tenant_usage.jsp       |  414 +++
 .../web/tenant-usage/css/tenant-usage.css       |   28 +
 .../web/tenant-usage/docs/images/view-usage.png |  Bin 0 -> 61024 bytes
 .../web/tenant-usage/docs/userguide.html        |   77 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../tenant-usage/images/tenant-usage-report.gif |  Bin 0 -> 1008 bytes
 .../tenant-usage/images/user-usage-report.gif   |  Bin 0 -> 1033 bytes
 .../tenant-usage/js/all-tenant-usage-report.js  |   49 +
 .../web/tenant-usage/js/tenant-usage.js         |    7 +
 .../web/tenant-usage/js/usage-report.js         |   48 +
 .../resources/web/tenant-usage/tenant_usage.jsp |  427 +++
 .../resources/web/tenant-usage/usage_report.jsp |   28 +
 .../org.wso2.carbon.usage.ui/2.1.3/pom.xml      |  131 +
 .../usage/ui/clients/UsageServiceClient.java    |  115 +
 .../usage/ui/report/AllTenantUsageData.java     |   93 +
 .../usage/ui/report/AllTenantUsageReport.java   |  110 +
 .../carbon/usage/ui/report/UsageReport.java     |  194 ++
 .../wso2/carbon/usage/ui/utils/UsageUtil.java   |  251 ++
 .../src/main/resources/META-INF/component.xml   |   73 +
 .../2.1.3/src/main/resources/UsageService.wsdl  |  604 +++++
 .../carbon/usage/ui/i18n/JSResources.properties |    2 +
 .../carbon/usage/ui/i18n/Resources.properties   |   57 +
 .../tenant-usage/all_tenant_instance_usage.jsp  |  216 ++
 .../web/tenant-usage/all_tenant_usage.jsp       |  208 ++
 .../tenant-usage/all_tenant_usage_report.jsp    |   25 +
 .../web/tenant-usage/any_tenant_usage.jsp       |  462 ++++
 .../web/tenant-usage/css/tenant-usage.css       |   28 +
 .../web/tenant-usage/docs/images/view-usage.png |  Bin 0 -> 61024 bytes
 .../web/tenant-usage/docs/userguide.html        |   77 +
 .../images/instance-usage-report.gif            |  Bin 0 -> 849 bytes
 .../tenant-usage/images/tenant-usage-report.gif |  Bin 0 -> 1008 bytes
 .../tenant-usage/images/user-usage-report.gif   |  Bin 0 -> 1033 bytes
 .../tenant-usage/js/all-tenant-usage-report.js  |   49 +
 .../web/tenant-usage/js/tenant-usage.js         |    7 +
 .../web/tenant-usage/js/usage-report.js         |   48 +
 .../resources/web/tenant-usage/tenant_usage.jsp |  474 ++++
 .../resources/web/tenant-usage/usage_report.jsp |   28 +
 .../usage/org.wso2.carbon.usage/2.1.0/pom.xml   |  142 +
 .../carbon/usage/api/TenantUsageRetriever.java  |  435 +++
 .../carbon/usage/beans/BandwidthStatistics.java |   62 +
 .../usage/beans/InstanceUsageStatics.java       |   90 +
 .../usage/beans/PaginatedInstanceUsage.java     |   58 +
 .../usage/beans/PaginatedTenantUsageInfo.java   |   46 +
 .../carbon/usage/beans/RequestStatistics.java   |   60 +
 .../carbon/usage/beans/TenantDataCapacity.java  |   52 +
 .../wso2/carbon/usage/beans/TenantUsage.java    |  190 ++
 .../org/wso2/carbon/usage/beans/UsageEntry.java |   46 +
 .../usage/internal/UsageServiceComponent.java   |  103 +
 .../carbon/usage/services/UsageService.java     |  203 ++
 .../carbon/usage/util/DataAccessObject.java     |  358 +++
 .../java/org/wso2/carbon/usage/util/Util.java   |  108 +
 .../src/main/resources/META-INF/component.xml   |   45 +
 .../src/main/resources/META-INF/services.xml    |   47 +
 .../reports/all_tenant_usage_report.jrxml       |  137 +
 .../main/resources/reports/usage_report.jrxml   |  135 +
 .../usage/org.wso2.carbon.usage/2.1.1/pom.xml   |  142 +
 .../carbon/usage/api/TenantUsageRetriever.java  |  518 ++++
 .../usage/beans/APIManagerUsageStats.java       |   71 +
 .../carbon/usage/beans/BandwidthStatistics.java |   62 +
 .../usage/beans/InstanceUsageStatics.java       |   90 +
 .../usage/beans/PaginatedInstanceUsage.java     |   58 +
 .../usage/beans/PaginatedTenantUsageInfo.java   |   46 +
 .../carbon/usage/beans/RequestStatistics.java   |   60 +
 .../carbon/usage/beans/TenantDataCapacity.java  |   52 +
 .../wso2/carbon/usage/beans/TenantUsage.java    |  198 ++
 .../org/wso2/carbon/usage/beans/UsageEntry.java |   46 +
 .../usage/internal/UsageServiceComponent.java   |  103 +
 .../carbon/usage/services/UsageService.java     |  203 ++
 .../carbon/usage/util/DataAccessObject.java     |  498 ++++
 .../java/org/wso2/carbon/usage/util/Util.java   |  108 +
 .../src/main/resources/META-INF/component.xml   |   45 +
 .../src/main/resources/META-INF/services.xml    |   47 +
 .../reports/all_tenant_usage_report.jrxml       |  137 +
 .../main/resources/reports/usage_report.jrxml   |  135 +
 .../usage/org.wso2.carbon.usage/2.1.2/pom.xml   |  143 +
 .../carbon/usage/api/TenantUsageRetriever.java  |  518 ++++
 .../usage/beans/APIManagerUsageStats.java       |   71 +
 .../carbon/usage/beans/BandwidthStatistics.java |   62 +
 .../usage/beans/InstanceUsageStatics.java       |   90 +
 .../usage/beans/PaginatedInstanceUsage.java     |   58 +
 .../usage/beans/PaginatedTenantUsageInfo.java   |   46 +
 .../carbon/usage/beans/RequestStatistics.java   |   60 +
 .../carbon/usage/beans/TenantDataCapacity.java  |   52 +
 .../wso2/carbon/usage/beans/TenantUsage.java    |  198 ++
 .../org/wso2/carbon/usage/beans/UsageEntry.java |   46 +
 .../usage/internal/UsageServiceComponent.java   |  103 +
 .../carbon/usage/services/UsageService.java     |  203 ++
 .../carbon/usage/util/DataAccessObject.java     |  498 ++++
 .../java/org/wso2/carbon/usage/util/Util.java   |  108 +
 .../src/main/resources/META-INF/component.xml   |   45 +
 .../src/main/resources/META-INF/services.xml    |   47 +
 .../reports/all_tenant_usage_report.jrxml       |  137 +
 .../main/resources/reports/usage_report.jrxml   |  135 +
 .../usage/org.wso2.carbon.usage/2.1.3/pom.xml   |  143 +
 .../carbon/usage/api/TenantUsageRetriever.java  |  604 +++++
 .../usage/beans/APIManagerUsageStats.java       |   71 +
 .../carbon/usage/beans/BandwidthStatistics.java |   62 +
 .../carbon/usage/beans/CartridgeStatistics.java |   41 +
 .../usage/beans/InstanceUsageStatics.java       |   90 +
 .../usage/beans/PaginatedInstanceUsage.java     |   58 +
 .../usage/beans/PaginatedTenantUsageInfo.java   |   46 +
 .../carbon/usage/beans/RequestStatistics.java   |   60 +
 .../carbon/usage/beans/TenantDataCapacity.java  |   52 +
 .../wso2/carbon/usage/beans/TenantUsage.java    |  216 ++
 .../org/wso2/carbon/usage/beans/UsageEntry.java |   46 +
 .../usage/internal/UsageServiceComponent.java   |  103 +
 .../carbon/usage/services/UsageService.java     |  203 ++
 .../carbon/usage/util/DataAccessObject.java     |  624 +++++
 .../java/org/wso2/carbon/usage/util/Util.java   |  108 +
 .../src/main/resources/META-INF/component.xml   |   45 +
 .../src/main/resources/META-INF/services.xml    |   47 +
 .../reports/all_tenant_usage_report.jrxml       |  137 +
 .../main/resources/reports/usage_report.jrxml   |  135 +
 components/stratos/usage/pom.xml                |   43 +
 .../4.1.0/pom.xml                               |   96 +
 .../4.1.1/pom.xml                               |   96 +
 .../4.1.3/pom.xml                               |   96 +
 features/autoscaler/pom.xml                     |   35 +
 .../4.1.0/pom.xml                               |   84 +
 .../4.1.1/pom.xml                               |   84 +
 .../4.1.3/pom.xml                               |   84 +
 features/loadbalancer/pom.xml                   |   35 +
 .../2.1.1/pom.xml                               |   78 +
 .../2.1.3/pom.xml                               |   78 +
 .../2.1.1/pom.xml                               |  119 +
 .../2.1.3/pom.xml                               |  143 +
 .../2.1.3/src/main/resources/build.properties   |    1 +
 .../resources/conf/cartridge-config.properties  |   38 +
 .../src/main/resources/conf/etc/policies.xsd    |   36 +
 .../2.1.3/src/main/resources/conf/policies.xml  |   22 +
 .../2.1.3/src/main/resources/p2.inf             |    5 +
 .../2.1.1/pom.xml                               |   82 +
 .../2.1.3/pom.xml                               |   82 +
 features/stratos/adc-mgt/pom.xml                |   42 +
 .../2.1.0/pom.xml                               |  103 +
 .../2.1.1/pom.xml                               |  109 +
 .../2.1.3/pom.xml                               |  109 +
 .../2.1.0/pom.xml                               |   85 +
 features/stratos/billing/pom.xml                |   36 +
 .../2.1.1/pom.xml                               |   78 +
 .../2.1.3/pom.xml                               |   78 +
 .../2.1.1/pom.xml                               |  158 ++
 .../2.1.1/src/main/resources/build.properties   |    2 +
 .../src/main/resources/conf/agent.properties    |   25 +
 .../2.1.1/src/main/resources/p2.inf             |    3 +
 .../2.1.3/pom.xml                               |  158 ++
 .../2.1.3/src/main/resources/build.properties   |    2 +
 .../src/main/resources/conf/agent.properties    |   25 +
 .../2.1.3/src/main/resources/p2.inf             |    3 +
 .../2.1.1/pom.xml                               |   83 +
 features/stratos/cartridge-agent/pom.xml        |   42 +
 .../2.1.1/pom.xml                               |   88 +
 .../2.1.3/pom.xml                               |   88 +
 features/stratos/cartridge-mgt/pom.xml          |   55 +
 .../2.1.1/pom.xml                               |  282 ++
 .../2.1.1/src/main/resources/build.properties   |    1 +
 .../main/resources/conf/cloud-controller.xml    |   82 +
 .../src/main/resources/conf/etc/cartridge.xsd   |  133 +
 .../src/main/resources/conf/etc/cartridges.xsd  |  144 +
 .../src/main/resources/conf/etc/service.xsd     |   46 +
 .../src/main/resources/conf/etc/services.xsd    |   51 +
 .../2.1.1/src/main/resources/p2.inf             |    8 +
 .../2.1.3/pom.xml                               |  293 ++
 .../2.1.3/src/main/resources/build.properties   |    1 +
 .../main/resources/conf/cloud-controller.xml    |   82 +
 .../src/main/resources/conf/etc/cartridge.xsd   |  133 +
 .../src/main/resources/conf/etc/cartridges.xsd  |  144 +
 .../src/main/resources/conf/etc/service.xsd     |   46 +
 .../src/main/resources/conf/etc/services.xsd    |   51 +
 .../2.1.3/src/main/resources/p2.inf             |    8 +
 features/stratos/cloud-controller/pom.xml       |   54 +
 .../2.1.0/pom.xml                               |   81 +
 .../2.1.1/pom.xml                               |   81 +
 .../2.1.2/pom.xml                               |   81 +
 .../2.1.3/pom.xml                               |   81 +
 .../2.1.0/pom.xml                               |  248 ++
 .../2.1.0/resources/build.properties            |    2 +
 .../resources/conf/cloud-services-desc.xml      |  150 +
 .../2.1.0/resources/conf/eula.xml               |  165 ++
 .../2.1.0/resources/conf/identity.xml           |  166 ++
 .../resources/conf/multitenancy-packages.xml    |   84 +
 .../2.1.0/resources/conf/stratos.xml            |   83 +
 .../2.1.0/resources/conf/tenant-mgt.xml         |   37 +
 .../conf/usage-throttling-agent-config.xml      |   48 +
 .../2.1.0/resources/p2.inf                      |   10 +
 .../2.1.1/pom.xml                               |  248 ++
 .../2.1.1/resources/build.properties            |    2 +
 .../resources/conf/cloud-services-desc.xml      |  176 ++
 .../2.1.1/resources/conf/eula.xml               |  165 ++
 .../2.1.1/resources/conf/identity.xml           |  166 ++
 .../resources/conf/multitenancy-packages.xml    |   84 +
 .../2.1.1/resources/conf/stratos.xml            |   83 +
 .../2.1.1/resources/conf/tenant-mgt.xml         |   37 +
 .../conf/usage-throttling-agent-config.xml      |   48 +
 .../2.1.1/resources/p2.inf                      |   10 +
 .../2.1.2/pom.xml                               |  249 ++
 .../2.1.2/resources/build.properties            |    2 +
 .../resources/conf/cloud-services-desc.xml      |  176 ++
 .../2.1.2/resources/conf/eula.xml               |  165 ++
 .../2.1.2/resources/conf/identity.xml           |  166 ++
 .../resources/conf/multitenancy-packages.xml    |   84 +
 .../2.1.2/resources/conf/stratos.xml            |   83 +
 .../2.1.2/resources/conf/tenant-mgt.xml         |   37 +
 .../conf/usage-throttling-agent-config.xml      |   48 +
 .../2.1.2/resources/p2.inf                      |   10 +
 .../2.1.3/pom.xml                               |  249 ++
 .../2.1.3/resources/build.properties            |    2 +
 .../resources/conf/cloud-services-desc.xml      |  176 ++
 .../2.1.3/resources/conf/eula.xml               |  165 ++
 .../2.1.3/resources/conf/identity.xml           |  166 ++
 .../resources/conf/multitenancy-packages.xml    |  100 +
 .../2.1.3/resources/conf/stratos.xml            |   83 +
 .../2.1.3/resources/conf/tenant-mgt.xml         |   37 +
 .../conf/usage-throttling-agent-config.xml      |   48 +
 .../2.1.3/resources/p2.inf                      |   10 +
 .../2.1.0/pom.xml                               |  125 +
 features/stratos/common/pom.xml                 |   44 +
 features/stratos/deployment/2.1.0/pom.xml       |   74 +
 .../2.1.0/pom.xml                               |   63 +
 .../2.1.0/pom.xml                               |   63 +
 .../2.1.0/pom.xml                               |   86 +
 features/stratos/gapp/pom.xml                   |   41 +
 .../2.1.0/pom.xml                               |   83 +
 .../2.1.0/pom.xml                               |   79 +
 .../2.1.0/pom.xml                               |   78 +
 features/stratos/load-balance-agent/pom.xml     |   55 +
 features/stratos/pom.xml                        |  168 ++
 .../2.1.0/pom.xml                               |   77 +
 .../2.1.0/pom.xml                               |  101 +
 .../2.1.0/resources/conf/sso-idp-config.xml     |   29 +
 .../2.1.0/resources/p2.inf                      |    2 +
 .../2.1.0/pom.xml                               |   77 +
 features/stratos/sso-mgt/pom.xml                |   39 +
 .../2.1.0/pom.xml                               |  117 +
 .../2.1.0/pom.xml                               |   90 +
 .../2.1.0/pom.xml                               |   84 +
 .../2.1.0/pom.xml                               |   84 +
 features/stratos/status-monitor/pom.xml         |   71 +
 .../2.1.0/pom.xml                               |  100 +
 .../2.1.0/pom.xml                               |   98 +
 features/stratos/tenant-activity/pom.xml        |   36 +
 .../2.1.0/pom.xml                               |  122 +
 .../2.1.0/resources/build.properties            |    2 +
 .../resources/conf/cloud-services-desc.xml      |  150 +
 .../2.1.0/resources/p2.inf                      |    2 +
 .../2.1.0/pom.xml                               |   91 +
 features/stratos/tenant-mgt/pom.xml             |   70 +
 .../2.1.0/pom.xml                               |   78 +
 .../2.1.0/pom.xml                               |   91 +
 features/stratos/throttling/pom.xml             |   36 +
 .../2.1.0/pom.xml                               |   77 +
 .../2.1.2/pom.xml                               |   81 +
 .../2.1.0/pom.xml                               |   79 +
 .../2.1.3/pom.xml                               |   79 +
 .../2.1.0/pom.xml                               |   80 +
 .../2.1.3/pom.xml                               |   80 +
 .../2.1.0/pom.xml                               |   85 +
 .../2.1.3/pom.xml                               |   85 +
 features/stratos/usage/pom.xml                  |   36 +
 .../4.1.0/pom.xml                               |   89 +
 .../4.1.1/pom.xml                               |   93 +
 .../4.1.3/pom.xml                               |   93 +
 features/tenantaware-load-balancer/pom.xml      |   35 +
 products/elb/2.0.4/INSTALL.txt                  |   55 +
 products/elb/2.0.4/LICENSE.txt                  |  371 +++
 products/elb/2.0.4/README.txt                   |  147 +
 products/elb/2.0.4/docs/xdoc/release-notes.xml  |  169 ++
 products/elb/2.0.4/modules/distribution/pom.xml |  595 ++++
 .../distribution/src/main/assembly/bin.xml      |  284 ++
 .../distribution/src/main/assembly/dist.xml     |   37 +
 .../distribution/src/main/assembly/docs.xml     |   32 +
 .../src/main/assembly/filter.properties         |    8 +
 .../distribution/src/main/assembly/src.xml      |   72 +
 .../distribution/src/main/bin/wso2server.bat    |  170 ++
 .../distribution/src/main/bin/wso2server.sh     |  299 ++
 .../distribution/src/main/conf/axis2.xml        |  525 ++++
 .../src/main/conf/cipher-text.properties        |   23 +
 .../src/main/conf/datasources.properties        |   55 +
 .../src/main/conf/embedded-ldap.xml             |  162 ++
 .../src/main/conf/loadbalancer.conf             |  126 +
 .../distribution/src/main/conf/log4j.properties |  132 +
 .../distribution/src/main/conf/nhttp.properties |   39 +
 .../src/main/conf/passthru-http.properties      |   32 +
 .../src/main/conf/rule-component.conf           |    3 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../src/main/conf/synapse.properties            |   35 +
 .../distribution/src/main/conf/user-mgt.xml     |  238 ++
 products/elb/2.0.4/modules/integration/pom.xml  |  127 +
 .../tests/LoadBalancerTestServerManager.java    |   52 +
 .../src/test/resources/instrumentation.txt      |    1 +
 products/elb/2.0.4/modules/p2-profile/pom.xml   |  323 +++
 products/elb/2.0.4/pom.xml                      |  214 ++
 products/elb/2.0.5/INSTALL.txt                  |   55 +
 products/elb/2.0.5/LICENSE.txt                  |  386 +++
 products/elb/2.0.5/README.txt                   |  147 +
 products/elb/2.0.5/docs/xdoc/release-notes.xml  |  169 ++
 products/elb/2.0.5/modules/distribution/pom.xml |  595 ++++
 .../distribution/src/main/assembly/bin.xml      |  292 ++
 .../distribution/src/main/assembly/dist.xml     |   37 +
 .../distribution/src/main/assembly/docs.xml     |   32 +
 .../src/main/assembly/filter.properties         |    8 +
 .../distribution/src/main/assembly/src.xml      |   72 +
 .../distribution/src/main/bin/wso2server.bat    |  170 ++
 .../distribution/src/main/bin/wso2server.sh     |  299 ++
 .../distribution/src/main/conf/axis2.xml        |  525 ++++
 .../src/main/conf/cipher-text.properties        |   23 +
 .../src/main/conf/datasources.properties        |   55 +
 .../src/main/conf/embedded-ldap.xml             |  162 ++
 .../src/main/conf/loadbalancer.conf             |  126 +
 .../distribution/src/main/conf/log4j.properties |  132 +
 .../distribution/src/main/conf/nhttp.properties |   46 +
 .../src/main/conf/passthru-http.properties      |   32 +
 .../src/main/conf/rule-component.conf           |    3 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../src/main/conf/synapse.properties            |   35 +
 .../distribution/src/main/conf/user-mgt.xml     |  238 ++
 products/elb/2.0.5/modules/integration/pom.xml  |  127 +
 .../tests/LoadBalancerTestServerManager.java    |   52 +
 .../src/test/resources/instrumentation.txt      |    1 +
 products/elb/2.0.5/modules/p2-profile/pom.xml   |  342 +++
 products/elb/2.0.5/pom.xml                      |  216 ++
 .../stratos2/cloud_controller/1.0.0/INSTALL.txt |   78 +
 .../stratos2/cloud_controller/1.0.0/LICENSE.txt |  406 +++
 .../stratos2/cloud_controller/1.0.0/README.txt  |  208 ++
 .../1.0.0/docs/resources/css/mb-docs.css        |  173 ++
 .../resources/images/Deployment_Diagram.jpg     |  Bin 0 -> 40421 bytes
 .../1.0.0/docs/resources/images/Login.png       |  Bin 0 -> 112406 bytes
 .../resources/images/MessageFlowDiagram.jpg     |  Bin 0 -> 43164 bytes
 .../docs/resources/images/MessageQueue.jpg      |  Bin 0 -> 41880 bytes
 .../1.0.0/docs/resources/images/addMessage.png  |  Bin 0 -> 83311 bytes
 .../docs/resources/images/addPermission.png     |  Bin 0 -> 93870 bytes
 .../resources/images/cluster_scenario_01.png    |  Bin 0 -> 64444 bytes
 .../resources/images/cluster_scenario_02.png    |  Bin 0 -> 105140 bytes
 .../resources/images/cluster_scenario_03.png    |  Bin 0 -> 105277 bytes
 .../resources/images/cluster_scenario_04.png    |  Bin 0 -> 103247 bytes
 .../resources/images/cluster_scenario_05.png    |  Bin 0 -> 88343 bytes
 .../1.0.0/docs/resources/images/createMB.png    |  Bin 0 -> 68180 bytes
 .../docs/resources/images/listMessageBoxes.png  |  Bin 0 -> 69959 bytes
 .../1.0.0/docs/resources/images/logs.PNG        |  Bin 0 -> 63610 bytes
 .../1.0.0/docs/resources/images/mb-docs-bg.gif  |  Bin 0 -> 520 bytes
 .../docs/resources/images/mb-docs-header.gif    |  Bin 0 -> 5716 bytes
 .../docs/resources/images/retrieveMessage.png   |  Bin 0 -> 84034 bytes
 .../docs/resources/images/set-java-home.jpg     |  Bin 0 -> 84364 bytes
 .../docs/resources/images/state1_esper.png      |  Bin 0 -> 85366 bytes
 .../1.0.0/docs/resources/images/storeConfig.png |  Bin 0 -> 25128 bytes
 .../docs/resources/images/table-header.gif      |  Bin 0 -> 873 bytes
 .../docs/resources/images/topicBrowser.png      |  Bin 0 -> 41142 bytes
 .../images/topic_AddTopicFromDetails.png        |  Bin 0 -> 25193 bytes
 .../1.0.0/docs/resources/images/topic_add.png   |  Bin 0 -> 57217 bytes
 .../resources/images/topic_addSubscription.png  |  Bin 0 -> 76820 bytes
 .../docs/resources/images/topic_browser.png     |  Bin 0 -> 50827 bytes
 .../resources/images/topic_browser_clicked.png  |  Bin 0 -> 55746 bytes
 .../docs/resources/images/topic_details.png     |  Bin 0 -> 70525 bytes
 .../images/topic_subscriptionDetails.png        |  Bin 0 -> 47014 bytes
 .../images/topic_updatePermissions.png          |  Bin 0 -> 85779 bytes
 .../1.0.0/docs/resources/images/user-mgt.PNG    |  Bin 0 -> 8985 bytes
 .../docs/resources/images/userguide_state_1.png |  Bin 0 -> 73672 bytes
 .../docs/resources/images/zookeeperConfig.png   |  Bin 0 -> 19377 bytes
 .../cloud_controller/1.0.0/docs/site.xml        |   70 +
 .../1.0.0/docs/xdoc/admin_guide.xml             |  484 ++++
 .../1.0.0/docs/xdoc/cluster_scenario_01.xml     |  183 ++
 .../1.0.0/docs/xdoc/cluster_scenario_02.xml     |  159 ++
 .../1.0.0/docs/xdoc/cluster_scenario_03.xml     |  199 ++
 .../1.0.0/docs/xdoc/cluster_scenario_04.xml     |  168 ++
 .../1.0.0/docs/xdoc/cluster_scenario_05.xml     |  215 ++
 .../1.0.0/docs/xdoc/deployment_guide.xml        |   90 +
 .../1.0.0/docs/xdoc/docs_index.xml              |   76 +
 .../cloud_controller/1.0.0/docs/xdoc/faq.xml    |   79 +
 .../cloud_controller/1.0.0/docs/xdoc/index.xml  |   70 +
 .../1.0.0/docs/xdoc/installation_guide.xml      |  413 +++
 .../1.0.0/docs/xdoc/release-notes.xml           |  238 ++
 .../docs/xdoc/samples/jms_queue_sample.xml      |  260 ++
 .../docs/xdoc/samples/jms_topic_sample.xml      |  252 ++
 .../docs/xdoc/samples/jms_transport_sample.xml  |  371 +++
 .../xdoc/samples/web_service_client_sample.xml  |  232 ++
 .../1.0.0/docs/xdoc/samples_index.xml           |   79 +
 .../1.0.0/docs/xdoc/setting_java_home.xml       |   53 +
 .../1.0.0/docs/xdoc/source-repository.xml       |  136 +
 .../1.0.0/docs/xdoc/user_guide.xml              |  416 +++
 .../distribution/lib/home/images/bottom.gif     |  Bin 0 -> 523 bytes
 .../distribution/lib/home/images/content-bg.gif |  Bin 0 -> 233 bytes
 .../distribution/lib/home/images/favicon.ico    |  Bin 0 -> 17542 bytes
 .../lib/home/images/feature-01-icon.gif         |  Bin 0 -> 2063 bytes
 .../lib/home/images/feature-02-icon.gif         |  Bin 0 -> 2141 bytes
 .../lib/home/images/feature-03-icon.gif         |  Bin 0 -> 2649 bytes
 .../distribution/lib/home/images/intro-bg.gif   |  Bin 0 -> 3964 bytes
 .../distribution/lib/home/images/logo.gif       |  Bin 0 -> 3931 bytes
 .../lib/home/images/powered-logo.gif            |  Bin 0 -> 1280 bytes
 .../distribution/lib/home/images/register.gif   |  Bin 0 -> 6859 bytes
 .../distribution/lib/home/images/sign-in.gif    |  Bin 0 -> 3256 bytes
 .../distribution/lib/home/images/title-bg.gif   |  Bin 0 -> 1182 bytes
 .../distribution/lib/home/images/top.gif        |  Bin 0 -> 16149 bytes
 .../modules/distribution/lib/home/index.html    |   69 +
 .../modules/distribution/lib/home/style.css     |   46 +
 .../1.0.0/modules/distribution/pom.xml          |  272 ++
 .../distribution/src/main/assembly/bin.xml      |  329 +++
 .../distribution/src/main/assembly/dist.xml     |   36 +
 .../distribution/src/main/assembly/docs.xml     |   32 +
 .../src/main/assembly/filter.properties         |    4 +
 .../distribution/src/main/assembly/src.xml      |   73 +
 .../distribution/src/main/conf/axis2.xml        |  523 ++++
 .../src/main/conf/cipher-text.properties        |   23 +
 .../src/main/conf/datasources.properties        |   55 +
 .../src/main/conf/embedded-ldap.xml             |  162 ++
 .../distribution/src/main/conf/event-broker.xml |   44 +
 .../distribution/src/main/conf/jaas.conf        |   10 +
 .../distribution/src/main/conf/log4j.properties |  125 +
 .../src/main/conf/rule-component.conf           |    3 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../src/main/conf/synapse.properties            |   35 +
 .../modules/distribution/src/main/conf/zoo.cfg  |    3 +
 .../distribution/src/main/resources/launch.ini  |  248 ++
 .../src/main/resources/log4j.properties         |  193 ++
 .../src/main/resources/wso2server.bat           |  274 ++
 .../src/main/resources/wso2server.sh            |  296 ++
 .../src/site/resources/css/mb-docs.css          |  173 ++
 .../resources/images/Deployment_Diagram.jpg     |  Bin 0 -> 40421 bytes
 .../src/site/resources/images/Login.png         |  Bin 0 -> 112406 bytes
 .../resources/images/MessageFlowDiagram.jpg     |  Bin 0 -> 43164 bytes
 .../src/site/resources/images/MessageQueue.jpg  |  Bin 0 -> 41880 bytes
 .../src/site/resources/images/addMessage.png    |  Bin 0 -> 83311 bytes
 .../src/site/resources/images/addPermission.png |  Bin 0 -> 93870 bytes
 .../resources/images/cluster_scenario_01.png    |  Bin 0 -> 64444 bytes
 .../resources/images/cluster_scenario_02.png    |  Bin 0 -> 105140 bytes
 .../resources/images/cluster_scenario_03.png    |  Bin 0 -> 105277 bytes
 .../resources/images/cluster_scenario_04.png    |  Bin 0 -> 103247 bytes
 .../resources/images/cluster_scenario_05.png    |  Bin 0 -> 88343 bytes
 .../src/site/resources/images/createMB.png      |  Bin 0 -> 68180 bytes
 .../site/resources/images/listMessageBoxes.png  |  Bin 0 -> 69959 bytes
 .../src/site/resources/images/logs.PNG          |  Bin 0 -> 63610 bytes
 .../src/site/resources/images/mb-docs-bg.gif    |  Bin 0 -> 520 bytes
 .../site/resources/images/mb-docs-header.gif    |  Bin 0 -> 5716 bytes
 .../site/resources/images/retrieveMessage.png   |  Bin 0 -> 84034 bytes
 .../src/site/resources/images/set-java-home.jpg |  Bin 0 -> 84364 bytes
 .../src/site/resources/images/state1_esper.png  |  Bin 0 -> 85366 bytes
 .../src/site/resources/images/storeConfig.png   |  Bin 0 -> 25128 bytes
 .../src/site/resources/images/table-header.gif  |  Bin 0 -> 873 bytes
 .../src/site/resources/images/topicBrowser.png  |  Bin 0 -> 41142 bytes
 .../images/topic_AddTopicFromDetails.png        |  Bin 0 -> 25193 bytes
 .../src/site/resources/images/topic_add.png     |  Bin 0 -> 57217 bytes
 .../resources/images/topic_addSubscription.png  |  Bin 0 -> 76820 bytes
 .../src/site/resources/images/topic_browser.png |  Bin 0 -> 50827 bytes
 .../resources/images/topic_browser_clicked.png  |  Bin 0 -> 55746 bytes
 .../src/site/resources/images/topic_details.png |  Bin 0 -> 70525 bytes
 .../images/topic_subscriptionDetails.png        |  Bin 0 -> 47014 bytes
 .../images/topic_updatePermissions.png          |  Bin 0 -> 85779 bytes
 .../src/site/resources/images/user-mgt.PNG      |  Bin 0 -> 8985 bytes
 .../site/resources/images/userguide_state_1.png |  Bin 0 -> 73672 bytes
 .../site/resources/images/zookeeperConfig.png   |  Bin 0 -> 19377 bytes
 .../modules/distribution/src/site/site.xml      |   70 +
 .../site/xdoc/admin/css/carbonFormStyles.css    |  265 ++
 .../src/site/xdoc/admin/css/documentation.css   |   74 +
 .../src/site/xdoc/admin/css/global.css          | 1436 ++++++++++
 .../images/ui-bg_flat_0_aaaaaa_40x100.png       |  Bin 0 -> 180 bytes
 .../images/ui-bg_flat_75_ffffff_40x100.png      |  Bin 0 -> 178 bytes
 .../images/ui-bg_glass_55_fbf9ee_1x400.png      |  Bin 0 -> 120 bytes
 .../images/ui-bg_glass_65_ffffff_1x400.png      |  Bin 0 -> 105 bytes
 .../images/ui-bg_glass_75_dadada_1x400.png      |  Bin 0 -> 111 bytes
 .../images/ui-bg_glass_75_e6e6e6_1x400.png      |  Bin 0 -> 110 bytes
 .../images/ui-bg_glass_95_fef1ec_1x400.png      |  Bin 0 -> 119 bytes
 .../ui-bg_highlight-soft_75_cccccc_1x100.png    |  Bin 0 -> 101 bytes
 .../images/ui-icons_222222_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_2e83ff_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_454545_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_888888_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_cd0a0a_256x240.png          |  Bin 0 -> 4369 bytes
 .../css/smoothness/jquery-ui-1.8.11.custom.css  |  573 ++++
 .../src/site/xdoc/admin/docs/userguide.xml      |  232 ++
 .../src/site/xdoc/admin/images/1px.gif          |  Bin 0 -> 43 bytes
 .../site/xdoc/admin/images/add-collection.gif   |  Bin 0 -> 628 bytes
 .../src/site/xdoc/admin/images/add-link.gif     |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/admin/images/add-resource.gif |  Bin 0 -> 616 bytes
 .../site/xdoc/admin/images/add-small-icon.gif   |  Bin 0 -> 938 bytes
 .../src/site/xdoc/admin/images/add.gif          |  Bin 0 -> 407 bytes
 .../src/site/xdoc/admin/images/addNewTab.gif    |  Bin 0 -> 219 bytes
 .../src/site/xdoc/admin/images/am_logo_h23.gif  |  Bin 0 -> 1536 bytes
 .../site/xdoc/admin/images/application_edit.gif |  Bin 0 -> 1047 bytes
 .../xdoc/admin/images/appserver_logo_h23.gif    |  Bin 0 -> 1574 bytes
 .../src/site/xdoc/admin/images/arrow-down.png   |  Bin 0 -> 284 bytes
 .../src/site/xdoc/admin/images/arrow-up.png     |  Bin 0 -> 319 bytes
 .../src/site/xdoc/admin/images/atom.gif         |  Bin 0 -> 204 bytes
 .../site/xdoc/admin/images/axis2-powered.gif    |  Bin 0 -> 1813 bytes
 .../src/site/xdoc/admin/images/bam_logo_h23.gif |  Bin 0 -> 1808 bytes
 .../src/site/xdoc/admin/images/basket_put.gif   |  Bin 0 -> 599 bytes
 .../site/xdoc/admin/images/basket_remove.gif    |  Bin 0 -> 599 bytes
 .../src/site/xdoc/admin/images/book_add.gif     |  Bin 0 -> 1086 bytes
 .../src/site/xdoc/admin/images/bps_logo_h23.gif |  Bin 0 -> 1725 bytes
 .../src/site/xdoc/admin/images/brick_edit.gif   |  Bin 0 -> 649 bytes
 .../src/site/xdoc/admin/images/brs_logo_h23.gif |  Bin 0 -> 2864 bytes
 .../site/xdoc/admin/images/button-bg-focus.gif  |  Bin 0 -> 111 bytes
 .../site/xdoc/admin/images/button-bg-hover.gif  |  Bin 0 -> 243 bytes
 .../src/site/xdoc/admin/images/button-bg.gif    |  Bin 0 -> 243 bytes
 .../src/site/xdoc/admin/images/buttonRow-bg.gif |  Bin 0 -> 130 bytes
 .../src/site/xdoc/admin/images/calculator.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/admin/images/calendar.gif     |  Bin 0 -> 610 bytes
 .../src/site/xdoc/admin/images/cancel.gif       |  Bin 0 -> 411 bytes
 .../src/site/xdoc/admin/images/cep_logo_h23.gif |  Bin 0 -> 1998 bytes
 .../src/site/xdoc/admin/images/cloneTab.gif     |  Bin 0 -> 170 bytes
 .../xdoc/admin/images/control_play_blue.gif     |  Bin 0 -> 632 bytes
 .../src/site/xdoc/admin/images/copy.gif         |  Bin 0 -> 1036 bytes
 .../xdoc/admin/images/create-checkpoint.gif     |  Bin 0 -> 384 bytes
 .../xdoc/admin/images/default-menu-icon.gif     |  Bin 0 -> 86 bytes
 .../src/site/xdoc/admin/images/delete.gif       |  Bin 0 -> 555 bytes
 .../src/site/xdoc/admin/images/down-arrow.gif   |  Bin 0 -> 610 bytes
 .../src/site/xdoc/admin/images/down-arrow.png   |  Bin 0 -> 791 bytes
 .../src/site/xdoc/admin/images/ds_logo_h23.gif  |  Bin 0 -> 1686 bytes
 .../src/site/xdoc/admin/images/edit.gif         |  Bin 0 -> 1041 bytes
 .../src/site/xdoc/admin/images/elb_logo_h23.gif |  Bin 0 -> 1710 bytes
 .../src/site/xdoc/admin/images/esb_logo_h23.gif |  Bin 0 -> 1714 bytes
 .../src/site/xdoc/admin/images/excelicon.gif    |  Bin 0 -> 1080 bytes
 .../src/site/xdoc/admin/images/exlink.gif       |  Bin 0 -> 292 bytes
 .../src/site/xdoc/admin/images/favicon.ico      |  Bin 0 -> 17542 bytes
 .../src/site/xdoc/admin/images/forum.gif        |  Bin 0 -> 1977 bytes
 .../xdoc/admin/images/gadgetserver_logo_h23.gif |  Bin 0 -> 1556 bytes
 .../src/site/xdoc/admin/images/header-bg.gif    |  Bin 0 -> 495 bytes
 .../src/site/xdoc/admin/images/header-logo.gif  |  Bin 0 -> 1506 bytes
 .../site/xdoc/admin/images/header-region-bg.gif |  Bin 0 -> 369 bytes
 .../src/site/xdoc/admin/images/help-bg.gif      |  Bin 0 -> 465 bytes
 .../src/site/xdoc/admin/images/help-footer.gif  |  Bin 0 -> 1708 bytes
 .../src/site/xdoc/admin/images/help-header.gif  |  Bin 0 -> 9996 bytes
 .../site/xdoc/admin/images/help-small-icon.png  |  Bin 0 -> 631 bytes
 .../src/site/xdoc/admin/images/help.gif         |  Bin 0 -> 411 bytes
 .../src/site/xdoc/admin/images/home-bg.gif      |  Bin 0 -> 145 bytes
 .../src/site/xdoc/admin/images/htmlicon.gif     |  Bin 0 -> 1017 bytes
 .../xdoc/admin/images/icon-feed-small-res.gif   |  Bin 0 -> 1022 bytes
 .../xdoc/admin/images/identity_logo_h23.gif     |  Bin 0 -> 1499 bytes
 .../src/site/xdoc/admin/images/information.gif  |  Bin 0 -> 1025 bytes
 .../src/site/xdoc/admin/images/invisible.gif    |  Bin 0 -> 51 bytes
 .../site/xdoc/admin/images/issue-tracker.gif    |  Bin 0 -> 1821 bytes
 .../xdoc/admin/images/leftRightSlider-dark.png  |  Bin 0 -> 1421 bytes
 .../site/xdoc/admin/images/leftRightSlider.png  |  Bin 0 -> 448 bytes
 .../site/xdoc/admin/images/loading-small.gif    |  Bin 0 -> 673 bytes
 .../src/site/xdoc/admin/images/loading.gif      |  Bin 0 -> 14367 bytes
 .../src/site/xdoc/admin/images/mailing-list.gif |  Bin 0 -> 2064 bytes
 .../src/site/xdoc/admin/images/mainIcons.png    |  Bin 0 -> 1891 bytes
 .../site/xdoc/admin/images/mashup_logo_h23.gif  |  Bin 0 -> 1508 bytes
 .../src/site/xdoc/admin/images/mb_logo_h23.gif  |  Bin 0 -> 1603 bytes
 .../src/site/xdoc/admin/images/menu-header.gif  |  Bin 0 -> 237 bytes
 .../src/site/xdoc/admin/images/mgt-logo.gif     |  Bin 0 -> 2095 bytes
 .../src/site/xdoc/admin/images/minus-plus.png   |  Bin 0 -> 1113 bytes
 .../src/site/xdoc/admin/images/move.gif         |  Bin 0 -> 166 bytes
 .../site/xdoc/admin/images/nseditor-icon.gif    |  Bin 0 -> 1065 bytes
 .../src/site/xdoc/admin/images/oops.gif         |  Bin 0 -> 678 bytes
 .../src/site/xdoc/admin/images/overlay.png      |  Bin 0 -> 289 bytes
 .../src/site/xdoc/admin/images/panelImage.png   |  Bin 0 -> 144 bytes
 .../src/site/xdoc/admin/images/pdficon.gif      |  Bin 0 -> 361 bytes
 .../src/site/xdoc/admin/images/plugin_add.gif   |  Bin 0 -> 1030 bytes
 .../site/xdoc/admin/images/plugin_delete.gif    |  Bin 0 -> 1031 bytes
 .../src/site/xdoc/admin/images/policies.gif     |  Bin 0 -> 387 bytes
 .../xdoc/admin/images/registry_logo_h23.gif     |  Bin 0 -> 1657 bytes
 .../site/xdoc/admin/images/registry_picker.gif  |  Bin 0 -> 1053 bytes
 .../src/site/xdoc/admin/images/rss.gif          |  Bin 0 -> 207 bytes
 .../src/site/xdoc/admin/images/spacer.gif       |  Bin 0 -> 43 bytes
 .../src/site/xdoc/admin/images/star.gif         |  Bin 0 -> 588 bytes
 .../xdoc/admin/images/static-icon-disabled.gif  |  Bin 0 -> 935 bytes
 .../src/site/xdoc/admin/images/static-icon.gif  |  Bin 0 -> 935 bytes
 .../src/site/xdoc/admin/images/table-header.gif |  Bin 0 -> 873 bytes
 .../xdoc/admin/images/trace-icon-disabled.gif   |  Bin 0 -> 950 bytes
 .../src/site/xdoc/admin/images/trace-icon.gif   |  Bin 0 -> 961 bytes
 .../src/site/xdoc/admin/images/up-arrow.gif     |  Bin 0 -> 615 bytes
 .../src/site/xdoc/admin/images/up-arrow.png     |  Bin 0 -> 822 bytes
 .../src/site/xdoc/admin/images/user-guide.gif   |  Bin 0 -> 2161 bytes
 .../src/site/xdoc/admin/images/user.gif         |  Bin 0 -> 604 bytes
 .../site/xdoc/admin/images/view-disabled.gif    |  Bin 0 -> 998 bytes
 .../src/site/xdoc/admin/images/view.gif         |  Bin 0 -> 596 bytes
 .../src/site/xdoc/admin/images/zoom_in.gif      |  Bin 0 -> 575 bytes
 .../src/site/xdoc/admin/images/zoom_out.gif     |  Bin 0 -> 563 bytes
 .../distribution/src/site/xdoc/admin_guide.xml  |  484 ++++
 .../xdoc/andes-cluster-mgt/docs/userguide.xml   |  108 +
 .../images/cassandra-connection.png             |  Bin 0 -> 13921 bytes
 .../andes-cluster-mgt/images/cluster_info.png   |  Bin 0 -> 877 bytes
 .../site/xdoc/andes-cluster-mgt/images/list.gif |  Bin 0 -> 216 bytes
 .../xdoc/andes-cluster-mgt/images/minus.gif     |  Bin 0 -> 896 bytes
 .../site/xdoc/andes-cluster-mgt/images/move.gif |  Bin 0 -> 565 bytes
 .../xdoc/andes-cluster-mgt/images/nodata.gif    |  Bin 0 -> 883 bytes
 .../xdoc/andes-cluster-mgt/images/nodeIDBox.png |  Bin 0 -> 5775 bytes
 .../andes-cluster-mgt/images/nodeQueues.png     |  Bin 0 -> 20833 bytes
 .../images/nodewiseQueueWorkers.png             |  Bin 0 -> 17287 bytes
 .../site/xdoc/andes-cluster-mgt/images/plus.gif |  Bin 0 -> 905 bytes
 .../site/xdoc/andes-cluster-mgt/images/qpid.png |  Bin 0 -> 709 bytes
 .../images/queue_type_admin.gif                 |  Bin 0 -> 481 bytes
 .../images/queue_type_amqp.gif                  |  Bin 0 -> 501 bytes
 .../andes-cluster-mgt/images/queue_type_sqs.gif |  Bin 0 -> 467 bytes
 .../xdoc/andes-cluster-mgt/images/refresh.gif   |  Bin 0 -> 596 bytes
 .../xdoc/andes-cluster-mgt/images/restart.png   |  Bin 0 -> 854 bytes
 .../xdoc/andes-cluster-mgt/images/secure.gif    |  Bin 0 -> 943 bytes
 .../xdoc/andes-cluster-mgt/images/treetop.jpg   |  Bin 0 -> 795 bytes
 .../images/zookeeper-connection.png             |  Bin 0 -> 4968 bytes
 .../andes-cluster-mgt/styles/dsxmleditor.css    |   82 +
 .../andes-cluster-mgt/styles/tree-styles.css    |   36 +
 .../src/site/xdoc/axis2/images/type.gif         |  Bin 0 -> 409 bytes
 .../docs/images/caching configuration.JPG       |  Bin 0 -> 24509 bytes
 .../src/site/xdoc/caching/docs/userguide.xml    |  142 +
 .../src/site/xdoc/cluster_scenario_01.xml       |  183 ++
 .../src/site/xdoc/cluster_scenario_02.xml       |  159 ++
 .../src/site/xdoc/cluster_scenario_03.xml       |  199 ++
 .../src/site/xdoc/cluster_scenario_04.xml       |  168 ++
 .../src/site/xdoc/cluster_scenario_05.xml       |  215 ++
 .../src/site/xdoc/deployment_guide.xml          |   90 +
 .../src/site/xdoc/dialog/css/dialog-ie8.css     |    4 +
 .../src/site/xdoc/dialog/css/dialog.css         |  129 +
 .../jqueryui/images/222222_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../images/222222_11x11_icon_resize_se.gif      |  Bin 0 -> 61 bytes
 .../jqueryui/images/222222_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/222222_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../jqueryui/images/454545_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../jqueryui/images/454545_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/454545_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../jqueryui/images/888888_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../jqueryui/images/888888_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/888888_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../images/ffffff_40x100_textures_01_flat_0.png |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../css/jqueryui/jqueryui-themeroller.css       |  856 ++++++
 .../src/site/xdoc/dialog/img/confirm.gif        |  Bin 0 -> 2324 bytes
 .../src/site/xdoc/dialog/img/error.gif          |  Bin 0 -> 2258 bytes
 .../src/site/xdoc/dialog/img/info.gif           |  Bin 0 -> 2349 bytes
 .../src/site/xdoc/dialog/img/overlay.png        |  Bin 0 -> 144 bytes
 .../src/site/xdoc/dialog/img/warning.gif        |  Bin 0 -> 2345 bytes
 .../222222_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/222222_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/222222_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../tabs/images/222222_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/222222_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/222222_11x11_icon_resize_se.gif |  Bin 0 -> 61 bytes
 .../tabs/images/222222_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/222222_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/222222_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/222222_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../454545_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/454545_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/454545_11x11_icon_close.gif     |  Bin 0 -> 62 bytes
 .../tabs/images/454545_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../images/454545_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/454545_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../tabs/images/454545_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/454545_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/454545_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/454545_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/454545_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/454545_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../888888_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/888888_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/888888_11x11_icon_close.gif     |  Bin 0 -> 62 bytes
 .../tabs/images/888888_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../images/888888_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/888888_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../tabs/images/888888_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/888888_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/888888_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/888888_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/888888_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/888888_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../ffffff_40x100_textures_01_flat_75.png       |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../xdoc/dialog/js/jqueryui/tabs/ui.all.css     |  609 +++++
 .../distribution/src/site/xdoc/docs/about.xml   |  125 +
 .../src/site/xdoc/docs/images/login.png         |  Bin 0 -> 5995 bytes
 .../src/site/xdoc/docs/signin_userguide.xml     |   70 +
 .../distribution/src/site/xdoc/docs_index.xml   |   76 +
 .../src/site/xdoc/eventing/css/dsxmleditor.css  |   82 +
 .../site/xdoc/eventing/css/subscriptions.css    |   12 +
 .../src/site/xdoc/eventing/css/tree-styles.css  |   36 +
 .../src/site/xdoc/eventing/images/add.gif       |  Bin 0 -> 407 bytes
 .../src/site/xdoc/eventing/images/down.png      |  Bin 0 -> 555 bytes
 .../src/site/xdoc/eventing/images/hide.gif      |  Bin 0 -> 919 bytes
 .../src/site/xdoc/eventing/images/list.gif      |  Bin 0 -> 216 bytes
 .../src/site/xdoc/eventing/images/minus.gif     |  Bin 0 -> 896 bytes
 .../src/site/xdoc/eventing/images/nodata.gif    |  Bin 0 -> 883 bytes
 .../src/site/xdoc/eventing/images/plus.gif      |  Bin 0 -> 905 bytes
 .../src/site/xdoc/eventing/images/refresh.gif   |  Bin 0 -> 929 bytes
 .../src/site/xdoc/eventing/images/secure.gif    |  Bin 0 -> 943 bytes
 .../src/site/xdoc/eventing/images/show.gif      |  Bin 0 -> 919 bytes
 .../site/xdoc/eventing/images/subscriptions.gif |  Bin 0 -> 369 bytes
 .../src/site/xdoc/eventing/images/topics.gif    |  Bin 0 -> 147 bytes
 .../src/site/xdoc/eventing/images/treetop.jpg   |  Bin 0 -> 795 bytes
 .../src/site/xdoc/eventing/images/type.gif      |  Bin 0 -> 1037 bytes
 .../src/site/xdoc/eventing/images/up.png        |  Bin 0 -> 562 bytes
 .../modules/distribution/src/site/xdoc/faq.xml  |   79 +
 .../222222_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/222222_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/222222_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../css/images/222222_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/222222_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/222222_11x11_icon_resize_se.gif  |  Bin 0 -> 61 bytes
 .../css/images/222222_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/222222_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/222222_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/222222_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../454545_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/454545_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/454545_11x11_icon_close.gif      |  Bin 0 -> 62 bytes
 .../css/images/454545_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../images/454545_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/454545_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../css/images/454545_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/454545_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/454545_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/454545_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/454545_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/454545_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../888888_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/888888_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/888888_11x11_icon_close.gif      |  Bin 0 -> 62 bytes
 .../css/images/888888_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../images/888888_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/888888_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../css/images/888888_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/888888_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/888888_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/888888_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/888888_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/888888_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../feature-mgt/css/images/buttonRow-bg.gif     |  Bin 0 -> 130 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../ffffff_40x100_textures_01_flat_75.png       |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../src/site/xdoc/feature-mgt/css/ui.all.css    |  699 +++++
 .../docs/images/add-repositories.jpg.png        |  Bin 0 -> 10889 bytes
 .../docs/images/add-repositories.png            |  Bin 0 -> 18886 bytes
 .../images/available-features-uncategorized.png |  Bin 0 -> 125809 bytes
 .../docs/images/available-features.png          |  Bin 0 -> 55734 bytes
 .../docs/images/back-end-front-end.png          |  Bin 0 -> 27818 bytes
 .../docs/images/configuration-details.png       |  Bin 0 -> 21515 bytes
 .../docs/images/edit-repositories.png           |  Bin 0 -> 14335 bytes
 .../feature-mgt/docs/images/find-features.png   |  Bin 0 -> 44004 bytes
 .../images/installation-complete-message.png    |  Bin 0 -> 7649 bytes
 .../docs/images/installation-history.png        |  Bin 0 -> 30799 bytes
 .../docs/images/installed-features.png          |  Bin 0 -> 31229 bytes
 .../docs/images/licence-agreement.png           |  Bin 0 -> 59591 bytes
 .../docs/images/manage-repositories.png         |  Bin 0 -> 33724 bytes
 .../docs/images/review-installation.png         |  Bin 0 -> 27514 bytes
 .../images/select-a-category-to-install.png     |  Bin 0 -> 115949 bytes
 .../site/xdoc/feature-mgt/docs/userguide.xml    |  170 ++
 .../site/xdoc/feature-mgt/images/activate.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/feature-mgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../xdoc/feature-mgt/images/comp-manager.gif    |  Bin 0 -> 580 bytes
 .../site/xdoc/feature-mgt/images/deactivate.gif |  Bin 0 -> 606 bytes
 .../xdoc/feature-mgt/images/install-feature.png |  Bin 0 -> 783 bytes
 .../site/xdoc/feature-mgt/images/magnifier.gif  |  Bin 0 -> 578 bytes
 .../src/site/xdoc/feature-mgt/images/minus.gif  |  Bin 0 -> 896 bytes
 .../site/xdoc/feature-mgt/images/more-info.gif  |  Bin 0 -> 617 bytes
 .../src/site/xdoc/feature-mgt/images/nodata.gif |  Bin 0 -> 883 bytes
 .../src/site/xdoc/feature-mgt/images/plus.gif   |  Bin 0 -> 905 bytes
 .../src/site/xdoc/feature-mgt/images/search.gif |  Bin 0 -> 578 bytes
 .../src/site/xdoc/feature-mgt/images/spacer.png |  Bin 0 -> 144 bytes
 .../feature-mgt/images/uninstall-feature.png    |  Bin 0 -> 769 bytes
 .../xdoc/highlighter/css/SyntaxHighlighter.css  |  185 ++
 .../src/site/xdoc/highlighter/js/clipboard.swf  |  Bin 0 -> 109 bytes
 .../src/site/xdoc/images/keystores1.jpg         |  Bin 0 -> 14288 bytes
 .../src/site/xdoc/images/keystores2.jpg         |  Bin 0 -> 15098 bytes
 .../distribution/src/site/xdoc/images/menu.jpg  |  Bin 0 -> 15430 bytes
 .../src/site/xdoc/images/usergroups.jpg         |  Bin 0 -> 13759 bytes
 .../distribution/src/site/xdoc/images/users.jpg |  Bin 0 -> 10656 bytes
 .../src/site/xdoc/images/userstores.jpg         |  Bin 0 -> 15682 bytes
 .../distribution/src/site/xdoc/index.xml        |   70 +
 .../src/site/xdoc/installation_guide.xml        |  413 +++
 .../xdoc/java2wsdl/docs/images/add_resource.png |  Bin 0 -> 12443 bytes
 .../xdoc/java2wsdl/docs/images/java2wsdl.png    |  Bin 0 -> 77420 bytes
 .../src/site/xdoc/java2wsdl/docs/userguide.xml  |   55 +
 .../site/xdoc/java2wsdl/images/java2wsdl.gif    |  Bin 0 -> 399 bytes
 .../keystoremgt/docs/images/adding-keystore.JPG |  Bin 0 -> 19638 bytes
 .../docs/images/keystoremanagement.JPG          |  Bin 0 -> 12691 bytes
 .../site/xdoc/keystoremgt/docs/userguide.xml    |   77 +
 .../src/site/xdoc/keystoremgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../src/site/xdoc/keystoremgt/images/close.gif  |  Bin 0 -> 403 bytes
 .../src/site/xdoc/keystoremgt/images/delete.gif |  Bin 0 -> 555 bytes
 .../src/site/xdoc/keystoremgt/images/edit.gif   |  Bin 0 -> 1036 bytes
 .../xdoc/keystoremgt/images/import-cert.png     |  Bin 0 -> 13474 bytes
 .../src/site/xdoc/keystoremgt/images/import.gif |  Bin 0 -> 618 bytes
 .../site/xdoc/keystoremgt/images/keystore.gif   |  Bin 0 -> 604 bytes
 .../xdoc/keystoremgt/images/view-keystore.png   |  Bin 0 -> 20459 bytes
 .../src/site/xdoc/keystoremgt/images/view.gif   |  Bin 0 -> 596 bytes
 .../docs/images/config log appenders.JPG        |  Bin 0 -> 36196 bytes
 .../docs/images/config log4j loggers.JPG        |  Bin 0 -> 164685 bytes
 .../xdoc/log-admin/docs/images/configSyslog.JPG |  Bin 0 -> 19463 bytes
 .../docs/images/global log4j config.JPG         |  Bin 0 -> 20579 bytes
 .../xdoc/log-admin/docs/images/logging_mgt.jpg  |  Bin 0 -> 1669302 bytes
 .../log-admin/docs/images/syslogProperties.JPG  |  Bin 0 -> 21796 bytes
 .../src/site/xdoc/log-admin/docs/userguide.xml  |  112 +
 .../src/site/xdoc/log-admin/images/log.gif      |  Bin 0 -> 596 bytes
 .../xdoc/log-view/docs/images/application.jpg   |  Bin 0 -> 83936 bytes
 .../src/site/xdoc/log-view/docs/images/log.jpg  |  Bin 0 -> 1575250 bytes
 .../site/xdoc/log-view/docs/images/logIndex.jpg |  Bin 0 -> 35191 bytes
 .../site/xdoc/log-view/docs/images/logview.jpg  |  Bin 0 -> 104153 bytes
 .../src/site/xdoc/log-view/docs/userguide.xml   |   76 +
 .../src/site/xdoc/log-view/images/cancel.gif    |  Bin 0 -> 1032 bytes
 .../src/site/xdoc/log-view/images/collapse.gif  |  Bin 0 -> 102 bytes
 .../src/site/xdoc/log-view/images/debug.png     |  Bin 0 -> 775 bytes
 .../src/site/xdoc/log-view/images/download.gif  |  Bin 0 -> 146 bytes
 .../src/site/xdoc/log-view/images/error.png     |  Bin 0 -> 778 bytes
 .../src/site/xdoc/log-view/images/expand.gif    |  Bin 0 -> 102 bytes
 .../src/site/xdoc/log-view/images/fatal.png     |  Bin 0 -> 670 bytes
 .../site/xdoc/log-view/images/information.gif   |  Bin 0 -> 1025 bytes
 .../src/site/xdoc/log-view/images/magnifier.gif |  Bin 0 -> 578 bytes
 .../src/site/xdoc/log-view/images/minus.gif     |  Bin 0 -> 896 bytes
 .../src/site/xdoc/log-view/images/plus.gif      |  Bin 0 -> 905 bytes
 .../site/xdoc/log-view/images/script_gear.gif   |  Bin 0 -> 1082 bytes
 .../src/site/xdoc/log-view/images/search.gif    |  Bin 0 -> 578 bytes
 .../src/site/xdoc/log-view/images/trace.png     |  Bin 0 -> 900 bytes
 .../src/site/xdoc/log-view/images/view.gif      |  Bin 0 -> 596 bytes
 .../src/site/xdoc/log-view/images/warn.png      |  Bin 0 -> 741 bytes
 .../xdoc/mediation/images/mediation-icon.gif    |  Bin 0 -> 573 bytes
 .../menugeneral/images/chart_organisation.gif   |  Bin 0 -> 558 bytes
 .../site/xdoc/menugeneral/images/magnifier.gif  |  Bin 0 -> 578 bytes
 .../xdoc/modulemgt/docs/images/addmodule.png    |  Bin 0 -> 19515 bytes
 .../xdoc/modulemgt/docs/images/global-after.png |  Bin 0 -> 111586 bytes
 .../modulemgt/docs/images/global-before.png     |  Bin 0 -> 106993 bytes
 .../modulemgt/docs/images/global-throttling.png |  Bin 0 -> 36168 bytes
 .../src/site/xdoc/modulemgt/docs/userguide.xml  |  138 +
 .../src/site/xdoc/modulemgt/images/add.gif      |  Bin 0 -> 407 bytes
 .../src/site/xdoc/modulemgt/images/bricks.gif   |  Bin 0 -> 1051 bytes
 .../site/xdoc/modulemgt/images/configure.gif    |  Bin 0 -> 608 bytes
 .../src/site/xdoc/modulemgt/images/delete.gif   |  Bin 0 -> 555 bytes
 .../site/xdoc/modulemgt/images/disengage.gif    |  Bin 0 -> 595 bytes
 .../src/site/xdoc/modulemgt/images/edit.gif     |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/modulemgt/images/engage.gif   |  Bin 0 -> 603 bytes
 .../src/site/xdoc/modulemgt/images/list.gif     |  Bin 0 -> 216 bytes
 .../src/site/xdoc/modulemgt/images/policies.gif |  Bin 0 -> 387 bytes
 .../src/site/xdoc/modulemgt/images/restart.png  |  Bin 0 -> 3334 bytes
 .../src/site/xdoc/modulemgt/images/shutdown.png |  Bin 0 -> 3347 bytes
 .../site/xdoc/modulemgt/images/shutdowng.png    |  Bin 0 -> 2785 bytes
 .../docs/images/operation-dashboard.jpg         |  Bin 0 -> 72822 bytes
 .../docs/images/published-operations.jpg        |  Bin 0 -> 15138 bytes
 .../src/site/xdoc/operation/docs/userguide.xml  |  105 +
 .../src/site/xdoc/operation/images/add.gif      |  Bin 0 -> 1315 bytes
 .../src/site/xdoc/operation/images/caching.gif  |  Bin 0 -> 630 bytes
 .../src/site/xdoc/operation/images/delete.gif   |  Bin 0 -> 606 bytes
 .../src/site/xdoc/operation/images/flows.gif    |  Bin 0 -> 1309 bytes
 .../src/site/xdoc/operation/images/modules.gif  |  Bin 0 -> 1051 bytes
 .../site/xdoc/operation/images/parameters.gif   |  Bin 0 -> 1041 bytes
 .../src/site/xdoc/operation/images/service.gif  |  Bin 0 -> 638 bytes
 .../site/xdoc/operation/images/throttling.gif   |  Bin 0 -> 349 bytes
 .../site/xdoc/policyeditor/css/local-styles.css |   48 +
 .../docs/images/policy-editor-design-view.png   |  Bin 0 -> 71422 bytes
 .../docs/images/policy-editor-source-view.png   |  Bin 0 -> 83111 bytes
 .../docs/images/select-service-policies.png     |  Bin 0 -> 17068 bytes
 .../docs/images/service-policy-hierarchy.png    |  Bin 0 -> 38498 bytes
 .../site/xdoc/policyeditor/docs/userguide.xml   |   75 +
 .../xdoc/properties/images/icon-expanded.gif    |  Bin 0 -> 389 bytes
 .../xdoc/properties/images/icon-minimized.gif   |  Bin 0 -> 405 bytes
 .../site/xdoc/properties/images/save-button.gif |  Bin 0 -> 623 bytes
 .../src/site/xdoc/queues/docs/userguide.xml     |   92 +
 .../src/site/xdoc/queues/images/add.gif         |  Bin 0 -> 407 bytes
 .../src/site/xdoc/queues/images/list.gif        |  Bin 0 -> 216 bytes
 .../src/site/xdoc/queues/images/minus.gif       |  Bin 0 -> 896 bytes
 .../src/site/xdoc/queues/images/move.gif        |  Bin 0 -> 565 bytes
 .../src/site/xdoc/queues/images/nodata.gif      |  Bin 0 -> 883 bytes
 .../src/site/xdoc/queues/images/plus.gif        |  Bin 0 -> 905 bytes
 .../src/site/xdoc/queues/images/qpid.png        |  Bin 0 -> 709 bytes
 .../src/site/xdoc/queues/images/queue_add.png   |  Bin 0 -> 29186 bytes
 .../xdoc/queues/images/queue_add_success.png    |  Bin 0 -> 21010 bytes
 .../site/xdoc/queues/images/queue_browse.png    |  Bin 0 -> 25479 bytes
 .../xdoc/queues/images/queue_delete_success.png |  Bin 0 -> 20681 bytes
 .../xdoc/queues/images/queue_from_tenant.png    |  Bin 0 -> 18297 bytes
 .../xdoc/queues/images/queue_type_admin.gif     |  Bin 0 -> 481 bytes
 .../site/xdoc/queues/images/queue_type_amqp.gif |  Bin 0 -> 501 bytes
 .../site/xdoc/queues/images/queue_type_sqs.gif  |  Bin 0 -> 467 bytes
 .../src/site/xdoc/queues/images/queues.gif      |  Bin 0 -> 366 bytes
 .../src/site/xdoc/queues/images/refresh.gif     |  Bin 0 -> 596 bytes
 .../src/site/xdoc/queues/images/restart.png     |  Bin 0 -> 854 bytes
 .../src/site/xdoc/queues/images/secure.gif      |  Bin 0 -> 943 bytes
 .../src/site/xdoc/queues/images/treetop.jpg     |  Bin 0 -> 795 bytes
 .../src/site/xdoc/queues/styles/dsxmleditor.css |   82 +
 .../src/site/xdoc/queues/styles/tree-styles.css |   36 +
 .../src/site/xdoc/release-notes.xml             |  238 ++
 .../site/xdoc/resources/css/registry-ie7.css    |    7 +
 .../site/xdoc/resources/css/registry-ie8.css    |    4 +
 .../src/site/xdoc/resources/css/registry.css    |  842 ++++++
 .../resources/docs/images/HierSubscriptions.png |  Bin 0 -> 27885 bytes
 .../resources/docs/images/addCollection.png     |  Bin 0 -> 10514 bytes
 .../xdoc/resources/docs/images/addResource.png  |  Bin 0 -> 22508 bytes
 .../resources/docs/images/add_remotelink.png    |  Bin 0 -> 741710 bytes
 .../resources/docs/images/add_subscription.png  |  Bin 0 -> 20527 bytes
 .../xdoc/resources/docs/images/add_symlink.png  |  Bin 0 -> 666765 bytes
 .../xdoc/resources/docs/images/associations.png |  Bin 0 -> 20179 bytes
 .../xdoc/resources/docs/images/breadcrumb.png   |  Bin 0 -> 6649 bytes
 .../xdoc/resources/docs/images/comments.png     |  Bin 0 -> 13497 bytes
 .../site/xdoc/resources/docs/images/content.png |  Bin 0 -> 27060 bytes
 .../xdoc/resources/docs/images/dependency.png   |  Bin 0 -> 19592 bytes
 .../xdoc/resources/docs/images/detail_view.png  |  Bin 0 -> 70192 bytes
 .../xdoc/resources/docs/images/details_view.png |  Bin 0 -> 46680 bytes
 .../resources/docs/images/edit_mime_types.png   |  Bin 0 -> 767343 bytes
 .../site/xdoc/resources/docs/images/entries.png |  Bin 0 -> 552380 bytes
 .../xdoc/resources/docs/images/lifeCycles.png   |  Bin 0 -> 10306 bytes
 .../docs/images/manage_notifications.png        |  Bin 0 -> 17486 bytes
 .../xdoc/resources/docs/images/metadata.png     |  Bin 0 -> 20963 bytes
 .../xdoc/resources/docs/images/properties.png   |  Bin 0 -> 19831 bytes
 .../site/xdoc/resources/docs/images/rating.png  |  Bin 0 -> 6484 bytes
 .../resources/docs/images/registryBrowser.png   |  Bin 0 -> 40815 bytes
 .../site/xdoc/resources/docs/images/symlink.png |  Bin 0 -> 376850 bytes
 .../xdoc/resources/docs/images/tagSearch.png    |  Bin 0 -> 4565 bytes
 .../site/xdoc/resources/docs/images/tags.png    |  Bin 0 -> 10957 bytes
 .../xdoc/resources/docs/images/version_view.png |  Bin 0 -> 21283 bytes
 .../src/site/xdoc/resources/docs/userguide.xml  |  404 +++
 .../xdoc/resources/images/TrainingTitleBack.jpg |  Bin 0 -> 331 bytes
 .../site/xdoc/resources/images/ajax-loader.gif  |  Bin 0 -> 673 bytes
 .../site/xdoc/resources/images/arrow-right.gif  |  Bin 0 -> 651 bytes
 .../src/site/xdoc/resources/images/arrow-up.gif |  Bin 0 -> 1049 bytes
 .../src/site/xdoc/resources/images/back.gif     |  Bin 0 -> 622 bytes
 .../site/xdoc/resources/images/button-back.gif  |  Bin 0 -> 121 bytes
 .../xdoc/resources/images/button_center.gif     |  Bin 0 -> 865 bytes
 .../resources/images/button_center_focus.gif    |  Bin 0 -> 860 bytes
 .../resources/images/button_center_over.gif     |  Bin 0 -> 853 bytes
 .../src/site/xdoc/resources/images/calendar.jpg |  Bin 0 -> 572 bytes
 .../resources/images/cancel-save-button.gif     |  Bin 0 -> 576 bytes
 .../src/site/xdoc/resources/images/colSep.jpg   |  Bin 0 -> 376 bytes
 .../site/xdoc/resources/images/col_header.gif   |  Bin 0 -> 866 bytes
 .../images/collection-extn-mounted.gif          |  Bin 0 -> 614 bytes
 .../xdoc/resources/images/collection-extn.gif   |  Bin 0 -> 1006 bytes
 .../src/site/xdoc/resources/images/config.gif   |  Bin 0 -> 1006 bytes
 .../site/xdoc/resources/images/editshred.png    |  Bin 0 -> 526 bytes
 .../src/site/xdoc/resources/images/goto_url.gif |  Bin 0 -> 1028 bytes
 .../site/xdoc/resources/images/help-small.jpg   |  Bin 0 -> 485 bytes
 .../xdoc/resources/images/icon-add-folder.gif   |  Bin 0 -> 628 bytes
 .../xdoc/resources/images/icon-add-resource.gif |  Bin 0 -> 616 bytes
 .../site/xdoc/resources/images/icon-copy.jpg    |  Bin 0 -> 647 bytes
 .../xdoc/resources/images/icon-detail-view.png  |  Bin 0 -> 369 bytes
 .../site/xdoc/resources/images/icon-details.jpg |  Bin 0 -> 475 bytes
 .../xdoc/resources/images/icon-download.jpg     |  Bin 0 -> 466 bytes
 .../xdoc/resources/images/icon-expanded.gif     |  Bin 0 -> 389 bytes
 .../xdoc/resources/images/icon-feed-small.gif   |  Bin 0 -> 664 bytes
 .../xdoc/resources/images/icon-folder-small.gif |  Bin 0 -> 631 bytes
 .../xdoc/resources/images/icon-minimized.gif    |  Bin 0 -> 405 bytes
 .../site/xdoc/resources/images/icon-move.jpg    |  Bin 0 -> 580 bytes
 .../site/xdoc/resources/images/icon-restore.gif |  Bin 0 -> 639 bytes
 .../site/xdoc/resources/images/icon-search.gif  |  Bin 0 -> 1003 bytes
 .../xdoc/resources/images/icon-tree-minus.gif   |  Bin 0 -> 955 bytes
 .../xdoc/resources/images/icon-tree-minus.jpg   |  Bin 0 -> 667 bytes
 .../xdoc/resources/images/icon-tree-plus.gif    |  Bin 0 -> 988 bytes
 .../xdoc/resources/images/icon-tree-plus.jpg    |  Bin 0 -> 493 bytes
 .../site/xdoc/resources/images/icon-tree.png    |  Bin 0 -> 528 bytes
 .../site/xdoc/resources/images/icon-upload.jpg  |  Bin 0 -> 1167 bytes
 .../site/xdoc/resources/images/icon-vlidate.jpg |  Bin 0 -> 653 bytes
 .../site/xdoc/resources/images/menu-back.gif    |  Bin 0 -> 92 bytes
 .../site/xdoc/resources/images/menu-back.jpg    |  Bin 0 -> 347 bytes
 .../xdoc/resources/images/page-back-repeat.jpg  |  Bin 0 -> 4215 bytes
 .../site/xdoc/resources/images/page-back.jpg    |  Bin 0 -> 351 bytes
 .../xdoc/resources/images/page-left-top.gif     |  Bin 0 -> 291 bytes
 .../site/xdoc/resources/images/pageheader.gif   |  Bin 0 -> 886 bytes
 .../site/xdoc/resources/images/point-left.gif   |  Bin 0 -> 407 bytes
 .../site/xdoc/resources/images/point-right.gif  |  Bin 0 -> 401 bytes
 .../src/site/xdoc/resources/images/popback.png  |  Bin 0 -> 144 bytes
 .../xdoc/resources/images/portlet_header.gif    |  Bin 0 -> 866 bytes
 .../resources/images/promotionBackground.jpg    |  Bin 0 -> 379 bytes
 .../src/site/xdoc/resources/images/r00.gif      |  Bin 0 -> 577 bytes
 .../src/site/xdoc/resources/images/r01.gif      |  Bin 0 -> 980 bytes
 .../src/site/xdoc/resources/images/r02.gif      |  Bin 0 -> 980 bytes
 .../src/site/xdoc/resources/images/r03.gif      |  Bin 0 -> 981 bytes
 .../src/site/xdoc/resources/images/r04.gif      |  Bin 0 -> 582 bytes
 .../src/site/xdoc/resources/images/r44.gif      |  Bin 0 -> 582 bytes
 .../src/site/xdoc/resources/images/r4x.gif      |  Bin 0 -> 582 bytes
 .../resources/images/resource-extn-mounted.gif  |  Bin 0 -> 619 bytes
 .../xdoc/resources/images/resource-extn.gif     |  Bin 0 -> 1015 bytes
 .../src/site/xdoc/resources/images/resource.gif |  Bin 0 -> 1008 bytes
 .../site/xdoc/resources/images/resources.gif    |  Bin 0 -> 1028 bytes
 .../site/xdoc/resources/images/save-button.gif  |  Bin 0 -> 623 bytes
 .../site/xdoc/resources/images/seperator.gif    |  Bin 0 -> 817 bytes
 .../xdoc/resources/images/sidemenu_header.gif   |  Bin 0 -> 873 bytes
 .../src/site/xdoc/resources/images/spacer.gif   |  Bin 0 -> 68 bytes
 .../src/site/xdoc/resources/images/spacer.jpg   |  Bin 0 -> 309 bytes
 .../src/site/xdoc/resources/images/sqr.gif      |  Bin 0 -> 812 bytes
 .../resources/images/submain-title-back.jpg     |  Bin 0 -> 361 bytes
 .../site/xdoc/resources/images/table_header.gif |  Bin 0 -> 212 bytes
 .../site/xdoc/resources/images/titleBack.jpg    |  Bin 0 -> 370 bytes
 .../src/site/xdoc/resources/images/to-root.gif  |  Bin 0 -> 1023 bytes
 .../xdoc/resources/images/universal-add.gif     |  Bin 0 -> 986 bytes
 .../site/xdoc/resources/images/viewIcons.png    |  Bin 0 -> 5179 bytes
 .../site/xdoc/resources/images/view_tree.gif    |  Bin 0 -> 1090 bytes
 .../site/xdoc/resources/images/visualize.png    |  Bin 0 -> 842 bytes
 .../xdoc/resources/images/welcomebanner.gif     |  Bin 0 -> 878 bytes
 .../resources/images/window-headding-back.gif   |  Bin 0 -> 838 bytes
 .../src/site/xdoc/resources/xslt/XMLSchema.dtd  |  402 +++
 .../src/site/xdoc/resources/xslt/XMLSchema.xsd  | 2312 ++++++++++++++++
 .../src/site/xdoc/resources/xslt/datatypes.dtd  |  200 ++
 .../src/site/xdoc/rm/docs/images/rm.jpg         |  Bin 0 -> 88288 bytes
 .../src/site/xdoc/rm/docs/userguide.xml         |  158 ++
 .../src/site/xdoc/role/docs/rolepermissions.xml |  153 ++
 .../src/site/xdoc/role/docs/userguide.xml       |  111 +
 .../src/site/xdoc/role/images/Thumbs.db         |  Bin 0 -> 12800 bytes
 .../src/site/xdoc/role/images/add-role1.png     |  Bin 0 -> 14525 bytes
 .../src/site/xdoc/role/images/add-role2.png     |  Bin 0 -> 34733 bytes
 .../src/site/xdoc/role/images/add-role3.png     |  Bin 0 -> 20692 bytes
 .../src/site/xdoc/role/images/add.gif           |  Bin 0 -> 407 bytes
 .../src/site/xdoc/role/images/check0.gif        |  Bin 0 -> 608 bytes
 .../src/site/xdoc/role/images/check1.gif        |  Bin 0 -> 609 bytes
 .../src/site/xdoc/role/images/check2.gif        |  Bin 0 -> 622 bytes
 .../src/site/xdoc/role/images/contractall.gif   |  Bin 0 -> 987 bytes
 .../src/site/xdoc/role/images/delete.gif        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/role/images/edit.gif          |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/role/images/expandall.gif     |  Bin 0 -> 983 bytes
 .../site/xdoc/role/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../site/xdoc/role/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../site/xdoc/role/images/permission-edit.png   |  Bin 0 -> 23367 bytes
 .../src/site/xdoc/role/images/role-main.png     |  Bin 0 -> 17918 bytes
 .../src/site/xdoc/role/images/test.gif          |  Bin 0 -> 600 bytes
 .../src/site/xdoc/role/images/user-roles.gif    |  Bin 0 -> 1048 bytes
 .../src/site/xdoc/role/images/user-store.gif    |  Bin 0 -> 589 bytes
 .../src/site/xdoc/role/images/users.gif         |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/role/images/view.gif          |  Bin 0 -> 596 bytes
 .../src/site/xdoc/role/js/treeview.css          |    7 +
 .../site/xdoc/roles-mgt/docs/server-roles.xml   |   62 +
 .../src/site/xdoc/roles-mgt/docs/userguide.xml  |   91 +
 .../src/site/xdoc/roles-mgt/images/add.gif      |  Bin 0 -> 407 bytes
 .../xdoc/roles-mgt/images/add_server_role.jpg   |  Bin 0 -> 46641 bytes
 .../src/site/xdoc/roles-mgt/images/delete.gif   |  Bin 0 -> 555 bytes
 .../roles-mgt/images/delete_server_role.jpg     |  Bin 0 -> 38559 bytes
 .../xdoc/roles-mgt/images/icon-expanded.gif     |  Bin 0 -> 389 bytes
 .../xdoc/roles-mgt/images/icon-minimized.gif    |  Bin 0 -> 405 bytes
 .../site/xdoc/roles-mgt/images/landingpage.jpg  |  Bin 0 -> 95016 bytes
 .../site/xdoc/roles-mgt/images/server-role.gif  |  Bin 0 -> 1073 bytes
 .../src/site/xdoc/samples/jms_queue_sample.xml  |  260 ++
 .../src/site/xdoc/samples/jms_topic_sample.xml  |  252 ++
 .../site/xdoc/samples/jms_transport_sample.xml  |  371 +++
 .../xdoc/samples/web_service_client_sample.xml  |  232 ++
 .../src/site/xdoc/samples_index.xml             |   79 +
 .../src/site/xdoc/search/css/search.css         |   25 +
 .../xdoc/search/docs/images/configuration.png   |  Bin 0 -> 49079 bytes
 .../xdoc/search/docs/images/custom_search.png   |  Bin 0 -> 48792 bytes
 .../src/site/xdoc/search/docs/images/date.png   |  Bin 0 -> 54047 bytes
 .../xdoc/search/docs/images/load_filter.png     |  Bin 0 -> 15375 bytes
 .../src/site/xdoc/search/docs/images/main.png   |  Bin 0 -> 43061 bytes
 .../xdoc/search/docs/images/reporting_crumb.png |  Bin 0 -> 4290 bytes
 .../xdoc/search/docs/images/save_filter.png     |  Bin 0 -> 10440 bytes
 .../src/site/xdoc/search/docs/userguide.xml     |  102 +
 .../src/site/xdoc/search/images/arrow-down.png  |  Bin 0 -> 529 bytes
 .../src/site/xdoc/search/images/arrow-up.png    |  Bin 0 -> 512 bytes
 .../src/site/xdoc/search/images/calendar.jpg    |  Bin 0 -> 572 bytes
 .../site/xdoc/search/images/icon-expanded.gif   |  Bin 0 -> 389 bytes
 .../xdoc/search/images/icon-folder-small.gif    |  Bin 0 -> 631 bytes
 .../site/xdoc/search/images/icon-minimized.gif  |  Bin 0 -> 405 bytes
 .../src/site/xdoc/search/images/r00.gif         |  Bin 0 -> 577 bytes
 .../src/site/xdoc/search/images/r01.gif         |  Bin 0 -> 980 bytes
 .../src/site/xdoc/search/images/r02.gif         |  Bin 0 -> 980 bytes
 .../src/site/xdoc/search/images/r03.gif         |  Bin 0 -> 981 bytes
 .../src/site/xdoc/search/images/r04.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/r44.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/r4x.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/resource.gif    |  Bin 0 -> 1008 bytes
 .../site/xdoc/search/images/search-content.png  |  Bin 0 -> 883 bytes
 .../xdoc/search/images/search-resources.gif     |  Bin 0 -> 1046 bytes
 .../src/site/xdoc/search/images/search-top.png  |  Bin 0 -> 785 bytes
 .../src/site/xdoc/search/images/search.gif      |  Bin 0 -> 578 bytes
 .../images/activate_security_custom_policy.png  |  Bin 0 -> 30309 bytes
 .../images/activate_security_key_stores.png     |  Bin 0 -> 24569 bytes
 .../images/activate_security_user_groups.png    |  Bin 0 -> 19093 bytes
 .../docs/images/default_scenarios.png           |  Bin 0 -> 124356 bytes
 .../securityconfig/docs/images/kerberos_spn.png |  Bin 0 -> 23907 bytes
 .../securityconfig/docs/images/no_security.png  |  Bin 0 -> 14725 bytes
 .../docs/images/policy_from_registry.png        |  Bin 0 -> 13835 bytes
 .../site/xdoc/securityconfig/docs/userguide.xml |  205 ++
 .../xdoc/securityconfig/images/scenario1.png    |  Bin 0 -> 51504 bytes
 .../xdoc/securityconfig/images/scenario10.png   |  Bin 0 -> 85245 bytes
 .../xdoc/securityconfig/images/scenario11.png   |  Bin 0 -> 86296 bytes
 .../xdoc/securityconfig/images/scenario12.png   |  Bin 0 -> 93294 bytes
 .../xdoc/securityconfig/images/scenario13.png   |  Bin 0 -> 93878 bytes
 .../xdoc/securityconfig/images/scenario14.png   |  Bin 0 -> 103007 bytes
 .../xdoc/securityconfig/images/scenario15.png   |  Bin 0 -> 103608 bytes
 .../xdoc/securityconfig/images/scenario16.png   |  Bin 0 -> 290183 bytes
 .../xdoc/securityconfig/images/scenario2.png    |  Bin 0 -> 60285 bytes
 .../xdoc/securityconfig/images/scenario3.png    |  Bin 0 -> 71785 bytes
 .../xdoc/securityconfig/images/scenario4.png    |  Bin 0 -> 72930 bytes
 .../xdoc/securityconfig/images/scenario5.png    |  Bin 0 -> 71865 bytes
 .../xdoc/securityconfig/images/scenario6.png    |  Bin 0 -> 73596 bytes
 .../xdoc/securityconfig/images/scenario7.png    |  Bin 0 -> 84269 bytes
 .../xdoc/securityconfig/images/scenario8.png    |  Bin 0 -> 83791 bytes
 .../xdoc/securityconfig/images/scenario9.png    |  Bin 0 -> 85331 bytes
 .../site/xdoc/securityconfig/images/view.png    |  Bin 0 -> 656 bytes
 .../server-admin/docs/images/server-admin.gif   |  Bin 0 -> 21871 bytes
 .../site/xdoc/server-admin/docs/userguide.xml   |   55 +
 .../server-admin/images/graceful-restart.gif    |  Bin 0 -> 630 bytes
 .../server-admin/images/graceful-shutdown.gif   |  Bin 0 -> 623 bytes
 .../site/xdoc/server-admin/images/restart.gif   |  Bin 0 -> 631 bytes
 .../site/xdoc/server-admin/images/shutdown.gif  |  Bin 0 -> 404 bytes
 .../docs/faultyservices_userguide.xml           |   47 +
 .../service-mgt/docs/images/Engaging module.JPG |  Bin 0 -> 38855 bytes
 .../site/xdoc/service-mgt/docs/images/QoS.JPG   |  Bin 0 -> 17054 bytes
 .../docs/images/Servicegroup Dashboard.JPG      |  Bin 0 -> 23262 bytes
 .../docs/images/client operations.JPG           |  Bin 0 -> 8717 bytes
 .../docs/images/deployedservices.JPG            |  Bin 0 -> 134937 bytes
 .../service-mgt/docs/images/faulty_services.jpg |  Bin 0 -> 1973914 bytes
 .../docs/images/response time graph.JPG         |  Bin 0 -> 17155 bytes
 .../service-mgt/docs/images/service details.JPG |  Bin 0 -> 12416 bytes
 .../docs/images/service group parameters.JPG    |  Bin 0 -> 18175 bytes
 .../docs/images/service parameters.JPG          |  Bin 0 -> 21034 bytes
 .../xdoc/service-mgt/docs/images/service.JPG    |  Bin 0 -> 235858 bytes
 .../xdoc/service-mgt/docs/images/statistics.JPG |  Bin 0 -> 14542 bytes
 .../service-mgt/docs/images/try the service.JPG |  Bin 0 -> 15674 bytes
 .../xdoc/service-mgt/docs/images/wsdl2code.JPG  |  Bin 0 -> 72697 bytes
 .../site/xdoc/service-mgt/docs/userguide.xml    |  417 +++
 .../xdoc/service-mgt/images/Engaging module.jpg |  Bin 0 -> 17919 bytes
 .../src/site/xdoc/service-mgt/images/QoS.jpg    |  Bin 0 -> 18555 bytes
 .../images/Servicegroup Dashboard.jpg           |  Bin 0 -> 33154 bytes
 .../site/xdoc/service-mgt/images/activate.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/service-mgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../src/site/xdoc/service-mgt/images/axis.gif   |  Bin 0 -> 372 bytes
 .../site/xdoc/service-mgt/images/axis2_01.gif   |  Bin 0 -> 409 bytes
 .../site/xdoc/service-mgt/images/axis2_02.gif   |  Bin 0 -> 613 bytes
 .../src/site/xdoc/service-mgt/images/bricks.gif |  Bin 0 -> 1051 bytes
 .../site/xdoc/service-mgt/images/caching.gif    |  Bin 0 -> 630 bytes
 .../service-mgt/images/client operations.jpg    |  Bin 0 -> 9520 bytes
 .../site/xdoc/service-mgt/images/create_svc.gif |  Bin 0 -> 623 bytes
 .../xdoc/service-mgt/images/data_service.gif    |  Bin 0 -> 351 bytes
 .../site/xdoc/service-mgt/images/deactivate.gif |  Bin 0 -> 606 bytes
 .../src/site/xdoc/service-mgt/images/delete.gif |  Bin 0 -> 606 bytes
 .../service-mgt/images/deployedservices.jpg     |  Bin 0 -> 42108 bytes
 .../site/xdoc/service-mgt/images/download.gif   |  Bin 0 -> 146 bytes
 .../src/site/xdoc/service-mgt/images/edit.gif   |  Bin 0 -> 353 bytes
 .../src/site/xdoc/service-mgt/images/edit2.gif  |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/service-mgt/images/ejb.gif    |  Bin 0 -> 355 bytes
 .../site/xdoc/service-mgt/images/genclient.gif  |  Bin 0 -> 1086 bytes
 .../src/site/xdoc/service-mgt/images/list.gif   |  Bin 0 -> 216 bytes
 .../site/xdoc/service-mgt/images/modules.gif    |  Bin 0 -> 1051 bytes
 .../site/xdoc/service-mgt/images/operations.gif |  Bin 0 -> 623 bytes
 .../site/xdoc/service-mgt/images/policies.gif   |  Bin 0 -> 387 bytes
 .../service-mgt/images/response time graph.jpg  |  Bin 0 -> 19259 bytes
 .../src/site/xdoc/service-mgt/images/rm.gif     |  Bin 0 -> 578 bytes
 .../src/site/xdoc/service-mgt/images/search.gif |  Bin 0 -> 578 bytes
 .../site/xdoc/service-mgt/images/secured.gif    |  Bin 0 -> 558 bytes
 .../site/xdoc/service-mgt/images/security.gif   |  Bin 0 -> 1019 bytes
 .../xdoc/service-mgt/images/service details.jpg |  Bin 0 -> 14738 bytes
 .../service-mgt/images/service parameters.jpg   |  Bin 0 -> 36648 bytes
 .../site/xdoc/service-mgt/images/service.gif    |  Bin 0 -> 638 bytes
 .../site/xdoc/service-mgt/images/service.jpg    |  Bin 0 -> 235858 bytes
 .../site/xdoc/service-mgt/images/statistics.jpg |  Bin 0 -> 14542 bytes
 .../site/xdoc/service-mgt/images/throttling.gif |  Bin 0 -> 349 bytes
 .../site/xdoc/service-mgt/images/transports.gif |  Bin 0 -> 611 bytes
 .../xdoc/service-mgt/images/try the service.jpg |  Bin 0 -> 14462 bytes
 .../src/site/xdoc/service-mgt/images/tryit.gif  |  Bin 0 -> 632 bytes
 .../site/xdoc/service-mgt/images/unsecured.gif  |  Bin 0 -> 558 bytes
 .../xdoc/service-mgt/images/url-rewrite.png     |  Bin 0 -> 654 bytes
 .../src/site/xdoc/service-mgt/images/wsdl.gif   |  Bin 0 -> 612 bytes
 .../site/xdoc/service-mgt/styles/XMLSchema.dtd  |  418 +++
 .../site/xdoc/service-mgt/styles/XMLSchema.xsd  | 2328 ++++++++++++++++
 .../site/xdoc/service-mgt/styles/datatypes.dtd  |  216 ++
 .../src/site/xdoc/setting_java_home.xml         |   53 +
 .../src/site/xdoc/source-repository.xml         |  136 +
 .../src/site/xdoc/sso-acs/css/authFailures.css  |   28 +
 .../src/site/xdoc/sso-acs/images/reload.gif     |  Bin 0 -> 963 bytes
 .../xdoc/statistics/docs/images/statistics.jpg  |  Bin 0 -> 223782 bytes
 .../src/site/xdoc/statistics/docs/userguide.xml |   52 +
 .../site/xdoc/statistics/gadget/stat_gadget.xml |  158 ++
 .../xdoc/statistics/gadget/stats_gadget.xml     |   91 +
 .../site/xdoc/statistics/images/chart_bar.gif   |  Bin 0 -> 1040 bytes
 .../xdoc/stratos-auth/css/stratos-loginpage.css |   94 +
 .../images/cloud-identity-sso-config-ok.png     |  Bin 0 -> 38465 bytes
 .../images/cloud-identity-sso-config.png        |  Bin 0 -> 32929 bytes
 .../stratos-auth/images/cloud-sso-config.png    |  Bin 0 -> 29222 bytes
 .../site/xdoc/stratos-auth/images/delete.gif    |  Bin 0 -> 555 bytes
 .../site/xdoc/stratos-auth/images/import.gif    |  Bin 0 -> 1051 bytes
 .../site/xdoc/stratos-auth/images/loading.gif   |  Bin 0 -> 14367 bytes
 .../src/site/xdoc/stratos-auth/images/logo.gif  |  Bin 0 -> 17603 bytes
 .../site/xdoc/stratos-auth/images/policy.gif    |  Bin 0 -> 1017 bytes
 .../site/xdoc/stratos-auth/images/powered.gif   |  Bin 0 -> 1773 bytes
 .../site/xdoc/stratos-auth/images/register.gif  |  Bin 0 -> 4099 bytes
 .../src/site/xdoc/stratos-auth/images/sso.gif   |  Bin 0 -> 394 bytes
 .../stratos-auth/images/st-login-body-bg.gif    |  Bin 0 -> 2215 bytes
 .../stratos-auth/images/st-login-content-bg.gif |  Bin 0 -> 1060 bytes
 .../stratos-auth/images/st-login-footer-bg.gif  |  Bin 0 -> 749 bytes
 .../stratos-auth/images/st-login-header-bg.gif  |  Bin 0 -> 64503 bytes
 .../src/site/xdoc/tenant-mgt/css/tenant.css     |   62 +
 .../xdoc/tenant-mgt/docs/aboutUsagePlans.xml    |  104 +
 .../xdoc/tenant-mgt/docs/images/add-org.png     |  Bin 0 -> 49926 bytes
 .../xdoc/tenant-mgt/docs/images/add-tenant.png  |  Bin 0 -> 28704 bytes
 .../tenant-mgt/docs/images/view-tenants.png     |  Bin 0 -> 11896 bytes
 .../src/site/xdoc/tenant-mgt/docs/userguide.xml |   56 +
 .../xdoc/tenant-mgt/images/multi_tenancy.png    |  Bin 0 -> 768 bytes
 .../site/xdoc/tenant-mgt/images/services.gif    |  Bin 0 -> 604 bytes
 .../site/xdoc/tenant-mgt/images/services1.gif   |  Bin 0 -> 608 bytes
 .../xdoc/throttling/docs/images/throttle.jpg    |  Bin 0 -> 112870 bytes
 .../src/site/xdoc/throttling/docs/userguide.xml |  198 ++
 .../src/site/xdoc/throttling/images/add.gif     |  Bin 0 -> 589 bytes
 .../src/site/xdoc/throttling/images/delete.gif  |  Bin 0 -> 555 bytes
 .../src/site/xdoc/throttling/images/help.gif    |  Bin 0 -> 1109 bytes
 .../src/site/xdoc/tools/images/tools.gif        |  Bin 0 -> 573 bytes
 .../src/site/xdoc/topics/css/dsxmleditor.css    |   82 +
 .../src/site/xdoc/topics/css/topics.css         |   17 +
 .../src/site/xdoc/topics/css/tree-styles.css    |   80 +
 .../src/site/xdoc/topics/docs/userguide.xml     |  135 +
 .../site/xdoc/topics/images/Add_subtopic.png    |  Bin 0 -> 53579 bytes
 .../src/site/xdoc/topics/images/Subscribe.png   |  Bin 0 -> 54335 bytes
 .../site/xdoc/topics/images/Topic_Browser.png   |  Bin 0 -> 43590 bytes
 .../site/xdoc/topics/images/Topic_details.png   |  Bin 0 -> 67101 bytes
 .../src/site/xdoc/topics/images/add.gif         |  Bin 0 -> 873 bytes
 .../src/site/xdoc/topics/images/delete.gif      |  Bin 0 -> 555 bytes
 .../src/site/xdoc/topics/images/details.gif     |  Bin 0 -> 1046 bytes
 .../src/site/xdoc/topics/images/down.png        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/topics/images/hide.gif        |  Bin 0 -> 919 bytes
 .../site/xdoc/topics/images/icon-tree-dot.gif   |  Bin 0 -> 119 bytes
 .../site/xdoc/topics/images/icon-tree-minus.gif |  Bin 0 -> 117 bytes
 .../site/xdoc/topics/images/icon-tree-minus.jpg |  Bin 0 -> 1278 bytes
 .../xdoc/topics/images/icon-tree-plus-alone.jpg |  Bin 0 -> 1347 bytes
 .../site/xdoc/topics/images/icon-tree-plus.gif  |  Bin 0 -> 128 bytes
 .../site/xdoc/topics/images/icon-tree-plus.jpg  |  Bin 0 -> 1290 bytes
 .../src/site/xdoc/topics/images/line.png        |  Bin 0 -> 144 bytes
 .../src/site/xdoc/topics/images/minus.gif       |  Bin 0 -> 896 bytes
 .../src/site/xdoc/topics/images/nodata.gif      |  Bin 0 -> 883 bytes
 .../src/site/xdoc/topics/images/node-normal.gif |  Bin 0 -> 171 bytes
 .../site/xdoc/topics/images/node-selected.gif   |  Bin 0 -> 978 bytes
 .../src/site/xdoc/topics/images/plus.gif        |  Bin 0 -> 905 bytes
 .../src/site/xdoc/topics/images/refresh.gif     |  Bin 0 -> 929 bytes
 .../src/site/xdoc/topics/images/secure.gif      |  Bin 0 -> 943 bytes
 .../src/site/xdoc/topics/images/show.gif        |  Bin 0 -> 919 bytes
 .../src/site/xdoc/topics/images/subscribe.gif   |  Bin 0 -> 366 bytes
 .../src/site/xdoc/topics/images/treetop.jpg     |  Bin 0 -> 795 bytes
 .../src/site/xdoc/topics/images/type.gif        |  Bin 0 -> 1037 bytes
 .../src/site/xdoc/topics/images/up.png          |  Bin 0 -> 562 bytes
 .../src/site/xdoc/tracer/docs/images/tracer.jpg |  Bin 0 -> 25921 bytes
 .../site/xdoc/tracer/docs/images/tracer_on.jpg  |  Bin 0 -> 120355 bytes
 .../src/site/xdoc/tracer/docs/userguide.xml     |   78 +
 .../src/site/xdoc/tracer/images/delete.gif      |  Bin 0 -> 606 bytes
 .../src/site/xdoc/tracer/images/refresh.gif     |  Bin 0 -> 251 bytes
 .../src/site/xdoc/tracer/images/tracer.gif      |  Bin 0 -> 1058 bytes
 .../docs/images/transport-statistics-http.jpg   |  Bin 0 -> 290495 bytes
 .../docs/images/transport-statistics.jpg        |  Bin 0 -> 142918 bytes
 .../src/site/xdoc/transport/docs/userguide.xml  |   62 +
 .../xdoc/transport/images/transport-stats.gif   |  Bin 0 -> 1036 bytes
 .../xdoc/tryit/docs/images/choose_endpoints.jpg |  Bin 0 -> 19027 bytes
 .../tryit/docs/images/priority_operations.jpg   |  Bin 0 -> 11654 bytes
 .../src/site/xdoc/tryit/docs/images/results.jpg |  Bin 0 -> 27740 bytes
 .../src/site/xdoc/tryit/docs/userguide.xml      |   93 +
 .../src/site/xdoc/tryit/images/ajax-loader.gif  |  Bin 0 -> 5009 bytes
 .../src/site/xdoc/tryit/images/deprior.png      |  Bin 0 -> 1173 bytes
 .../src/site/xdoc/tryit/images/error.png        |  Bin 0 -> 813 bytes
 .../src/site/xdoc/tryit/images/info.png         |  Bin 0 -> 881 bytes
 .../src/site/xdoc/tryit/images/minus-plus.png   |  Bin 0 -> 2805 bytes
 .../src/site/xdoc/tryit/images/minus.png        |  Bin 0 -> 75 bytes
 .../src/site/xdoc/tryit/images/plus.png         |  Bin 0 -> 82 bytes
 .../src/site/xdoc/tryit/images/prior.png        |  Bin 0 -> 1173 bytes
 .../src/site/xdoc/tryit/images/tryit.gif        |  Bin 0 -> 592 bytes
 .../src/site/xdoc/tryit/images/warrning.png     |  Bin 0 -> 690 bytes
 .../src/site/xdoc/tryit/xslt/prettyprinter.xslt |   73 +
 .../src/site/xdoc/user/docs/userguide.xml       |  100 +
 .../src/site/xdoc/user/images/Thumbs.db         |  Bin 0 -> 12800 bytes
 .../src/site/xdoc/user/images/add.gif           |  Bin 0 -> 407 bytes
 .../site/xdoc/user/images/bulk-import-main.png  |  Bin 0 -> 20476 bytes
 .../src/site/xdoc/user/images/bulk-import.gif   |  Bin 0 -> 1016 bytes
 .../src/site/xdoc/user/images/bulk-import1.png  |  Bin 0 -> 17641 bytes
 .../src/site/xdoc/user/images/bulk-import2.png  |  Bin 0 -> 24853 bytes
 .../src/site/xdoc/user/images/delete.gif        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/user/images/edit.gif          |  Bin 0 -> 1036 bytes
 .../site/xdoc/user/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../site/xdoc/user/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../src/site/xdoc/user/images/test.gif          |  Bin 0 -> 600 bytes
 .../src/site/xdoc/user/images/user-main.png     |  Bin 0 -> 21016 bytes
 .../src/site/xdoc/user/images/user-roles.gif    |  Bin 0 -> 1048 bytes
 .../src/site/xdoc/user/images/user-store.gif    |  Bin 0 -> 589 bytes
 .../src/site/xdoc/user/images/userManager.JPG   |  Bin 0 -> 36706 bytes
 .../src/site/xdoc/user/images/users.JPG         |  Bin 0 -> 24922 bytes
 .../src/site/xdoc/user/images/users.gif         |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/user/images/view.gif          |  Bin 0 -> 596 bytes
 .../distribution/src/site/xdoc/user_guide.xml   |  416 +++
 .../src/site/xdoc/userstore/docs/userguide.xml  |   58 +
 .../userstore/images/External-user store.JPG    |  Bin 0 -> 16722 bytes
 .../src/site/xdoc/userstore/images/add.gif      |  Bin 0 -> 407 bytes
 .../src/site/xdoc/userstore/images/delete.gif   |  Bin 0 -> 555 bytes
 .../src/site/xdoc/userstore/images/edit.gif     |  Bin 0 -> 1036 bytes
 .../xdoc/userstore/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../xdoc/userstore/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../src/site/xdoc/userstore/images/keys.gif     |  Bin 0 -> 969 bytes
 .../src/site/xdoc/userstore/images/roles.JPG    |  Bin 0 -> 20207 bytes
 .../src/site/xdoc/userstore/images/test.gif     |  Bin 0 -> 600 bytes
 .../site/xdoc/userstore/images/user-chpass.png  |  Bin 0 -> 17664 bytes
 .../xdoc/userstore/images/user-role-main.png    |  Bin 0 -> 14744 bytes
 .../site/xdoc/userstore/images/user-roles.gif   |  Bin 0 -> 1048 bytes
 .../site/xdoc/userstore/images/user-store.gif   |  Bin 0 -> 617 bytes
 .../src/site/xdoc/userstore/images/users.gif    |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/userstore/images/view.gif     |  Bin 0 -> 596 bytes
 .../xdoc/viewflows/docs/images/handlers.png     |  Bin 0 -> 20561 bytes
 .../site/xdoc/viewflows/docs/images/phases.png  |  Bin 0 -> 64651 bytes
 .../src/site/xdoc/viewflows/docs/userguide.xml  |   81 +
 .../extensions/core/css/handler_flow.css        |  111 +
 .../extensions/core/images/flows-view.gif       |  Bin 0 -> 573 bytes
 .../core/images/handlerChain_leftmost.gif       |  Bin 0 -> 2154 bytes
 .../images/handlerChain_leftmost_inflow.gif     |  Bin 0 -> 2443 bytes
 .../images/handlerChain_leftmost_outflow.gif    |  Bin 0 -> 2476 bytes
 .../core/images/handlerChain_rightmost.gif      |  Bin 0 -> 1716 bytes
 .../images/handlerChain_rightmost_inflow.gif    |  Bin 0 -> 1962 bytes
 .../images/handlerChain_rightmost_outflow.gif   |  Bin 0 -> 1924 bytes
 .../extensions/core/images/handler_01_BG.gif    |  Bin 0 -> 486 bytes
 .../extensions/core/images/handler_01_left.gif  |  Bin 0 -> 1362 bytes
 .../extensions/core/images/handler_01_right.gif |  Bin 0 -> 1367 bytes
 .../extensions/core/images/handler_02_BG.gif    |  Bin 0 -> 472 bytes
 .../extensions/core/images/handler_02_left.gif  |  Bin 0 -> 1342 bytes
 .../extensions/core/images/handler_02_right.gif |  Bin 0 -> 1512 bytes
 .../extensions/core/images/handler_flow.gif     |  Bin 0 -> 1309 bytes
 .../extensions/core/images/handlers.jpg         |  Bin 0 -> 17669 bytes
 .../viewflows/extensions/core/images/phases.jpg |  Bin 0 -> 37132 bytes
 .../extensions/core/images/text-view.gif        |  Bin 0 -> 158 bytes
 .../xdoc/wsdl2code/docs/images/wsdl2code.jpg    |  Bin 0 -> 103562 bytes
 .../src/site/xdoc/wsdl2code/docs/userguide.xml  |   60 +
 .../src/site/xdoc/wsdl2code/images/dump_aar.gif |  Bin 0 -> 373 bytes
 .../xdoc/wsdl_validator/docs/images/result.png  |  Bin 0 -> 13481 bytes
 .../wsdl_validator/docs/images/upload-wsdl.png  |  Bin 0 -> 8422 bytes
 .../wsdl_validator/docs/images/url-wsdl.png     |  Bin 0 -> 7162 bytes
 .../site/xdoc/wsdl_validator/docs/userguide.xml |   62 +
 .../xdoc/wsdl_validator/images/wsdlValidate.gif |  Bin 0 -> 1001 bytes
 .../1.0.0/modules/p2-profile/pom.xml            |  586 ++++
 .../stratos2/cloud_controller/1.0.0/pom.xml     |  159 ++
 .../stratos2/cloud_controller/1.0.1/INSTALL.txt |   78 +
 .../stratos2/cloud_controller/1.0.1/LICENSE.txt |  512 ++++
 .../stratos2/cloud_controller/1.0.1/README.txt  |  218 ++
 .../1.0.1/docs/resources/css/mb-docs.css        |  173 ++
 .../resources/images/Deployment_Diagram.jpg     |  Bin 0 -> 40421 bytes
 .../1.0.1/docs/resources/images/Login.png       |  Bin 0 -> 112406 bytes
 .../resources/images/MessageFlowDiagram.jpg     |  Bin 0 -> 43164 bytes
 .../docs/resources/images/MessageQueue.jpg      |  Bin 0 -> 41880 bytes
 .../1.0.1/docs/resources/images/addMessage.png  |  Bin 0 -> 83311 bytes
 .../docs/resources/images/addPermission.png     |  Bin 0 -> 93870 bytes
 .../resources/images/cluster_scenario_01.png    |  Bin 0 -> 64444 bytes
 .../resources/images/cluster_scenario_02.png    |  Bin 0 -> 105140 bytes
 .../resources/images/cluster_scenario_03.png    |  Bin 0 -> 105277 bytes
 .../resources/images/cluster_scenario_04.png    |  Bin 0 -> 103247 bytes
 .../resources/images/cluster_scenario_05.png    |  Bin 0 -> 88343 bytes
 .../1.0.1/docs/resources/images/createMB.png    |  Bin 0 -> 68180 bytes
 .../docs/resources/images/listMessageBoxes.png  |  Bin 0 -> 69959 bytes
 .../1.0.1/docs/resources/images/logs.PNG        |  Bin 0 -> 63610 bytes
 .../1.0.1/docs/resources/images/mb-docs-bg.gif  |  Bin 0 -> 520 bytes
 .../docs/resources/images/mb-docs-header.gif    |  Bin 0 -> 5716 bytes
 .../docs/resources/images/retrieveMessage.png   |  Bin 0 -> 84034 bytes
 .../docs/resources/images/set-java-home.jpg     |  Bin 0 -> 84364 bytes
 .../docs/resources/images/state1_esper.png      |  Bin 0 -> 85366 bytes
 .../1.0.1/docs/resources/images/storeConfig.png |  Bin 0 -> 25128 bytes
 .../docs/resources/images/table-header.gif      |  Bin 0 -> 873 bytes
 .../docs/resources/images/topicBrowser.png      |  Bin 0 -> 41142 bytes
 .../images/topic_AddTopicFromDetails.png        |  Bin 0 -> 25193 bytes
 .../1.0.1/docs/resources/images/topic_add.png   |  Bin 0 -> 57217 bytes
 .../resources/images/topic_addSubscription.png  |  Bin 0 -> 76820 bytes
 .../docs/resources/images/topic_browser.png     |  Bin 0 -> 50827 bytes
 .../resources/images/topic_browser_clicked.png  |  Bin 0 -> 55746 bytes
 .../docs/resources/images/topic_details.png     |  Bin 0 -> 70525 bytes
 .../images/topic_subscriptionDetails.png        |  Bin 0 -> 47014 bytes
 .../images/topic_updatePermissions.png          |  Bin 0 -> 85779 bytes
 .../1.0.1/docs/resources/images/user-mgt.PNG    |  Bin 0 -> 8985 bytes
 .../docs/resources/images/userguide_state_1.png |  Bin 0 -> 73672 bytes
 .../docs/resources/images/zookeeperConfig.png   |  Bin 0 -> 19377 bytes
 .../cloud_controller/1.0.1/docs/site.xml        |   70 +
 .../1.0.1/docs/xdoc/admin_guide.xml             |  484 ++++
 .../1.0.1/docs/xdoc/cluster_scenario_01.xml     |  183 ++
 .../1.0.1/docs/xdoc/cluster_scenario_02.xml     |  159 ++
 .../1.0.1/docs/xdoc/cluster_scenario_03.xml     |  199 ++
 .../1.0.1/docs/xdoc/cluster_scenario_04.xml     |  168 ++
 .../1.0.1/docs/xdoc/cluster_scenario_05.xml     |  215 ++
 .../1.0.1/docs/xdoc/deployment_guide.xml        |   90 +
 .../1.0.1/docs/xdoc/docs_index.xml              |   76 +
 .../cloud_controller/1.0.1/docs/xdoc/faq.xml    |   79 +
 .../cloud_controller/1.0.1/docs/xdoc/index.xml  |   70 +
 .../1.0.1/docs/xdoc/installation_guide.xml      |  413 +++
 .../1.0.1/docs/xdoc/release-notes.xml           |  238 ++
 .../docs/xdoc/samples/jms_queue_sample.xml      |  260 ++
 .../docs/xdoc/samples/jms_topic_sample.xml      |  252 ++
 .../docs/xdoc/samples/jms_transport_sample.xml  |  371 +++
 .../xdoc/samples/web_service_client_sample.xml  |  232 ++
 .../1.0.1/docs/xdoc/samples_index.xml           |   79 +
 .../1.0.1/docs/xdoc/setting_java_home.xml       |   53 +
 .../1.0.1/docs/xdoc/source-repository.xml       |  136 +
 .../1.0.1/docs/xdoc/user_guide.xml              |  416 +++
 .../distribution/lib/home/images/bottom.gif     |  Bin 0 -> 523 bytes
 .../distribution/lib/home/images/content-bg.gif |  Bin 0 -> 233 bytes
 .../distribution/lib/home/images/favicon.ico    |  Bin 0 -> 17542 bytes
 .../lib/home/images/feature-01-icon.gif         |  Bin 0 -> 2063 bytes
 .../lib/home/images/feature-02-icon.gif         |  Bin 0 -> 2141 bytes
 .../lib/home/images/feature-03-icon.gif         |  Bin 0 -> 2649 bytes
 .../distribution/lib/home/images/intro-bg.gif   |  Bin 0 -> 3964 bytes
 .../distribution/lib/home/images/logo.gif       |  Bin 0 -> 3931 bytes
 .../lib/home/images/powered-logo.gif            |  Bin 0 -> 1280 bytes
 .../distribution/lib/home/images/register.gif   |  Bin 0 -> 6859 bytes
 .../distribution/lib/home/images/sign-in.gif    |  Bin 0 -> 3256 bytes
 .../distribution/lib/home/images/title-bg.gif   |  Bin 0 -> 1182 bytes
 .../distribution/lib/home/images/top.gif        |  Bin 0 -> 16149 bytes
 .../modules/distribution/lib/home/index.html    |   69 +
 .../modules/distribution/lib/home/style.css     |   46 +
 .../1.0.1/modules/distribution/pom.xml          |  272 ++
 .../distribution/src/main/assembly/bin.xml      |  338 +++
 .../distribution/src/main/assembly/dist.xml     |   36 +
 .../src/main/assembly/filter.properties         |    4 +
 .../distribution/src/main/conf/axis2.xml        |  523 ++++
 .../src/main/conf/cipher-text.properties        |   23 +
 .../src/main/conf/datasources.properties        |   55 +
 .../src/main/conf/embedded-ldap.xml             |  162 ++
 .../distribution/src/main/conf/event-broker.xml |   44 +
 .../distribution/src/main/conf/jaas.conf        |   10 +
 .../distribution/src/main/conf/log4j.properties |  125 +
 .../src/main/conf/rule-component.conf           |    3 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../src/main/conf/synapse.properties            |   35 +
 .../modules/distribution/src/main/conf/zoo.cfg  |    3 +
 .../distribution/src/main/resources/launch.ini  |  248 ++
 .../src/main/resources/log4j.properties         |  193 ++
 .../src/main/resources/wso2server.bat           |  274 ++
 .../src/main/resources/wso2server.sh            |  296 ++
 .../src/site/resources/css/mb-docs.css          |  173 ++
 .../resources/images/Deployment_Diagram.jpg     |  Bin 0 -> 40421 bytes
 .../src/site/resources/images/Login.png         |  Bin 0 -> 112406 bytes
 .../resources/images/MessageFlowDiagram.jpg     |  Bin 0 -> 43164 bytes
 .../src/site/resources/images/MessageQueue.jpg  |  Bin 0 -> 41880 bytes
 .../src/site/resources/images/addMessage.png    |  Bin 0 -> 83311 bytes
 .../src/site/resources/images/addPermission.png |  Bin 0 -> 93870 bytes
 .../resources/images/cluster_scenario_01.png    |  Bin 0 -> 64444 bytes
 .../resources/images/cluster_scenario_02.png    |  Bin 0 -> 105140 bytes
 .../resources/images/cluster_scenario_03.png    |  Bin 0 -> 105277 bytes
 .../resources/images/cluster_scenario_04.png    |  Bin 0 -> 103247 bytes
 .../resources/images/cluster_scenario_05.png    |  Bin 0 -> 88343 bytes
 .../src/site/resources/images/createMB.png      |  Bin 0 -> 68180 bytes
 .../site/resources/images/listMessageBoxes.png  |  Bin 0 -> 69959 bytes
 .../src/site/resources/images/logs.PNG          |  Bin 0 -> 63610 bytes
 .../src/site/resources/images/mb-docs-bg.gif    |  Bin 0 -> 520 bytes
 .../site/resources/images/mb-docs-header.gif    |  Bin 0 -> 5716 bytes
 .../site/resources/images/retrieveMessage.png   |  Bin 0 -> 84034 bytes
 .../src/site/resources/images/set-java-home.jpg |  Bin 0 -> 84364 bytes
 .../src/site/resources/images/state1_esper.png  |  Bin 0 -> 85366 bytes
 .../src/site/resources/images/storeConfig.png   |  Bin 0 -> 25128 bytes
 .../src/site/resources/images/table-header.gif  |  Bin 0 -> 873 bytes
 .../src/site/resources/images/topicBrowser.png  |  Bin 0 -> 41142 bytes
 .../images/topic_AddTopicFromDetails.png        |  Bin 0 -> 25193 bytes
 .../src/site/resources/images/topic_add.png     |  Bin 0 -> 57217 bytes
 .../resources/images/topic_addSubscription.png  |  Bin 0 -> 76820 bytes
 .../src/site/resources/images/topic_browser.png |  Bin 0 -> 50827 bytes
 .../resources/images/topic_browser_clicked.png  |  Bin 0 -> 55746 bytes
 .../src/site/resources/images/topic_details.png |  Bin 0 -> 70525 bytes
 .../images/topic_subscriptionDetails.png        |  Bin 0 -> 47014 bytes
 .../images/topic_updatePermissions.png          |  Bin 0 -> 85779 bytes
 .../src/site/resources/images/user-mgt.PNG      |  Bin 0 -> 8985 bytes
 .../site/resources/images/userguide_state_1.png |  Bin 0 -> 73672 bytes
 .../site/resources/images/zookeeperConfig.png   |  Bin 0 -> 19377 bytes
 .../modules/distribution/src/site/site.xml      |   70 +
 .../site/xdoc/admin/css/carbonFormStyles.css    |  265 ++
 .../src/site/xdoc/admin/css/documentation.css   |   74 +
 .../src/site/xdoc/admin/css/global.css          | 1436 ++++++++++
 .../images/ui-bg_flat_0_aaaaaa_40x100.png       |  Bin 0 -> 180 bytes
 .../images/ui-bg_flat_75_ffffff_40x100.png      |  Bin 0 -> 178 bytes
 .../images/ui-bg_glass_55_fbf9ee_1x400.png      |  Bin 0 -> 120 bytes
 .../images/ui-bg_glass_65_ffffff_1x400.png      |  Bin 0 -> 105 bytes
 .../images/ui-bg_glass_75_dadada_1x400.png      |  Bin 0 -> 111 bytes
 .../images/ui-bg_glass_75_e6e6e6_1x400.png      |  Bin 0 -> 110 bytes
 .../images/ui-bg_glass_95_fef1ec_1x400.png      |  Bin 0 -> 119 bytes
 .../ui-bg_highlight-soft_75_cccccc_1x100.png    |  Bin 0 -> 101 bytes
 .../images/ui-icons_222222_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_2e83ff_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_454545_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_888888_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_cd0a0a_256x240.png          |  Bin 0 -> 4369 bytes
 .../css/smoothness/jquery-ui-1.8.11.custom.css  |  573 ++++
 .../src/site/xdoc/admin/docs/userguide.xml      |  232 ++
 .../src/site/xdoc/admin/images/1px.gif          |  Bin 0 -> 43 bytes
 .../site/xdoc/admin/images/add-collection.gif   |  Bin 0 -> 628 bytes
 .../src/site/xdoc/admin/images/add-link.gif     |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/admin/images/add-resource.gif |  Bin 0 -> 616 bytes
 .../site/xdoc/admin/images/add-small-icon.gif   |  Bin 0 -> 938 bytes
 .../src/site/xdoc/admin/images/add.gif          |  Bin 0 -> 407 bytes
 .../src/site/xdoc/admin/images/addNewTab.gif    |  Bin 0 -> 219 bytes
 .../src/site/xdoc/admin/images/am_logo_h23.gif  |  Bin 0 -> 1536 bytes
 .../site/xdoc/admin/images/application_edit.gif |  Bin 0 -> 1047 bytes
 .../xdoc/admin/images/appserver_logo_h23.gif    |  Bin 0 -> 1574 bytes
 .../src/site/xdoc/admin/images/arrow-down.png   |  Bin 0 -> 284 bytes
 .../src/site/xdoc/admin/images/arrow-up.png     |  Bin 0 -> 319 bytes
 .../src/site/xdoc/admin/images/atom.gif         |  Bin 0 -> 204 bytes
 .../site/xdoc/admin/images/axis2-powered.gif    |  Bin 0 -> 1813 bytes
 .../src/site/xdoc/admin/images/bam_logo_h23.gif |  Bin 0 -> 1808 bytes
 .../src/site/xdoc/admin/images/basket_put.gif   |  Bin 0 -> 599 bytes
 .../site/xdoc/admin/images/basket_remove.gif    |  Bin 0 -> 599 bytes
 .../src/site/xdoc/admin/images/book_add.gif     |  Bin 0 -> 1086 bytes
 .../src/site/xdoc/admin/images/bps_logo_h23.gif |  Bin 0 -> 1725 bytes
 .../src/site/xdoc/admin/images/brick_edit.gif   |  Bin 0 -> 649 bytes
 .../src/site/xdoc/admin/images/brs_logo_h23.gif |  Bin 0 -> 2864 bytes
 .../site/xdoc/admin/images/button-bg-focus.gif  |  Bin 0 -> 111 bytes
 .../site/xdoc/admin/images/button-bg-hover.gif  |  Bin 0 -> 243 bytes
 .../src/site/xdoc/admin/images/button-bg.gif    |  Bin 0 -> 243 bytes
 .../src/site/xdoc/admin/images/buttonRow-bg.gif |  Bin 0 -> 130 bytes
 .../src/site/xdoc/admin/images/calculator.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/admin/images/calendar.gif     |  Bin 0 -> 610 bytes
 .../src/site/xdoc/admin/images/cancel.gif       |  Bin 0 -> 411 bytes
 .../src/site/xdoc/admin/images/cep_logo_h23.gif |  Bin 0 -> 1998 bytes
 .../src/site/xdoc/admin/images/cloneTab.gif     |  Bin 0 -> 170 bytes
 .../xdoc/admin/images/control_play_blue.gif     |  Bin 0 -> 632 bytes
 .../src/site/xdoc/admin/images/copy.gif         |  Bin 0 -> 1036 bytes
 .../xdoc/admin/images/create-checkpoint.gif     |  Bin 0 -> 384 bytes
 .../xdoc/admin/images/default-menu-icon.gif     |  Bin 0 -> 86 bytes
 .../src/site/xdoc/admin/images/delete.gif       |  Bin 0 -> 555 bytes
 .../src/site/xdoc/admin/images/down-arrow.gif   |  Bin 0 -> 610 bytes
 .../src/site/xdoc/admin/images/down-arrow.png   |  Bin 0 -> 791 bytes
 .../src/site/xdoc/admin/images/ds_logo_h23.gif  |  Bin 0 -> 1686 bytes
 .../src/site/xdoc/admin/images/edit.gif         |  Bin 0 -> 1041 bytes
 .../src/site/xdoc/admin/images/elb_logo_h23.gif |  Bin 0 -> 1710 bytes
 .../src/site/xdoc/admin/images/esb_logo_h23.gif |  Bin 0 -> 1714 bytes
 .../src/site/xdoc/admin/images/excelicon.gif    |  Bin 0 -> 1080 bytes
 .../src/site/xdoc/admin/images/exlink.gif       |  Bin 0 -> 292 bytes
 .../src/site/xdoc/admin/images/favicon.ico      |  Bin 0 -> 17542 bytes
 .../src/site/xdoc/admin/images/forum.gif        |  Bin 0 -> 1977 bytes
 .../xdoc/admin/images/gadgetserver_logo_h23.gif |  Bin 0 -> 1556 bytes
 .../src/site/xdoc/admin/images/header-bg.gif    |  Bin 0 -> 495 bytes
 .../src/site/xdoc/admin/images/header-logo.gif  |  Bin 0 -> 1506 bytes
 .../site/xdoc/admin/images/header-region-bg.gif |  Bin 0 -> 369 bytes
 .../src/site/xdoc/admin/images/help-bg.gif      |  Bin 0 -> 465 bytes
 .../src/site/xdoc/admin/images/help-footer.gif  |  Bin 0 -> 1708 bytes
 .../src/site/xdoc/admin/images/help-header.gif  |  Bin 0 -> 9996 bytes
 .../site/xdoc/admin/images/help-small-icon.png  |  Bin 0 -> 631 bytes
 .../src/site/xdoc/admin/images/help.gif         |  Bin 0 -> 411 bytes
 .../src/site/xdoc/admin/images/home-bg.gif      |  Bin 0 -> 145 bytes
 .../src/site/xdoc/admin/images/htmlicon.gif     |  Bin 0 -> 1017 bytes
 .../xdoc/admin/images/icon-feed-small-res.gif   |  Bin 0 -> 1022 bytes
 .../xdoc/admin/images/identity_logo_h23.gif     |  Bin 0 -> 1499 bytes
 .../src/site/xdoc/admin/images/information.gif  |  Bin 0 -> 1025 bytes
 .../src/site/xdoc/admin/images/invisible.gif    |  Bin 0 -> 51 bytes
 .../site/xdoc/admin/images/issue-tracker.gif    |  Bin 0 -> 1821 bytes
 .../xdoc/admin/images/leftRightSlider-dark.png  |  Bin 0 -> 1421 bytes
 .../site/xdoc/admin/images/leftRightSlider.png  |  Bin 0 -> 448 bytes
 .../site/xdoc/admin/images/loading-small.gif    |  Bin 0 -> 673 bytes
 .../src/site/xdoc/admin/images/loading.gif      |  Bin 0 -> 14367 bytes
 .../src/site/xdoc/admin/images/mailing-list.gif |  Bin 0 -> 2064 bytes
 .../src/site/xdoc/admin/images/mainIcons.png    |  Bin 0 -> 1891 bytes
 .../site/xdoc/admin/images/mashup_logo_h23.gif  |  Bin 0 -> 1508 bytes
 .../src/site/xdoc/admin/images/mb_logo_h23.gif  |  Bin 0 -> 1603 bytes
 .../src/site/xdoc/admin/images/menu-header.gif  |  Bin 0 -> 237 bytes
 .../src/site/xdoc/admin/images/mgt-logo.gif     |  Bin 0 -> 2095 bytes
 .../src/site/xdoc/admin/images/minus-plus.png   |  Bin 0 -> 1113 bytes
 .../src/site/xdoc/admin/images/move.gif         |  Bin 0 -> 166 bytes
 .../site/xdoc/admin/images/nseditor-icon.gif    |  Bin 0 -> 1065 bytes
 .../src/site/xdoc/admin/images/oops.gif         |  Bin 0 -> 678 bytes
 .../src/site/xdoc/admin/images/overlay.png      |  Bin 0 -> 289 bytes
 .../src/site/xdoc/admin/images/panelImage.png   |  Bin 0 -> 144 bytes
 .../src/site/xdoc/admin/images/pdficon.gif      |  Bin 0 -> 361 bytes
 .../src/site/xdoc/admin/images/plugin_add.gif   |  Bin 0 -> 1030 bytes
 .../site/xdoc/admin/images/plugin_delete.gif    |  Bin 0 -> 1031 bytes
 .../src/site/xdoc/admin/images/policies.gif     |  Bin 0 -> 387 bytes
 .../xdoc/admin/images/registry_logo_h23.gif     |  Bin 0 -> 1657 bytes
 .../site/xdoc/admin/images/registry_picker.gif  |  Bin 0 -> 1053 bytes
 .../src/site/xdoc/admin/images/rss.gif          |  Bin 0 -> 207 bytes
 .../src/site/xdoc/admin/images/spacer.gif       |  Bin 0 -> 43 bytes
 .../src/site/xdoc/admin/images/star.gif         |  Bin 0 -> 588 bytes
 .../xdoc/admin/images/static-icon-disabled.gif  |  Bin 0 -> 935 bytes
 .../src/site/xdoc/admin/images/static-icon.gif  |  Bin 0 -> 935 bytes
 .../src/site/xdoc/admin/images/table-header.gif |  Bin 0 -> 873 bytes
 .../xdoc/admin/images/trace-icon-disabled.gif   |  Bin 0 -> 950 bytes
 .../src/site/xdoc/admin/images/trace-icon.gif   |  Bin 0 -> 961 bytes
 .../src/site/xdoc/admin/images/up-arrow.gif     |  Bin 0 -> 615 bytes
 .../src/site/xdoc/admin/images/up-arrow.png     |  Bin 0 -> 822 bytes
 .../src/site/xdoc/admin/images/user-guide.gif   |  Bin 0 -> 2161 bytes
 .../src/site/xdoc/admin/images/user.gif         |  Bin 0 -> 604 bytes
 .../site/xdoc/admin/images/view-disabled.gif    |  Bin 0 -> 998 bytes
 .../src/site/xdoc/admin/images/view.gif         |  Bin 0 -> 596 bytes
 .../src/site/xdoc/admin/images/zoom_in.gif      |  Bin 0 -> 575 bytes
 .../src/site/xdoc/admin/images/zoom_out.gif     |  Bin 0 -> 563 bytes
 .../distribution/src/site/xdoc/admin_guide.xml  |  484 ++++
 .../xdoc/andes-cluster-mgt/docs/userguide.xml   |  108 +
 .../images/cassandra-connection.png             |  Bin 0 -> 13921 bytes
 .../andes-cluster-mgt/images/cluster_info.png   |  Bin 0 -> 877 bytes
 .../site/xdoc/andes-cluster-mgt/images/list.gif |  Bin 0 -> 216 bytes
 .../xdoc/andes-cluster-mgt/images/minus.gif     |  Bin 0 -> 896 bytes
 .../site/xdoc/andes-cluster-mgt/images/move.gif |  Bin 0 -> 565 bytes
 .../xdoc/andes-cluster-mgt/images/nodata.gif    |  Bin 0 -> 883 bytes
 .../xdoc/andes-cluster-mgt/images/nodeIDBox.png |  Bin 0 -> 5775 bytes
 .../andes-cluster-mgt/images/nodeQueues.png     |  Bin 0 -> 20833 bytes
 .../images/nodewiseQueueWorkers.png             |  Bin 0 -> 17287 bytes
 .../site/xdoc/andes-cluster-mgt/images/plus.gif |  Bin 0 -> 905 bytes
 .../site/xdoc/andes-cluster-mgt/images/qpid.png |  Bin 0 -> 709 bytes
 .../images/queue_type_admin.gif                 |  Bin 0 -> 481 bytes
 .../images/queue_type_amqp.gif                  |  Bin 0 -> 501 bytes
 .../andes-cluster-mgt/images/queue_type_sqs.gif |  Bin 0 -> 467 bytes
 .../xdoc/andes-cluster-mgt/images/refresh.gif   |  Bin 0 -> 596 bytes
 .../xdoc/andes-cluster-mgt/images/restart.png   |  Bin 0 -> 854 bytes
 .../xdoc/andes-cluster-mgt/images/secure.gif    |  Bin 0 -> 943 bytes
 .../xdoc/andes-cluster-mgt/images/treetop.jpg   |  Bin 0 -> 795 bytes
 .../images/zookeeper-connection.png             |  Bin 0 -> 4968 bytes
 .../andes-cluster-mgt/styles/dsxmleditor.css    |   82 +
 .../andes-cluster-mgt/styles/tree-styles.css    |   36 +
 .../src/site/xdoc/axis2/images/type.gif         |  Bin 0 -> 409 bytes
 .../docs/images/caching configuration.JPG       |  Bin 0 -> 24509 bytes
 .../src/site/xdoc/caching/docs/userguide.xml    |  142 +
 .../src/site/xdoc/cluster_scenario_01.xml       |  183 ++
 .../src/site/xdoc/cluster_scenario_02.xml       |  159 ++
 .../src/site/xdoc/cluster_scenario_03.xml       |  199 ++
 .../src/site/xdoc/cluster_scenario_04.xml       |  168 ++
 .../src/site/xdoc/cluster_scenario_05.xml       |  215 ++
 .../src/site/xdoc/deployment_guide.xml          |   90 +
 .../src/site/xdoc/dialog/css/dialog-ie8.css     |    4 +
 .../src/site/xdoc/dialog/css/dialog.css         |  129 +
 .../jqueryui/images/222222_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../images/222222_11x11_icon_resize_se.gif      |  Bin 0 -> 61 bytes
 .../jqueryui/images/222222_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/222222_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../jqueryui/images/454545_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../jqueryui/images/454545_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/454545_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../jqueryui/images/888888_11x11_icon_close.gif |  Bin 0 -> 62 bytes
 .../jqueryui/images/888888_7x7_arrow_left.gif   |  Bin 0 -> 53 bytes
 .../jqueryui/images/888888_7x7_arrow_right.gif  |  Bin 0 -> 53 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../images/ffffff_40x100_textures_01_flat_0.png |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../css/jqueryui/jqueryui-themeroller.css       |  856 ++++++
 .../src/site/xdoc/dialog/img/confirm.gif        |  Bin 0 -> 2324 bytes
 .../src/site/xdoc/dialog/img/error.gif          |  Bin 0 -> 2258 bytes
 .../src/site/xdoc/dialog/img/info.gif           |  Bin 0 -> 2349 bytes
 .../src/site/xdoc/dialog/img/overlay.png        |  Bin 0 -> 144 bytes
 .../src/site/xdoc/dialog/img/warning.gif        |  Bin 0 -> 2345 bytes
 .../222222_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/222222_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/222222_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../tabs/images/222222_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/222222_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/222222_11x11_icon_resize_se.gif |  Bin 0 -> 61 bytes
 .../tabs/images/222222_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/222222_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/222222_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/222222_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../454545_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/454545_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/454545_11x11_icon_close.gif     |  Bin 0 -> 62 bytes
 .../tabs/images/454545_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../images/454545_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/454545_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../tabs/images/454545_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/454545_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/454545_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/454545_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/454545_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/454545_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../888888_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/888888_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../tabs/images/888888_11x11_icon_close.gif     |  Bin 0 -> 62 bytes
 .../tabs/images/888888_11x11_icon_doc.gif       |  Bin 0 -> 64 bytes
 .../images/888888_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/888888_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../tabs/images/888888_11x11_icon_minus.gif     |  Bin 0 -> 56 bytes
 .../tabs/images/888888_11x11_icon_plus.gif      |  Bin 0 -> 61 bytes
 .../tabs/images/888888_7x7_arrow_down.gif       |  Bin 0 -> 52 bytes
 .../tabs/images/888888_7x7_arrow_left.gif       |  Bin 0 -> 53 bytes
 .../tabs/images/888888_7x7_arrow_right.gif      |  Bin 0 -> 53 bytes
 .../tabs/images/888888_7x7_arrow_up.gif         |  Bin 0 -> 52 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../ffffff_40x100_textures_01_flat_75.png       |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../xdoc/dialog/js/jqueryui/tabs/ui.all.css     |  609 +++++
 .../distribution/src/site/xdoc/docs/about.xml   |  125 +
 .../src/site/xdoc/docs/images/login.png         |  Bin 0 -> 5995 bytes
 .../src/site/xdoc/docs/signin_userguide.xml     |   70 +
 .../distribution/src/site/xdoc/docs_index.xml   |   76 +
 .../src/site/xdoc/eventing/css/dsxmleditor.css  |   82 +
 .../site/xdoc/eventing/css/subscriptions.css    |   12 +
 .../src/site/xdoc/eventing/css/tree-styles.css  |   36 +
 .../src/site/xdoc/eventing/images/add.gif       |  Bin 0 -> 407 bytes
 .../src/site/xdoc/eventing/images/down.png      |  Bin 0 -> 555 bytes
 .../src/site/xdoc/eventing/images/hide.gif      |  Bin 0 -> 919 bytes
 .../src/site/xdoc/eventing/images/list.gif      |  Bin 0 -> 216 bytes
 .../src/site/xdoc/eventing/images/minus.gif     |  Bin 0 -> 896 bytes
 .../src/site/xdoc/eventing/images/nodata.gif    |  Bin 0 -> 883 bytes
 .../src/site/xdoc/eventing/images/plus.gif      |  Bin 0 -> 905 bytes
 .../src/site/xdoc/eventing/images/refresh.gif   |  Bin 0 -> 929 bytes
 .../src/site/xdoc/eventing/images/secure.gif    |  Bin 0 -> 943 bytes
 .../src/site/xdoc/eventing/images/show.gif      |  Bin 0 -> 919 bytes
 .../site/xdoc/eventing/images/subscriptions.gif |  Bin 0 -> 369 bytes
 .../src/site/xdoc/eventing/images/topics.gif    |  Bin 0 -> 147 bytes
 .../src/site/xdoc/eventing/images/treetop.jpg   |  Bin 0 -> 795 bytes
 .../src/site/xdoc/eventing/images/type.gif      |  Bin 0 -> 1037 bytes
 .../src/site/xdoc/eventing/images/up.png        |  Bin 0 -> 562 bytes
 .../modules/distribution/src/site/xdoc/faq.xml  |   79 +
 .../222222_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/222222_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/222222_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../css/images/222222_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/222222_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/222222_11x11_icon_resize_se.gif  |  Bin 0 -> 61 bytes
 .../css/images/222222_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/222222_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/222222_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/222222_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../454545_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/454545_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/454545_11x11_icon_close.gif      |  Bin 0 -> 62 bytes
 .../css/images/454545_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../images/454545_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/454545_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../css/images/454545_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/454545_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/454545_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/454545_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/454545_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/454545_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../888888_11x11_icon_arrows_leftright.gif      |  Bin 0 -> 58 bytes
 .../images/888888_11x11_icon_arrows_updown.gif  |  Bin 0 -> 56 bytes
 .../css/images/888888_11x11_icon_close.gif      |  Bin 0 -> 62 bytes
 .../css/images/888888_11x11_icon_doc.gif        |  Bin 0 -> 64 bytes
 .../images/888888_11x11_icon_folder_closed.gif  |  Bin 0 -> 61 bytes
 .../images/888888_11x11_icon_folder_open.gif    |  Bin 0 -> 61 bytes
 .../css/images/888888_11x11_icon_minus.gif      |  Bin 0 -> 56 bytes
 .../css/images/888888_11x11_icon_plus.gif       |  Bin 0 -> 61 bytes
 .../css/images/888888_7x7_arrow_down.gif        |  Bin 0 -> 52 bytes
 .../css/images/888888_7x7_arrow_left.gif        |  Bin 0 -> 53 bytes
 .../css/images/888888_7x7_arrow_right.gif       |  Bin 0 -> 53 bytes
 .../css/images/888888_7x7_arrow_up.gif          |  Bin 0 -> 52 bytes
 .../feature-mgt/css/images/buttonRow-bg.gif     |  Bin 0 -> 130 bytes
 .../dadada_40x100_textures_02_glass_75.png      |  Bin 0 -> 214 bytes
 .../e6e6e6_40x100_textures_02_glass_75.png      |  Bin 0 -> 211 bytes
 .../ffffff_40x100_textures_01_flat_75.png       |  Bin 0 -> 178 bytes
 .../ffffff_40x100_textures_02_glass_65.png      |  Bin 0 -> 207 bytes
 .../src/site/xdoc/feature-mgt/css/ui.all.css    |  699 +++++
 .../docs/images/add-repositories.jpg.png        |  Bin 0 -> 10889 bytes
 .../docs/images/add-repositories.png            |  Bin 0 -> 18886 bytes
 .../images/available-features-uncategorized.png |  Bin 0 -> 125809 bytes
 .../docs/images/available-features.png          |  Bin 0 -> 55734 bytes
 .../docs/images/back-end-front-end.png          |  Bin 0 -> 27818 bytes
 .../docs/images/configuration-details.png       |  Bin 0 -> 21515 bytes
 .../docs/images/edit-repositories.png           |  Bin 0 -> 14335 bytes
 .../feature-mgt/docs/images/find-features.png   |  Bin 0 -> 44004 bytes
 .../images/installation-complete-message.png    |  Bin 0 -> 7649 bytes
 .../docs/images/installation-history.png        |  Bin 0 -> 30799 bytes
 .../docs/images/installed-features.png          |  Bin 0 -> 31229 bytes
 .../docs/images/licence-agreement.png           |  Bin 0 -> 59591 bytes
 .../docs/images/manage-repositories.png         |  Bin 0 -> 33724 bytes
 .../docs/images/review-installation.png         |  Bin 0 -> 27514 bytes
 .../images/select-a-category-to-install.png     |  Bin 0 -> 115949 bytes
 .../site/xdoc/feature-mgt/docs/userguide.xml    |  170 ++
 .../site/xdoc/feature-mgt/images/activate.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/feature-mgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../xdoc/feature-mgt/images/comp-manager.gif    |  Bin 0 -> 580 bytes
 .../site/xdoc/feature-mgt/images/deactivate.gif |  Bin 0 -> 606 bytes
 .../xdoc/feature-mgt/images/install-feature.png |  Bin 0 -> 783 bytes
 .../site/xdoc/feature-mgt/images/magnifier.gif  |  Bin 0 -> 578 bytes
 .../src/site/xdoc/feature-mgt/images/minus.gif  |  Bin 0 -> 896 bytes
 .../site/xdoc/feature-mgt/images/more-info.gif  |  Bin 0 -> 617 bytes
 .../src/site/xdoc/feature-mgt/images/nodata.gif |  Bin 0 -> 883 bytes
 .../src/site/xdoc/feature-mgt/images/plus.gif   |  Bin 0 -> 905 bytes
 .../src/site/xdoc/feature-mgt/images/search.gif |  Bin 0 -> 578 bytes
 .../src/site/xdoc/feature-mgt/images/spacer.png |  Bin 0 -> 144 bytes
 .../feature-mgt/images/uninstall-feature.png    |  Bin 0 -> 769 bytes
 .../xdoc/highlighter/css/SyntaxHighlighter.css  |  185 ++
 .../src/site/xdoc/highlighter/js/clipboard.swf  |  Bin 0 -> 109 bytes
 .../src/site/xdoc/images/keystores1.jpg         |  Bin 0 -> 14288 bytes
 .../src/site/xdoc/images/keystores2.jpg         |  Bin 0 -> 15098 bytes
 .../distribution/src/site/xdoc/images/menu.jpg  |  Bin 0 -> 15430 bytes
 .../src/site/xdoc/images/usergroups.jpg         |  Bin 0 -> 13759 bytes
 .../distribution/src/site/xdoc/images/users.jpg |  Bin 0 -> 10656 bytes
 .../src/site/xdoc/images/userstores.jpg         |  Bin 0 -> 15682 bytes
 .../distribution/src/site/xdoc/index.xml        |   70 +
 .../src/site/xdoc/installation_guide.xml        |  413 +++
 .../xdoc/java2wsdl/docs/images/add_resource.png |  Bin 0 -> 12443 bytes
 .../xdoc/java2wsdl/docs/images/java2wsdl.png    |  Bin 0 -> 77420 bytes
 .../src/site/xdoc/java2wsdl/docs/userguide.xml  |   55 +
 .../site/xdoc/java2wsdl/images/java2wsdl.gif    |  Bin 0 -> 399 bytes
 .../keystoremgt/docs/images/adding-keystore.JPG |  Bin 0 -> 19638 bytes
 .../docs/images/keystoremanagement.JPG          |  Bin 0 -> 12691 bytes
 .../site/xdoc/keystoremgt/docs/userguide.xml    |   77 +
 .../src/site/xdoc/keystoremgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../src/site/xdoc/keystoremgt/images/close.gif  |  Bin 0 -> 403 bytes
 .../src/site/xdoc/keystoremgt/images/delete.gif |  Bin 0 -> 555 bytes
 .../src/site/xdoc/keystoremgt/images/edit.gif   |  Bin 0 -> 1036 bytes
 .../xdoc/keystoremgt/images/import-cert.png     |  Bin 0 -> 13474 bytes
 .../src/site/xdoc/keystoremgt/images/import.gif |  Bin 0 -> 618 bytes
 .../site/xdoc/keystoremgt/images/keystore.gif   |  Bin 0 -> 604 bytes
 .../xdoc/keystoremgt/images/view-keystore.png   |  Bin 0 -> 20459 bytes
 .../src/site/xdoc/keystoremgt/images/view.gif   |  Bin 0 -> 596 bytes
 .../docs/images/config log appenders.JPG        |  Bin 0 -> 36196 bytes
 .../docs/images/config log4j loggers.JPG        |  Bin 0 -> 164685 bytes
 .../xdoc/log-admin/docs/images/configSyslog.JPG |  Bin 0 -> 19463 bytes
 .../docs/images/global log4j config.JPG         |  Bin 0 -> 20579 bytes
 .../xdoc/log-admin/docs/images/logging_mgt.jpg  |  Bin 0 -> 1669302 bytes
 .../log-admin/docs/images/syslogProperties.JPG  |  Bin 0 -> 21796 bytes
 .../src/site/xdoc/log-admin/docs/userguide.xml  |  112 +
 .../src/site/xdoc/log-admin/images/log.gif      |  Bin 0 -> 596 bytes
 .../xdoc/log-view/docs/images/application.jpg   |  Bin 0 -> 83936 bytes
 .../src/site/xdoc/log-view/docs/images/log.jpg  |  Bin 0 -> 1575250 bytes
 .../site/xdoc/log-view/docs/images/logIndex.jpg |  Bin 0 -> 35191 bytes
 .../site/xdoc/log-view/docs/images/logview.jpg  |  Bin 0 -> 104153 bytes
 .../src/site/xdoc/log-view/docs/userguide.xml   |   76 +
 .../src/site/xdoc/log-view/images/cancel.gif    |  Bin 0 -> 1032 bytes
 .../src/site/xdoc/log-view/images/collapse.gif  |  Bin 0 -> 102 bytes
 .../src/site/xdoc/log-view/images/debug.png     |  Bin 0 -> 775 bytes
 .../src/site/xdoc/log-view/images/download.gif  |  Bin 0 -> 146 bytes
 .../src/site/xdoc/log-view/images/error.png     |  Bin 0 -> 778 bytes
 .../src/site/xdoc/log-view/images/expand.gif    |  Bin 0 -> 102 bytes
 .../src/site/xdoc/log-view/images/fatal.png     |  Bin 0 -> 670 bytes
 .../site/xdoc/log-view/images/information.gif   |  Bin 0 -> 1025 bytes
 .../src/site/xdoc/log-view/images/magnifier.gif |  Bin 0 -> 578 bytes
 .../src/site/xdoc/log-view/images/minus.gif     |  Bin 0 -> 896 bytes
 .../src/site/xdoc/log-view/images/plus.gif      |  Bin 0 -> 905 bytes
 .../site/xdoc/log-view/images/script_gear.gif   |  Bin 0 -> 1082 bytes
 .../src/site/xdoc/log-view/images/search.gif    |  Bin 0 -> 578 bytes
 .../src/site/xdoc/log-view/images/trace.png     |  Bin 0 -> 900 bytes
 .../src/site/xdoc/log-view/images/view.gif      |  Bin 0 -> 596 bytes
 .../src/site/xdoc/log-view/images/warn.png      |  Bin 0 -> 741 bytes
 .../xdoc/mediation/images/mediation-icon.gif    |  Bin 0 -> 573 bytes
 .../menugeneral/images/chart_organisation.gif   |  Bin 0 -> 558 bytes
 .../site/xdoc/menugeneral/images/magnifier.gif  |  Bin 0 -> 578 bytes
 .../xdoc/modulemgt/docs/images/addmodule.png    |  Bin 0 -> 19515 bytes
 .../xdoc/modulemgt/docs/images/global-after.png |  Bin 0 -> 111586 bytes
 .../modulemgt/docs/images/global-before.png     |  Bin 0 -> 106993 bytes
 .../modulemgt/docs/images/global-throttling.png |  Bin 0 -> 36168 bytes
 .../src/site/xdoc/modulemgt/docs/userguide.xml  |  138 +
 .../src/site/xdoc/modulemgt/images/add.gif      |  Bin 0 -> 407 bytes
 .../src/site/xdoc/modulemgt/images/bricks.gif   |  Bin 0 -> 1051 bytes
 .../site/xdoc/modulemgt/images/configure.gif    |  Bin 0 -> 608 bytes
 .../src/site/xdoc/modulemgt/images/delete.gif   |  Bin 0 -> 555 bytes
 .../site/xdoc/modulemgt/images/disengage.gif    |  Bin 0 -> 595 bytes
 .../src/site/xdoc/modulemgt/images/edit.gif     |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/modulemgt/images/engage.gif   |  Bin 0 -> 603 bytes
 .../src/site/xdoc/modulemgt/images/list.gif     |  Bin 0 -> 216 bytes
 .../src/site/xdoc/modulemgt/images/policies.gif |  Bin 0 -> 387 bytes
 .../src/site/xdoc/modulemgt/images/restart.png  |  Bin 0 -> 3334 bytes
 .../src/site/xdoc/modulemgt/images/shutdown.png |  Bin 0 -> 3347 bytes
 .../site/xdoc/modulemgt/images/shutdowng.png    |  Bin 0 -> 2785 bytes
 .../docs/images/operation-dashboard.jpg         |  Bin 0 -> 72822 bytes
 .../docs/images/published-operations.jpg        |  Bin 0 -> 15138 bytes
 .../src/site/xdoc/operation/docs/userguide.xml  |  105 +
 .../src/site/xdoc/operation/images/add.gif      |  Bin 0 -> 1315 bytes
 .../src/site/xdoc/operation/images/caching.gif  |  Bin 0 -> 630 bytes
 .../src/site/xdoc/operation/images/delete.gif   |  Bin 0 -> 606 bytes
 .../src/site/xdoc/operation/images/flows.gif    |  Bin 0 -> 1309 bytes
 .../src/site/xdoc/operation/images/modules.gif  |  Bin 0 -> 1051 bytes
 .../site/xdoc/operation/images/parameters.gif   |  Bin 0 -> 1041 bytes
 .../src/site/xdoc/operation/images/service.gif  |  Bin 0 -> 638 bytes
 .../site/xdoc/operation/images/throttling.gif   |  Bin 0 -> 349 bytes
 .../site/xdoc/policyeditor/css/local-styles.css |   48 +
 .../docs/images/policy-editor-design-view.png   |  Bin 0 -> 71422 bytes
 .../docs/images/policy-editor-source-view.png   |  Bin 0 -> 83111 bytes
 .../docs/images/select-service-policies.png     |  Bin 0 -> 17068 bytes
 .../docs/images/service-policy-hierarchy.png    |  Bin 0 -> 38498 bytes
 .../site/xdoc/policyeditor/docs/userguide.xml   |   75 +
 .../xdoc/properties/images/icon-expanded.gif    |  Bin 0 -> 389 bytes
 .../xdoc/properties/images/icon-minimized.gif   |  Bin 0 -> 405 bytes
 .../site/xdoc/properties/images/save-button.gif |  Bin 0 -> 623 bytes
 .../src/site/xdoc/queues/docs/userguide.xml     |   92 +
 .../src/site/xdoc/queues/images/add.gif         |  Bin 0 -> 407 bytes
 .../src/site/xdoc/queues/images/list.gif        |  Bin 0 -> 216 bytes
 .../src/site/xdoc/queues/images/minus.gif       |  Bin 0 -> 896 bytes
 .../src/site/xdoc/queues/images/move.gif        |  Bin 0 -> 565 bytes
 .../src/site/xdoc/queues/images/nodata.gif      |  Bin 0 -> 883 bytes
 .../src/site/xdoc/queues/images/plus.gif        |  Bin 0 -> 905 bytes
 .../src/site/xdoc/queues/images/qpid.png        |  Bin 0 -> 709 bytes
 .../src/site/xdoc/queues/images/queue_add.png   |  Bin 0 -> 29186 bytes
 .../xdoc/queues/images/queue_add_success.png    |  Bin 0 -> 21010 bytes
 .../site/xdoc/queues/images/queue_browse.png    |  Bin 0 -> 25479 bytes
 .../xdoc/queues/images/queue_delete_success.png |  Bin 0 -> 20681 bytes
 .../xdoc/queues/images/queue_from_tenant.png    |  Bin 0 -> 18297 bytes
 .../xdoc/queues/images/queue_type_admin.gif     |  Bin 0 -> 481 bytes
 .../site/xdoc/queues/images/queue_type_amqp.gif |  Bin 0 -> 501 bytes
 .../site/xdoc/queues/images/queue_type_sqs.gif  |  Bin 0 -> 467 bytes
 .../src/site/xdoc/queues/images/queues.gif      |  Bin 0 -> 366 bytes
 .../src/site/xdoc/queues/images/refresh.gif     |  Bin 0 -> 596 bytes
 .../src/site/xdoc/queues/images/restart.png     |  Bin 0 -> 854 bytes
 .../src/site/xdoc/queues/images/secure.gif      |  Bin 0 -> 943 bytes
 .../src/site/xdoc/queues/images/treetop.jpg     |  Bin 0 -> 795 bytes
 .../src/site/xdoc/queues/styles/dsxmleditor.css |   82 +
 .../src/site/xdoc/queues/styles/tree-styles.css |   36 +
 .../src/site/xdoc/release-notes.xml             |  238 ++
 .../site/xdoc/resources/css/registry-ie7.css    |    7 +
 .../site/xdoc/resources/css/registry-ie8.css    |    4 +
 .../src/site/xdoc/resources/css/registry.css    |  842 ++++++
 .../resources/docs/images/HierSubscriptions.png |  Bin 0 -> 27885 bytes
 .../resources/docs/images/addCollection.png     |  Bin 0 -> 10514 bytes
 .../xdoc/resources/docs/images/addResource.png  |  Bin 0 -> 22508 bytes
 .../resources/docs/images/add_remotelink.png    |  Bin 0 -> 741710 bytes
 .../resources/docs/images/add_subscription.png  |  Bin 0 -> 20527 bytes
 .../xdoc/resources/docs/images/add_symlink.png  |  Bin 0 -> 666765 bytes
 .../xdoc/resources/docs/images/associations.png |  Bin 0 -> 20179 bytes
 .../xdoc/resources/docs/images/breadcrumb.png   |  Bin 0 -> 6649 bytes
 .../xdoc/resources/docs/images/comments.png     |  Bin 0 -> 13497 bytes
 .../site/xdoc/resources/docs/images/content.png |  Bin 0 -> 27060 bytes
 .../xdoc/resources/docs/images/dependency.png   |  Bin 0 -> 19592 bytes
 .../xdoc/resources/docs/images/detail_view.png  |  Bin 0 -> 70192 bytes
 .../xdoc/resources/docs/images/details_view.png |  Bin 0 -> 46680 bytes
 .../resources/docs/images/edit_mime_types.png   |  Bin 0 -> 767343 bytes
 .../site/xdoc/resources/docs/images/entries.png |  Bin 0 -> 552380 bytes
 .../xdoc/resources/docs/images/lifeCycles.png   |  Bin 0 -> 10306 bytes
 .../docs/images/manage_notifications.png        |  Bin 0 -> 17486 bytes
 .../xdoc/resources/docs/images/metadata.png     |  Bin 0 -> 20963 bytes
 .../xdoc/resources/docs/images/properties.png   |  Bin 0 -> 19831 bytes
 .../site/xdoc/resources/docs/images/rating.png  |  Bin 0 -> 6484 bytes
 .../resources/docs/images/registryBrowser.png   |  Bin 0 -> 40815 bytes
 .../site/xdoc/resources/docs/images/symlink.png |  Bin 0 -> 376850 bytes
 .../xdoc/resources/docs/images/tagSearch.png    |  Bin 0 -> 4565 bytes
 .../site/xdoc/resources/docs/images/tags.png    |  Bin 0 -> 10957 bytes
 .../xdoc/resources/docs/images/version_view.png |  Bin 0 -> 21283 bytes
 .../src/site/xdoc/resources/docs/userguide.xml  |  404 +++
 .../xdoc/resources/images/TrainingTitleBack.jpg |  Bin 0 -> 331 bytes
 .../site/xdoc/resources/images/ajax-loader.gif  |  Bin 0 -> 673 bytes
 .../site/xdoc/resources/images/arrow-right.gif  |  Bin 0 -> 651 bytes
 .../src/site/xdoc/resources/images/arrow-up.gif |  Bin 0 -> 1049 bytes
 .../src/site/xdoc/resources/images/back.gif     |  Bin 0 -> 622 bytes
 .../site/xdoc/resources/images/button-back.gif  |  Bin 0 -> 121 bytes
 .../xdoc/resources/images/button_center.gif     |  Bin 0 -> 865 bytes
 .../resources/images/button_center_focus.gif    |  Bin 0 -> 860 bytes
 .../resources/images/button_center_over.gif     |  Bin 0 -> 853 bytes
 .../src/site/xdoc/resources/images/calendar.jpg |  Bin 0 -> 572 bytes
 .../resources/images/cancel-save-button.gif     |  Bin 0 -> 576 bytes
 .../src/site/xdoc/resources/images/colSep.jpg   |  Bin 0 -> 376 bytes
 .../site/xdoc/resources/images/col_header.gif   |  Bin 0 -> 866 bytes
 .../images/collection-extn-mounted.gif          |  Bin 0 -> 614 bytes
 .../xdoc/resources/images/collection-extn.gif   |  Bin 0 -> 1006 bytes
 .../src/site/xdoc/resources/images/config.gif   |  Bin 0 -> 1006 bytes
 .../site/xdoc/resources/images/editshred.png    |  Bin 0 -> 526 bytes
 .../src/site/xdoc/resources/images/goto_url.gif |  Bin 0 -> 1028 bytes
 .../site/xdoc/resources/images/help-small.jpg   |  Bin 0 -> 485 bytes
 .../xdoc/resources/images/icon-add-folder.gif   |  Bin 0 -> 628 bytes
 .../xdoc/resources/images/icon-add-resource.gif |  Bin 0 -> 616 bytes
 .../site/xdoc/resources/images/icon-copy.jpg    |  Bin 0 -> 647 bytes
 .../xdoc/resources/images/icon-detail-view.png  |  Bin 0 -> 369 bytes
 .../site/xdoc/resources/images/icon-details.jpg |  Bin 0 -> 475 bytes
 .../xdoc/resources/images/icon-download.jpg     |  Bin 0 -> 466 bytes
 .../xdoc/resources/images/icon-expanded.gif     |  Bin 0 -> 389 bytes
 .../xdoc/resources/images/icon-feed-small.gif   |  Bin 0 -> 664 bytes
 .../xdoc/resources/images/icon-folder-small.gif |  Bin 0 -> 631 bytes
 .../xdoc/resources/images/icon-minimized.gif    |  Bin 0 -> 405 bytes
 .../site/xdoc/resources/images/icon-move.jpg    |  Bin 0 -> 580 bytes
 .../site/xdoc/resources/images/icon-restore.gif |  Bin 0 -> 639 bytes
 .../site/xdoc/resources/images/icon-search.gif  |  Bin 0 -> 1003 bytes
 .../xdoc/resources/images/icon-tree-minus.gif   |  Bin 0 -> 955 bytes
 .../xdoc/resources/images/icon-tree-minus.jpg   |  Bin 0 -> 667 bytes
 .../xdoc/resources/images/icon-tree-plus.gif    |  Bin 0 -> 988 bytes
 .../xdoc/resources/images/icon-tree-plus.jpg    |  Bin 0 -> 493 bytes
 .../site/xdoc/resources/images/icon-tree.png    |  Bin 0 -> 528 bytes
 .../site/xdoc/resources/images/icon-upload.jpg  |  Bin 0 -> 1167 bytes
 .../site/xdoc/resources/images/icon-vlidate.jpg |  Bin 0 -> 653 bytes
 .../site/xdoc/resources/images/menu-back.gif    |  Bin 0 -> 92 bytes
 .../site/xdoc/resources/images/menu-back.jpg    |  Bin 0 -> 347 bytes
 .../xdoc/resources/images/page-back-repeat.jpg  |  Bin 0 -> 4215 bytes
 .../site/xdoc/resources/images/page-back.jpg    |  Bin 0 -> 351 bytes
 .../xdoc/resources/images/page-left-top.gif     |  Bin 0 -> 291 bytes
 .../site/xdoc/resources/images/pageheader.gif   |  Bin 0 -> 886 bytes
 .../site/xdoc/resources/images/point-left.gif   |  Bin 0 -> 407 bytes
 .../site/xdoc/resources/images/point-right.gif  |  Bin 0 -> 401 bytes
 .../src/site/xdoc/resources/images/popback.png  |  Bin 0 -> 144 bytes
 .../xdoc/resources/images/portlet_header.gif    |  Bin 0 -> 866 bytes
 .../resources/images/promotionBackground.jpg    |  Bin 0 -> 379 bytes
 .../src/site/xdoc/resources/images/r00.gif      |  Bin 0 -> 577 bytes
 .../src/site/xdoc/resources/images/r01.gif      |  Bin 0 -> 980 bytes
 .../src/site/xdoc/resources/images/r02.gif      |  Bin 0 -> 980 bytes
 .../src/site/xdoc/resources/images/r03.gif      |  Bin 0 -> 981 bytes
 .../src/site/xdoc/resources/images/r04.gif      |  Bin 0 -> 582 bytes
 .../src/site/xdoc/resources/images/r44.gif      |  Bin 0 -> 582 bytes
 .../src/site/xdoc/resources/images/r4x.gif      |  Bin 0 -> 582 bytes
 .../resources/images/resource-extn-mounted.gif  |  Bin 0 -> 619 bytes
 .../xdoc/resources/images/resource-extn.gif     |  Bin 0 -> 1015 bytes
 .../src/site/xdoc/resources/images/resource.gif |  Bin 0 -> 1008 bytes
 .../site/xdoc/resources/images/resources.gif    |  Bin 0 -> 1028 bytes
 .../site/xdoc/resources/images/save-button.gif  |  Bin 0 -> 623 bytes
 .../site/xdoc/resources/images/seperator.gif    |  Bin 0 -> 817 bytes
 .../xdoc/resources/images/sidemenu_header.gif   |  Bin 0 -> 873 bytes
 .../src/site/xdoc/resources/images/spacer.gif   |  Bin 0 -> 68 bytes
 .../src/site/xdoc/resources/images/spacer.jpg   |  Bin 0 -> 309 bytes
 .../src/site/xdoc/resources/images/sqr.gif      |  Bin 0 -> 812 bytes
 .../resources/images/submain-title-back.jpg     |  Bin 0 -> 361 bytes
 .../site/xdoc/resources/images/table_header.gif |  Bin 0 -> 212 bytes
 .../site/xdoc/resources/images/titleBack.jpg    |  Bin 0 -> 370 bytes
 .../src/site/xdoc/resources/images/to-root.gif  |  Bin 0 -> 1023 bytes
 .../xdoc/resources/images/universal-add.gif     |  Bin 0 -> 986 bytes
 .../site/xdoc/resources/images/viewIcons.png    |  Bin 0 -> 5179 bytes
 .../site/xdoc/resources/images/view_tree.gif    |  Bin 0 -> 1090 bytes
 .../site/xdoc/resources/images/visualize.png    |  Bin 0 -> 842 bytes
 .../xdoc/resources/images/welcomebanner.gif     |  Bin 0 -> 878 bytes
 .../resources/images/window-headding-back.gif   |  Bin 0 -> 838 bytes
 .../src/site/xdoc/resources/xslt/XMLSchema.dtd  |  402 +++
 .../src/site/xdoc/resources/xslt/XMLSchema.xsd  | 2312 ++++++++++++++++
 .../src/site/xdoc/resources/xslt/datatypes.dtd  |  200 ++
 .../src/site/xdoc/rm/docs/images/rm.jpg         |  Bin 0 -> 88288 bytes
 .../src/site/xdoc/rm/docs/userguide.xml         |  158 ++
 .../src/site/xdoc/role/docs/rolepermissions.xml |  153 ++
 .../src/site/xdoc/role/docs/userguide.xml       |  111 +
 .../src/site/xdoc/role/images/Thumbs.db         |  Bin 0 -> 12800 bytes
 .../src/site/xdoc/role/images/add-role1.png     |  Bin 0 -> 14525 bytes
 .../src/site/xdoc/role/images/add-role2.png     |  Bin 0 -> 34733 bytes
 .../src/site/xdoc/role/images/add-role3.png     |  Bin 0 -> 20692 bytes
 .../src/site/xdoc/role/images/add.gif           |  Bin 0 -> 407 bytes
 .../src/site/xdoc/role/images/check0.gif        |  Bin 0 -> 608 bytes
 .../src/site/xdoc/role/images/check1.gif        |  Bin 0 -> 609 bytes
 .../src/site/xdoc/role/images/check2.gif        |  Bin 0 -> 622 bytes
 .../src/site/xdoc/role/images/contractall.gif   |  Bin 0 -> 987 bytes
 .../src/site/xdoc/role/images/delete.gif        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/role/images/edit.gif          |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/role/images/expandall.gif     |  Bin 0 -> 983 bytes
 .../site/xdoc/role/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../site/xdoc/role/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../site/xdoc/role/images/permission-edit.png   |  Bin 0 -> 23367 bytes
 .../src/site/xdoc/role/images/role-main.png     |  Bin 0 -> 17918 bytes
 .../src/site/xdoc/role/images/test.gif          |  Bin 0 -> 600 bytes
 .../src/site/xdoc/role/images/user-roles.gif    |  Bin 0 -> 1048 bytes
 .../src/site/xdoc/role/images/user-store.gif    |  Bin 0 -> 589 bytes
 .../src/site/xdoc/role/images/users.gif         |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/role/images/view.gif          |  Bin 0 -> 596 bytes
 .../src/site/xdoc/role/js/treeview.css          |    7 +
 .../site/xdoc/roles-mgt/docs/server-roles.xml   |   62 +
 .../src/site/xdoc/roles-mgt/docs/userguide.xml  |   91 +
 .../src/site/xdoc/roles-mgt/images/add.gif      |  Bin 0 -> 407 bytes
 .../xdoc/roles-mgt/images/add_server_role.jpg   |  Bin 0 -> 46641 bytes
 .../src/site/xdoc/roles-mgt/images/delete.gif   |  Bin 0 -> 555 bytes
 .../roles-mgt/images/delete_server_role.jpg     |  Bin 0 -> 38559 bytes
 .../xdoc/roles-mgt/images/icon-expanded.gif     |  Bin 0 -> 389 bytes
 .../xdoc/roles-mgt/images/icon-minimized.gif    |  Bin 0 -> 405 bytes
 .../site/xdoc/roles-mgt/images/landingpage.jpg  |  Bin 0 -> 95016 bytes
 .../site/xdoc/roles-mgt/images/server-role.gif  |  Bin 0 -> 1073 bytes
 .../src/site/xdoc/samples/jms_queue_sample.xml  |  260 ++
 .../src/site/xdoc/samples/jms_topic_sample.xml  |  252 ++
 .../site/xdoc/samples/jms_transport_sample.xml  |  371 +++
 .../xdoc/samples/web_service_client_sample.xml  |  232 ++
 .../src/site/xdoc/samples_index.xml             |   79 +
 .../src/site/xdoc/search/css/search.css         |   25 +
 .../xdoc/search/docs/images/configuration.png   |  Bin 0 -> 49079 bytes
 .../xdoc/search/docs/images/custom_search.png   |  Bin 0 -> 48792 bytes
 .../src/site/xdoc/search/docs/images/date.png   |  Bin 0 -> 54047 bytes
 .../xdoc/search/docs/images/load_filter.png     |  Bin 0 -> 15375 bytes
 .../src/site/xdoc/search/docs/images/main.png   |  Bin 0 -> 43061 bytes
 .../xdoc/search/docs/images/reporting_crumb.png |  Bin 0 -> 4290 bytes
 .../xdoc/search/docs/images/save_filter.png     |  Bin 0 -> 10440 bytes
 .../src/site/xdoc/search/docs/userguide.xml     |  102 +
 .../src/site/xdoc/search/images/arrow-down.png  |  Bin 0 -> 529 bytes
 .../src/site/xdoc/search/images/arrow-up.png    |  Bin 0 -> 512 bytes
 .../src/site/xdoc/search/images/calendar.jpg    |  Bin 0 -> 572 bytes
 .../site/xdoc/search/images/icon-expanded.gif   |  Bin 0 -> 389 bytes
 .../xdoc/search/images/icon-folder-small.gif    |  Bin 0 -> 631 bytes
 .../site/xdoc/search/images/icon-minimized.gif  |  Bin 0 -> 405 bytes
 .../src/site/xdoc/search/images/r00.gif         |  Bin 0 -> 577 bytes
 .../src/site/xdoc/search/images/r01.gif         |  Bin 0 -> 980 bytes
 .../src/site/xdoc/search/images/r02.gif         |  Bin 0 -> 980 bytes
 .../src/site/xdoc/search/images/r03.gif         |  Bin 0 -> 981 bytes
 .../src/site/xdoc/search/images/r04.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/r44.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/r4x.gif         |  Bin 0 -> 582 bytes
 .../src/site/xdoc/search/images/resource.gif    |  Bin 0 -> 1008 bytes
 .../site/xdoc/search/images/search-content.png  |  Bin 0 -> 883 bytes
 .../xdoc/search/images/search-resources.gif     |  Bin 0 -> 1046 bytes
 .../src/site/xdoc/search/images/search-top.png  |  Bin 0 -> 785 bytes
 .../src/site/xdoc/search/images/search.gif      |  Bin 0 -> 578 bytes
 .../images/activate_security_custom_policy.png  |  Bin 0 -> 30309 bytes
 .../images/activate_security_key_stores.png     |  Bin 0 -> 24569 bytes
 .../images/activate_security_user_groups.png    |  Bin 0 -> 19093 bytes
 .../docs/images/default_scenarios.png           |  Bin 0 -> 124356 bytes
 .../securityconfig/docs/images/kerberos_spn.png |  Bin 0 -> 23907 bytes
 .../securityconfig/docs/images/no_security.png  |  Bin 0 -> 14725 bytes
 .../docs/images/policy_from_registry.png        |  Bin 0 -> 13835 bytes
 .../site/xdoc/securityconfig/docs/userguide.xml |  205 ++
 .../xdoc/securityconfig/images/scenario1.png    |  Bin 0 -> 51504 bytes
 .../xdoc/securityconfig/images/scenario10.png   |  Bin 0 -> 85245 bytes
 .../xdoc/securityconfig/images/scenario11.png   |  Bin 0 -> 86296 bytes
 .../xdoc/securityconfig/images/scenario12.png   |  Bin 0 -> 93294 bytes
 .../xdoc/securityconfig/images/scenario13.png   |  Bin 0 -> 93878 bytes
 .../xdoc/securityconfig/images/scenario14.png   |  Bin 0 -> 103007 bytes
 .../xdoc/securityconfig/images/scenario15.png   |  Bin 0 -> 103608 bytes
 .../xdoc/securityconfig/images/scenario16.png   |  Bin 0 -> 290183 bytes
 .../xdoc/securityconfig/images/scenario2.png    |  Bin 0 -> 60285 bytes
 .../xdoc/securityconfig/images/scenario3.png    |  Bin 0 -> 71785 bytes
 .../xdoc/securityconfig/images/scenario4.png    |  Bin 0 -> 72930 bytes
 .../xdoc/securityconfig/images/scenario5.png    |  Bin 0 -> 71865 bytes
 .../xdoc/securityconfig/images/scenario6.png    |  Bin 0 -> 73596 bytes
 .../xdoc/securityconfig/images/scenario7.png    |  Bin 0 -> 84269 bytes
 .../xdoc/securityconfig/images/scenario8.png    |  Bin 0 -> 83791 bytes
 .../xdoc/securityconfig/images/scenario9.png    |  Bin 0 -> 85331 bytes
 .../site/xdoc/securityconfig/images/view.png    |  Bin 0 -> 656 bytes
 .../server-admin/docs/images/server-admin.gif   |  Bin 0 -> 21871 bytes
 .../site/xdoc/server-admin/docs/userguide.xml   |   55 +
 .../server-admin/images/graceful-restart.gif    |  Bin 0 -> 630 bytes
 .../server-admin/images/graceful-shutdown.gif   |  Bin 0 -> 623 bytes
 .../site/xdoc/server-admin/images/restart.gif   |  Bin 0 -> 631 bytes
 .../site/xdoc/server-admin/images/shutdown.gif  |  Bin 0 -> 404 bytes
 .../docs/faultyservices_userguide.xml           |   47 +
 .../service-mgt/docs/images/Engaging module.JPG |  Bin 0 -> 38855 bytes
 .../site/xdoc/service-mgt/docs/images/QoS.JPG   |  Bin 0 -> 17054 bytes
 .../docs/images/Servicegroup Dashboard.JPG      |  Bin 0 -> 23262 bytes
 .../docs/images/client operations.JPG           |  Bin 0 -> 8717 bytes
 .../docs/images/deployedservices.JPG            |  Bin 0 -> 134937 bytes
 .../service-mgt/docs/images/faulty_services.jpg |  Bin 0 -> 1973914 bytes
 .../docs/images/response time graph.JPG         |  Bin 0 -> 17155 bytes
 .../service-mgt/docs/images/service details.JPG |  Bin 0 -> 12416 bytes
 .../docs/images/service group parameters.JPG    |  Bin 0 -> 18175 bytes
 .../docs/images/service parameters.JPG          |  Bin 0 -> 21034 bytes
 .../xdoc/service-mgt/docs/images/service.JPG    |  Bin 0 -> 235858 bytes
 .../xdoc/service-mgt/docs/images/statistics.JPG |  Bin 0 -> 14542 bytes
 .../service-mgt/docs/images/try the service.JPG |  Bin 0 -> 15674 bytes
 .../xdoc/service-mgt/docs/images/wsdl2code.JPG  |  Bin 0 -> 72697 bytes
 .../site/xdoc/service-mgt/docs/userguide.xml    |  417 +++
 .../xdoc/service-mgt/images/Engaging module.jpg |  Bin 0 -> 17919 bytes
 .../src/site/xdoc/service-mgt/images/QoS.jpg    |  Bin 0 -> 18555 bytes
 .../images/Servicegroup Dashboard.jpg           |  Bin 0 -> 33154 bytes
 .../site/xdoc/service-mgt/images/activate.gif   |  Bin 0 -> 623 bytes
 .../src/site/xdoc/service-mgt/images/add.gif    |  Bin 0 -> 407 bytes
 .../src/site/xdoc/service-mgt/images/axis.gif   |  Bin 0 -> 372 bytes
 .../site/xdoc/service-mgt/images/axis2_01.gif   |  Bin 0 -> 409 bytes
 .../site/xdoc/service-mgt/images/axis2_02.gif   |  Bin 0 -> 613 bytes
 .../src/site/xdoc/service-mgt/images/bricks.gif |  Bin 0 -> 1051 bytes
 .../site/xdoc/service-mgt/images/caching.gif    |  Bin 0 -> 630 bytes
 .../service-mgt/images/client operations.jpg    |  Bin 0 -> 9520 bytes
 .../site/xdoc/service-mgt/images/create_svc.gif |  Bin 0 -> 623 bytes
 .../xdoc/service-mgt/images/data_service.gif    |  Bin 0 -> 351 bytes
 .../site/xdoc/service-mgt/images/deactivate.gif |  Bin 0 -> 606 bytes
 .../src/site/xdoc/service-mgt/images/delete.gif |  Bin 0 -> 606 bytes
 .../service-mgt/images/deployedservices.jpg     |  Bin 0 -> 42108 bytes
 .../site/xdoc/service-mgt/images/download.gif   |  Bin 0 -> 146 bytes
 .../src/site/xdoc/service-mgt/images/edit.gif   |  Bin 0 -> 353 bytes
 .../src/site/xdoc/service-mgt/images/edit2.gif  |  Bin 0 -> 1036 bytes
 .../src/site/xdoc/service-mgt/images/ejb.gif    |  Bin 0 -> 355 bytes
 .../site/xdoc/service-mgt/images/genclient.gif  |  Bin 0 -> 1086 bytes
 .../src/site/xdoc/service-mgt/images/list.gif   |  Bin 0 -> 216 bytes
 .../site/xdoc/service-mgt/images/modules.gif    |  Bin 0 -> 1051 bytes
 .../site/xdoc/service-mgt/images/operations.gif |  Bin 0 -> 623 bytes
 .../site/xdoc/service-mgt/images/policies.gif   |  Bin 0 -> 387 bytes
 .../service-mgt/images/response time graph.jpg  |  Bin 0 -> 19259 bytes
 .../src/site/xdoc/service-mgt/images/rm.gif     |  Bin 0 -> 578 bytes
 .../src/site/xdoc/service-mgt/images/search.gif |  Bin 0 -> 578 bytes
 .../site/xdoc/service-mgt/images/secured.gif    |  Bin 0 -> 558 bytes
 .../site/xdoc/service-mgt/images/security.gif   |  Bin 0 -> 1019 bytes
 .../xdoc/service-mgt/images/service details.jpg |  Bin 0 -> 14738 bytes
 .../service-mgt/images/service parameters.jpg   |  Bin 0 -> 36648 bytes
 .../site/xdoc/service-mgt/images/service.gif    |  Bin 0 -> 638 bytes
 .../site/xdoc/service-mgt/images/service.jpg    |  Bin 0 -> 235858 bytes
 .../site/xdoc/service-mgt/images/statistics.jpg |  Bin 0 -> 14542 bytes
 .../site/xdoc/service-mgt/images/throttling.gif |  Bin 0 -> 349 bytes
 .../site/xdoc/service-mgt/images/transports.gif |  Bin 0 -> 611 bytes
 .../xdoc/service-mgt/images/try the service.jpg |  Bin 0 -> 14462 bytes
 .../src/site/xdoc/service-mgt/images/tryit.gif  |  Bin 0 -> 632 bytes
 .../site/xdoc/service-mgt/images/unsecured.gif  |  Bin 0 -> 558 bytes
 .../xdoc/service-mgt/images/url-rewrite.png     |  Bin 0 -> 654 bytes
 .../src/site/xdoc/service-mgt/images/wsdl.gif   |  Bin 0 -> 612 bytes
 .../site/xdoc/service-mgt/styles/XMLSchema.dtd  |  418 +++
 .../site/xdoc/service-mgt/styles/XMLSchema.xsd  | 2328 ++++++++++++++++
 .../site/xdoc/service-mgt/styles/datatypes.dtd  |  216 ++
 .../src/site/xdoc/setting_java_home.xml         |   53 +
 .../src/site/xdoc/source-repository.xml         |  136 +
 .../src/site/xdoc/sso-acs/css/authFailures.css  |   28 +
 .../src/site/xdoc/sso-acs/images/reload.gif     |  Bin 0 -> 963 bytes
 .../xdoc/statistics/docs/images/statistics.jpg  |  Bin 0 -> 223782 bytes
 .../src/site/xdoc/statistics/docs/userguide.xml |   52 +
 .../site/xdoc/statistics/gadget/stat_gadget.xml |  158 ++
 .../xdoc/statistics/gadget/stats_gadget.xml     |   91 +
 .../site/xdoc/statistics/images/chart_bar.gif   |  Bin 0 -> 1040 bytes
 .../xdoc/stratos-auth/css/stratos-loginpage.css |   94 +
 .../images/cloud-identity-sso-config-ok.png     |  Bin 0 -> 38465 bytes
 .../images/cloud-identity-sso-config.png        |  Bin 0 -> 32929 bytes
 .../stratos-auth/images/cloud-sso-config.png    |  Bin 0 -> 29222 bytes
 .../site/xdoc/stratos-auth/images/delete.gif    |  Bin 0 -> 555 bytes
 .../site/xdoc/stratos-auth/images/import.gif    |  Bin 0 -> 1051 bytes
 .../site/xdoc/stratos-auth/images/loading.gif   |  Bin 0 -> 14367 bytes
 .../src/site/xdoc/stratos-auth/images/logo.gif  |  Bin 0 -> 17603 bytes
 .../site/xdoc/stratos-auth/images/policy.gif    |  Bin 0 -> 1017 bytes
 .../site/xdoc/stratos-auth/images/powered.gif   |  Bin 0 -> 1773 bytes
 .../site/xdoc/stratos-auth/images/register.gif  |  Bin 0 -> 4099 bytes
 .../src/site/xdoc/stratos-auth/images/sso.gif   |  Bin 0 -> 394 bytes
 .../stratos-auth/images/st-login-body-bg.gif    |  Bin 0 -> 2215 bytes
 .../stratos-auth/images/st-login-content-bg.gif |  Bin 0 -> 1060 bytes
 .../stratos-auth/images/st-login-footer-bg.gif  |  Bin 0 -> 749 bytes
 .../stratos-auth/images/st-login-header-bg.gif  |  Bin 0 -> 64503 bytes
 .../src/site/xdoc/tenant-mgt/css/tenant.css     |   62 +
 .../xdoc/tenant-mgt/docs/aboutUsagePlans.xml    |  104 +
 .../xdoc/tenant-mgt/docs/images/add-org.png     |  Bin 0 -> 49926 bytes
 .../xdoc/tenant-mgt/docs/images/add-tenant.png  |  Bin 0 -> 28704 bytes
 .../tenant-mgt/docs/images/view-tenants.png     |  Bin 0 -> 11896 bytes
 .../src/site/xdoc/tenant-mgt/docs/userguide.xml |   56 +
 .../xdoc/tenant-mgt/images/multi_tenancy.png    |  Bin 0 -> 768 bytes
 .../site/xdoc/tenant-mgt/images/services.gif    |  Bin 0 -> 604 bytes
 .../site/xdoc/tenant-mgt/images/services1.gif   |  Bin 0 -> 608 bytes
 .../xdoc/throttling/docs/images/throttle.jpg    |  Bin 0 -> 112870 bytes
 .../src/site/xdoc/throttling/docs/userguide.xml |  198 ++
 .../src/site/xdoc/throttling/images/add.gif     |  Bin 0 -> 589 bytes
 .../src/site/xdoc/throttling/images/delete.gif  |  Bin 0 -> 555 bytes
 .../src/site/xdoc/throttling/images/help.gif    |  Bin 0 -> 1109 bytes
 .../src/site/xdoc/tools/images/tools.gif        |  Bin 0 -> 573 bytes
 .../src/site/xdoc/topics/css/dsxmleditor.css    |   82 +
 .../src/site/xdoc/topics/css/topics.css         |   17 +
 .../src/site/xdoc/topics/css/tree-styles.css    |   80 +
 .../src/site/xdoc/topics/docs/userguide.xml     |  135 +
 .../site/xdoc/topics/images/Add_subtopic.png    |  Bin 0 -> 53579 bytes
 .../src/site/xdoc/topics/images/Subscribe.png   |  Bin 0 -> 54335 bytes
 .../site/xdoc/topics/images/Topic_Browser.png   |  Bin 0 -> 43590 bytes
 .../site/xdoc/topics/images/Topic_details.png   |  Bin 0 -> 67101 bytes
 .../src/site/xdoc/topics/images/add.gif         |  Bin 0 -> 873 bytes
 .../src/site/xdoc/topics/images/delete.gif      |  Bin 0 -> 555 bytes
 .../src/site/xdoc/topics/images/details.gif     |  Bin 0 -> 1046 bytes
 .../src/site/xdoc/topics/images/down.png        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/topics/images/hide.gif        |  Bin 0 -> 919 bytes
 .../site/xdoc/topics/images/icon-tree-dot.gif   |  Bin 0 -> 119 bytes
 .../site/xdoc/topics/images/icon-tree-minus.gif |  Bin 0 -> 117 bytes
 .../site/xdoc/topics/images/icon-tree-minus.jpg |  Bin 0 -> 1278 bytes
 .../xdoc/topics/images/icon-tree-plus-alone.jpg |  Bin 0 -> 1347 bytes
 .../site/xdoc/topics/images/icon-tree-plus.gif  |  Bin 0 -> 128 bytes
 .../site/xdoc/topics/images/icon-tree-plus.jpg  |  Bin 0 -> 1290 bytes
 .../src/site/xdoc/topics/images/line.png        |  Bin 0 -> 144 bytes
 .../src/site/xdoc/topics/images/minus.gif       |  Bin 0 -> 896 bytes
 .../src/site/xdoc/topics/images/nodata.gif      |  Bin 0 -> 883 bytes
 .../src/site/xdoc/topics/images/node-normal.gif |  Bin 0 -> 171 bytes
 .../site/xdoc/topics/images/node-selected.gif   |  Bin 0 -> 978 bytes
 .../src/site/xdoc/topics/images/plus.gif        |  Bin 0 -> 905 bytes
 .../src/site/xdoc/topics/images/refresh.gif     |  Bin 0 -> 929 bytes
 .../src/site/xdoc/topics/images/secure.gif      |  Bin 0 -> 943 bytes
 .../src/site/xdoc/topics/images/show.gif        |  Bin 0 -> 919 bytes
 .../src/site/xdoc/topics/images/subscribe.gif   |  Bin 0 -> 366 bytes
 .../src/site/xdoc/topics/images/treetop.jpg     |  Bin 0 -> 795 bytes
 .../src/site/xdoc/topics/images/type.gif        |  Bin 0 -> 1037 bytes
 .../src/site/xdoc/topics/images/up.png          |  Bin 0 -> 562 bytes
 .../src/site/xdoc/tracer/docs/images/tracer.jpg |  Bin 0 -> 25921 bytes
 .../site/xdoc/tracer/docs/images/tracer_on.jpg  |  Bin 0 -> 120355 bytes
 .../src/site/xdoc/tracer/docs/userguide.xml     |   78 +
 .../src/site/xdoc/tracer/images/delete.gif      |  Bin 0 -> 606 bytes
 .../src/site/xdoc/tracer/images/refresh.gif     |  Bin 0 -> 251 bytes
 .../src/site/xdoc/tracer/images/tracer.gif      |  Bin 0 -> 1058 bytes
 .../docs/images/transport-statistics-http.jpg   |  Bin 0 -> 290495 bytes
 .../docs/images/transport-statistics.jpg        |  Bin 0 -> 142918 bytes
 .../src/site/xdoc/transport/docs/userguide.xml  |   62 +
 .../xdoc/transport/images/transport-stats.gif   |  Bin 0 -> 1036 bytes
 .../xdoc/tryit/docs/images/choose_endpoints.jpg |  Bin 0 -> 19027 bytes
 .../tryit/docs/images/priority_operations.jpg   |  Bin 0 -> 11654 bytes
 .../src/site/xdoc/tryit/docs/images/results.jpg |  Bin 0 -> 27740 bytes
 .../src/site/xdoc/tryit/docs/userguide.xml      |   93 +
 .../src/site/xdoc/tryit/images/ajax-loader.gif  |  Bin 0 -> 5009 bytes
 .../src/site/xdoc/tryit/images/deprior.png      |  Bin 0 -> 1173 bytes
 .../src/site/xdoc/tryit/images/error.png        |  Bin 0 -> 813 bytes
 .../src/site/xdoc/tryit/images/info.png         |  Bin 0 -> 881 bytes
 .../src/site/xdoc/tryit/images/minus-plus.png   |  Bin 0 -> 2805 bytes
 .../src/site/xdoc/tryit/images/minus.png        |  Bin 0 -> 75 bytes
 .../src/site/xdoc/tryit/images/plus.png         |  Bin 0 -> 82 bytes
 .../src/site/xdoc/tryit/images/prior.png        |  Bin 0 -> 1173 bytes
 .../src/site/xdoc/tryit/images/tryit.gif        |  Bin 0 -> 592 bytes
 .../src/site/xdoc/tryit/images/warrning.png     |  Bin 0 -> 690 bytes
 .../src/site/xdoc/tryit/xslt/prettyprinter.xslt |   73 +
 .../src/site/xdoc/user/docs/userguide.xml       |  100 +
 .../src/site/xdoc/user/images/Thumbs.db         |  Bin 0 -> 12800 bytes
 .../src/site/xdoc/user/images/add.gif           |  Bin 0 -> 407 bytes
 .../site/xdoc/user/images/bulk-import-main.png  |  Bin 0 -> 20476 bytes
 .../src/site/xdoc/user/images/bulk-import.gif   |  Bin 0 -> 1016 bytes
 .../src/site/xdoc/user/images/bulk-import1.png  |  Bin 0 -> 17641 bytes
 .../src/site/xdoc/user/images/bulk-import2.png  |  Bin 0 -> 24853 bytes
 .../src/site/xdoc/user/images/delete.gif        |  Bin 0 -> 555 bytes
 .../src/site/xdoc/user/images/edit.gif          |  Bin 0 -> 1036 bytes
 .../site/xdoc/user/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../site/xdoc/user/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../src/site/xdoc/user/images/test.gif          |  Bin 0 -> 600 bytes
 .../src/site/xdoc/user/images/user-main.png     |  Bin 0 -> 21016 bytes
 .../src/site/xdoc/user/images/user-roles.gif    |  Bin 0 -> 1048 bytes
 .../src/site/xdoc/user/images/user-store.gif    |  Bin 0 -> 589 bytes
 .../src/site/xdoc/user/images/userManager.JPG   |  Bin 0 -> 36706 bytes
 .../src/site/xdoc/user/images/users.JPG         |  Bin 0 -> 24922 bytes
 .../src/site/xdoc/user/images/users.gif         |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/user/images/view.gif          |  Bin 0 -> 596 bytes
 .../distribution/src/site/xdoc/user_guide.xml   |  416 +++
 .../src/site/xdoc/userstore/docs/userguide.xml  |   58 +
 .../userstore/images/External-user store.JPG    |  Bin 0 -> 16722 bytes
 .../src/site/xdoc/userstore/images/add.gif      |  Bin 0 -> 407 bytes
 .../src/site/xdoc/userstore/images/delete.gif   |  Bin 0 -> 555 bytes
 .../src/site/xdoc/userstore/images/edit.gif     |  Bin 0 -> 1036 bytes
 .../xdoc/userstore/images/external-roles.gif    |  Bin 0 -> 623 bytes
 .../xdoc/userstore/images/external-users.gif    |  Bin 0 -> 586 bytes
 .../src/site/xdoc/userstore/images/keys.gif     |  Bin 0 -> 969 bytes
 .../src/site/xdoc/userstore/images/roles.JPG    |  Bin 0 -> 20207 bytes
 .../src/site/xdoc/userstore/images/test.gif     |  Bin 0 -> 600 bytes
 .../site/xdoc/userstore/images/user-chpass.png  |  Bin 0 -> 17664 bytes
 .../xdoc/userstore/images/user-role-main.png    |  Bin 0 -> 14744 bytes
 .../site/xdoc/userstore/images/user-roles.gif   |  Bin 0 -> 1048 bytes
 .../site/xdoc/userstore/images/user-store.gif   |  Bin 0 -> 617 bytes
 .../src/site/xdoc/userstore/images/users.gif    |  Bin 0 -> 1027 bytes
 .../src/site/xdoc/userstore/images/view.gif     |  Bin 0 -> 596 bytes
 .../xdoc/viewflows/docs/images/handlers.png     |  Bin 0 -> 20561 bytes
 .../site/xdoc/viewflows/docs/images/phases.png  |  Bin 0 -> 64651 bytes
 .../src/site/xdoc/viewflows/docs/userguide.xml  |   81 +
 .../extensions/core/css/handler_flow.css        |  111 +
 .../extensions/core/images/flows-view.gif       |  Bin 0 -> 573 bytes
 .../core/images/handlerChain_leftmost.gif       |  Bin 0 -> 2154 bytes
 .../images/handlerChain_leftmost_inflow.gif     |  Bin 0 -> 2443 bytes
 .../images/handlerChain_leftmost_outflow.gif    |  Bin 0 -> 2476 bytes
 .../core/images/handlerChain_rightmost.gif      |  Bin 0 -> 1716 bytes
 .../images/handlerChain_rightmost_inflow.gif    |  Bin 0 -> 1962 bytes
 .../images/handlerChain_rightmost_outflow.gif   |  Bin 0 -> 1924 bytes
 .../extensions/core/images/handler_01_BG.gif    |  Bin 0 -> 486 bytes
 .../extensions/core/images/handler_01_left.gif  |  Bin 0 -> 1362 bytes
 .../extensions/core/images/handler_01_right.gif |  Bin 0 -> 1367 bytes
 .../extensions/core/images/handler_02_BG.gif    |  Bin 0 -> 472 bytes
 .../extensions/core/images/handler_02_left.gif  |  Bin 0 -> 1342 bytes
 .../extensions/core/images/handler_02_right.gif |  Bin 0 -> 1512 bytes
 .../extensions/core/images/handler_flow.gif     |  Bin 0 -> 1309 bytes
 .../extensions/core/images/handlers.jpg         |  Bin 0 -> 17669 bytes
 .../viewflows/extensions/core/images/phases.jpg |  Bin 0 -> 37132 bytes
 .../extensions/core/images/text-view.gif        |  Bin 0 -> 158 bytes
 .../xdoc/wsdl2code/docs/images/wsdl2code.jpg    |  Bin 0 -> 103562 bytes
 .../src/site/xdoc/wsdl2code/docs/userguide.xml  |   60 +
 .../src/site/xdoc/wsdl2code/images/dump_aar.gif |  Bin 0 -> 373 bytes
 .../xdoc/wsdl_validator/docs/images/result.png  |  Bin 0 -> 13481 bytes
 .../wsdl_validator/docs/images/upload-wsdl.png  |  Bin 0 -> 8422 bytes
 .../wsdl_validator/docs/images/url-wsdl.png     |  Bin 0 -> 7162 bytes
 .../site/xdoc/wsdl_validator/docs/userguide.xml |   62 +
 .../xdoc/wsdl_validator/images/wsdlValidate.gif |  Bin 0 -> 1001 bytes
 .../1.0.1/modules/p2-profile/pom.xml            |  605 +++++
 .../src/main/resources/META-INF/product.xml     |   27 +
 .../src/main/resources/web/product/about.html   |  130 +
 .../src/main/resources/web/styles/css/main.css  |  155 ++
 .../main/resources/web/styles/images/1px.gif    |  Bin 0 -> 43 bytes
 .../web/styles/images/leftRightSlider-dark.png  |  Bin 0 -> 1103 bytes
 .../resources/web/styles/images/menu_header.png |  Bin 0 -> 227 bytes
 .../web/styles/images/right-links-bg.gif        |  Bin 0 -> 1070 bytes
 .../web/styles/images/right-logo-bg.gif         |  Bin 0 -> 3445 bytes
 .../resources/web/styles/images/scc-back.png    |  Bin 0 -> 20094 bytes
 .../web/styles/images/scc-header-repeat.png     |  Bin 0 -> 178 bytes
 .../resources/web/styles/images/scclogo.png     |  Bin 0 -> 5808 bytes
 .../src/main/resources/META-INF/product.xml     |   26 +
 .../service/src/main/resources/web/favicon.ico  |  Bin 0 -> 17542 bytes
 .../src/main/resources/web/styles/css/main.css  |  240 ++
 .../resources/web/styles/images/def-body-bg.gif |  Bin 0 -> 419 bytes
 .../web/styles/images/def-header-bg.gif         |  Bin 0 -> 17875 bytes
 .../web/styles/images/def-header-region-bg.gif  |  Bin 0 -> 22784 bytes
 .../main/resources/web/styles/images/logo.gif   |  Bin 0 -> 1815 bytes
 .../resources/web/styles/images/powered.gif     |  Bin 0 -> 1773 bytes
 .../resources/web/styles/images/right-logo.gif  |  Bin 0 -> 6102 bytes
 .../web/styles/images/t-right-logo.gif          |  Bin 0 -> 3629 bytes
 .../stratos2/cloud_controller/1.0.1/pom.xml     |  161 ++
 products/stratos2/pom.xml                       |   27 +
 .../stratos2/stratos_agent/1.0.0/INSTALL.txt    |   55 +
 .../stratos2/stratos_agent/1.0.0/LICENSE.txt    |  371 +++
 .../stratos2/stratos_agent/1.0.0/README.txt     |  147 +
 .../1.0.0/docs/xdoc/release-notes.xml           |  169 ++
 .../1.0.0/modules/distribution/pom.xml          |  594 ++++
 .../distribution/src/main/assembly/bin.xml      |  167 ++
 .../distribution/src/main/assembly/dist.xml     |   37 +
 .../distribution/src/main/assembly/docs.xml     |   32 +
 .../src/main/assembly/filter.properties         |    8 +
 .../distribution/src/main/assembly/src.xml      |   72 +
 .../distribution/src/main/bin/wso2server.bat    |  170 ++
 .../distribution/src/main/bin/wso2server.sh     |  299 ++
 .../1.0.0/modules/p2-profile/pom.xml            |  157 ++
 products/stratos2/stratos_agent/1.0.0/pom.xml   |  212 ++
 .../stratos2/stratos_agent/1.0.1/INSTALL.txt    |   52 +
 .../stratos2/stratos_agent/1.0.1/LICENSE.txt    |  250 ++
 .../stratos2/stratos_agent/1.0.1/README.txt     |  111 +
 .../1.0.1/docs/xdoc/release-notes.xml           |  169 ++
 .../1.0.1/modules/distribution/pom.xml          |  594 ++++
 .../distribution/src/conf/log4j.properties      |  165 ++
 .../distribution/src/main/assembly/bin.xml      |  183 ++
 .../distribution/src/main/assembly/dist.xml     |   37 +
 .../distribution/src/main/assembly/docs.xml     |   32 +
 .../src/main/assembly/filter.properties         |    8 +
 .../distribution/src/main/assembly/src.xml      |   72 +
 .../distribution/src/main/bin/wso2server.bat    |  170 ++
 .../distribution/src/main/bin/wso2server.sh     |  299 ++
 .../1.0.1/modules/p2-profile/pom.xml            |  176 ++
 products/stratos2/stratos_agent/1.0.1/pom.xml   |  212 ++
 products/stratos2/stratos_cli/1.0.1/LICENSE.txt |   46 +
 products/stratos2/stratos_cli/1.0.1/README.txt  |   97 +
 .../stratos_cli/1.0.1/distribution/pom.xml      |   67 +
 .../distribution/src/main/assembly/bin.xml      |   56 +
 .../1.0.1/distribution/src/main/bin/stratos.bat |   34 +
 .../1.0.1/distribution/src/main/bin/stratos.sh  |   31 +
 .../1.0.1/distribution/src/main/bin/version.txt |    1 +
 products/stratos2/stratos_cli/1.0.1/pom.xml     |   46 +
 .../stratos2/stratos_cli/distribution/pom.xml   |  111 +
 .../distribution/src/main/assembly/bin.xml      |   42 +
 .../distribution/src/main/bin/stratos.sh        |    3 +
 products/stratos2/stratos_cli/pom.xml           |   46 +
 .../1.0.0/billing-script/billing-h2.sql         |  109 +
 .../1.0.0/billing-script/billing-mysql.sql      |  120 +
 .../1.0.0/billing-script/migration.sql          |    7 +
 .../1.0.0/conf/README-STRATOS                   |   90 +
 .../stratos_controller/1.0.0/conf/axis2.xml     |  525 ++++
 .../stratos_controller/1.0.0/conf/bam.xml       |   26 +
 .../1.0.0/conf/billing-config.xml               |   67 +
 .../1.0.0/conf/cartridge-config.properties      |   33 +
 .../1.0.0/conf/cipher-text.properties           |   23 +
 .../1.0.0/conf/cloud-services-desc.xml          |  176 ++
 .../1.0.0/conf/datasources.properties           |   55 +
 .../1.0.0/conf/email-bill-generated.xml         |   38 +
 .../1.0.0/conf/email-billing-notifications.xml  |   49 +
 .../1.0.0/conf/email-new-tenant-activation.xml  |   46 +
 .../conf/email-new-tenant-registration.xml      |   46 +
 .../1.0.0/conf/email-password-reset.xml         |   42 +
 .../conf/email-payment-received-customer.xml    |   38 +
 .../1.0.0/conf/email-payment-received-wso2.xml  |   38 +
 .../1.0.0/conf/email-registration-complete.xml  |   37 +
 .../conf/email-registration-moderation.xml      |   46 +
 ...l-registration-payment-received-customer.xml |   38 +
 .../1.0.0/conf/email-registration.xml           |   45 +
 .../1.0.0/conf/email-update.xml                 |   38 +
 .../1.0.0/conf/embedded-ldap.xml                |  162 ++
 .../1.0.0/conf/event-broker.xml                 |   44 +
 .../1.0.0/conf/features-dashboard.xml           |  776 ++++++
 .../stratos_controller/1.0.0/conf/identity.xml  |  107 +
 .../stratos_controller/1.0.0/conf/jaas.conf     |   10 +
 .../1.0.0/conf/loadbalancer.conf                |   29 +
 .../1.0.0/conf/metering-config-non-manager.xml  |  103 +
 .../1.0.0/conf/multitenancy-billing-rules.drl   |   34 +
 .../1.0.0/conf/nhttp.properties                 |   39 +
 .../1.0.0/conf/passthru-http.properties         |   31 +
 .../1.0.0/conf/rule-component.conf              |    3 +
 .../1.0.0/conf/samples-desc.xml                 |   32 +
 .../1.0.0/conf/sso-idp-config.xml               |   26 +
 .../1.0.0/conf/status-monitor-config.xml        |   52 +
 .../1.0.0/conf/stratos-datasources.xml          |   70 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../1.0.0/conf/synapse.properties               |   35 +
 .../1.0.0/conf/tenant-reg-agent.xml             |   24 +
 .../1.0.0/conf/throttling-rules.drl             |  251 ++
 .../stratos_controller/1.0.0/conf/user-mgt.xml  |  238 ++
 .../stratos_controller/1.0.0/conf/zoo.cfg       |    4 +
 .../1.0.0/modules/cloud-service-mgt/pom.xml     |   96 +
 .../services/mgt/beans/CloudService.java        |   82 +
 .../CloudServiceMgtServiceComponent.java        |   73 +
 .../mgt/services/CloudManagerService.java       |  121 +
 .../manager/services/mgt/util/Constants.java    |   26 +
 .../stratos/manager/services/mgt/util/Util.java |  261 ++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |   41 +
 .../1.0.0/modules/dashboard/pom.xml             |  153 ++
 .../ui/clients/CloudManagerServiceClient.java   |  123 +
 .../manager/dashboard/ui/utils/Util.java        |   45 +
 .../src/main/resources/CloudManagerService.wsdl |  312 +++
 .../src/main/resources/META-INF/component.xml   |   35 +
 .../dashboard/ui/i18n/JSResources.properties    |    3 +
 .../dashboard/ui/i18n/Resources.properties      |    3 +
 .../cloud_services_configuration.jsp            |  203 ++
 .../cloud_services_save_ajaxprocessor.jsp       |   34 +
 .../web/tenant-dashboard/css/dashboard.css      |  231 ++
 .../tenant-dashboard/docs/images/dashboard.png  |  Bin 0 -> 139674 bytes
 .../web/tenant-dashboard/docs/userguide.html    |  101 +
 .../images/WSO2-Cloud-Gateway-logo.gif          |  Bin 0 -> 2506 bytes
 .../images/WSO2-Storage-Server-logo.gif         |  Bin 0 -> 2490 bytes
 .../WSO2-Stratos-Application-Server-logo.gif    |  Bin 0 -> 1473 bytes
 ...2-Stratos-Business-Activity-Monitor-logo.gif |  Bin 0 -> 1690 bytes
 ...SO2-Stratos-Business-Process-Server-logo.gif |  Bin 0 -> 1606 bytes
 .../WSO2-Stratos-Business-Rules-Server-logo.gif |  Bin 0 -> 1596 bytes
 ...WSO2-Stratos-Cloud-Services-Gateway-logo.gif |  Bin 0 -> 2030 bytes
 ...tos-Complex-Event-Processing-Server-logo.gif |  Bin 0 -> 1998 bytes
 .../WSO2-Stratos-Data-Services-Server-logo.gif  |  Bin 0 -> 1528 bytes
 ...WSO2-Stratos-Enterprise-Service-Bus-logo.gif |  Bin 0 -> 1598 bytes
 .../images/WSO2-Stratos-Gadget-Server-logo.gif  |  Bin 0 -> 1368 bytes
 .../images/WSO2-Stratos-Governance-logo.gif     |  Bin 0 -> 1525 bytes
 .../images/WSO2-Stratos-Identity-logo.gif       |  Bin 0 -> 1398 bytes
 .../images/WSO2-Stratos-Mashup-Server-logo.gif  |  Bin 0 -> 1440 bytes
 .../images/WSO2-Stratos-Message-Broker-logo.gif |  Bin 0 -> 1603 bytes
 .../images/WSO2-Tasks-Server-logo.gif           |  Bin 0 -> 2350 bytes
 .../web/tenant-dashboard/images/aas-top.gif     |  Bin 0 -> 4659 bytes
 .../tenant-dashboard/images/activate-button.gif |  Bin 0 -> 2601 bytes
 .../tenant-dashboard/images/appserver-logo.gif  |  Bin 0 -> 1473 bytes
 .../web/tenant-dashboard/images/bam-logo.gif    |  Bin 0 -> 1690 bytes
 .../web/tenant-dashboard/images/bps-logo.gif    |  Bin 0 -> 1606 bytes
 .../web/tenant-dashboard/images/brs-logo.gif    |  Bin 0 -> 1596 bytes
 .../web/tenant-dashboard/images/cep_logo.gif    |  Bin 0 -> 1998 bytes
 .../web/tenant-dashboard/images/csg-logo.gif    |  Bin 0 -> 2030 bytes
 .../images/deactivate-button.gif                |  Bin 0 -> 2448 bytes
 .../web/tenant-dashboard/images/ds-logo.gif     |  Bin 0 -> 1528 bytes
 .../web/tenant-dashboard/images/esb-logo.gif    |  Bin 0 -> 1598 bytes
 .../web/tenant-dashboard/images/gadget-logo.gif |  Bin 0 -> 1368 bytes
 .../web/tenant-dashboard/images/go-button.gif   |  Bin 0 -> 2165 bytes
 .../tenant-dashboard/images/governance-logo.gif |  Bin 0 -> 1525 bytes
 .../tenant-dashboard/images/identity-logo.gif   |  Bin 0 -> 1398 bytes
 .../images/inactive-go-button.gif               |  Bin 0 -> 2135 bytes
 .../web/tenant-dashboard/images/mashup-logo.gif |  Bin 0 -> 1440 bytes
 .../web/tenant-dashboard/images/mb_logo.gif     |  Bin 0 -> 1603 bytes
 .../images/service-configuration.gif            |  Bin 0 -> 389 bytes
 .../resources/web/tenant-dashboard/index.jsp    |  243 ++
 .../web/tenant-dashboard/js/configurations.js   |  381 +++
 .../web/tenant-dashboard/js/dashboard.js        |   12 +
 .../1.0.0/modules/distribution/INSTALL.txt      |   61 +
 .../1.0.0/modules/distribution/LICENSE.txt      |  455 ++++
 .../1.0.0/modules/distribution/README.txt       |  144 +
 .../modules/distribution/lib/home/faq.html      |  392 +++
 .../distribution/lib/home/images/bottom.gif     |  Bin 0 -> 523 bytes
 .../distribution/lib/home/images/bullet-01.gif  |  Bin 0 -> 159 bytes
 .../distribution/lib/home/images/content-bg.gif |  Bin 0 -> 233 bytes
 .../distribution/lib/home/images/favicon.ico    |  Bin 0 -> 17542 bytes
 .../lib/home/images/feature-01-icon.gif         |  Bin 0 -> 2825 bytes
 .../lib/home/images/feature-02-icon.gif         |  Bin 0 -> 3361 bytes
 .../lib/home/images/feature-03-icon.gif         |  Bin 0 -> 3285 bytes
 .../lib/home/images/feature-middle-bg.gif       |  Bin 0 -> 1139 bytes
 .../distribution/lib/home/images/intro-bg.gif   |  Bin 0 -> 3964 bytes
 .../distribution/lib/home/images/intro-text.gif |  Bin 0 -> 4082 bytes
 .../distribution/lib/home/images/left-bg.gif    |  Bin 0 -> 1135 bytes
 .../distribution/lib/home/images/logo.gif       |  Bin 0 -> 11127 bytes
 .../lib/home/images/powered-logo.gif            |  Bin 0 -> 1280 bytes
 .../distribution/lib/home/images/register.gif   |  Bin 0 -> 6946 bytes
 .../distribution/lib/home/images/sign-in.gif    |  Bin 0 -> 3150 bytes
 .../lib/home/images/stratos-products-new.jpg    |  Bin 0 -> 25720 bytes
 .../distribution/lib/home/images/title-bg.gif   |  Bin 0 -> 1182 bytes
 .../distribution/lib/home/images/top.gif        |  Bin 0 -> 16149 bytes
 .../distribution/lib/home/images/webinar.png    |  Bin 0 -> 12318 bytes
 .../lib/home/images/white-paper.png             |  Bin 0 -> 15148 bytes
 .../modules/distribution/lib/home/index.html    |  119 +
 .../lib/home/js/jquery-1.5.1.min.js             |   16 +
 .../lib/home/js/jquery.orbit-1.2.3.min.js       |   17 +
 .../distribution/lib/home/js/orbit-1.2.3.css    |  202 ++
 .../lib/home/js/orbit/left-arrow.png            |  Bin 0 -> 860 bytes
 .../distribution/lib/home/js/orbit/loading.gif  |  Bin 0 -> 2608 bytes
 .../lib/home/js/orbit/mask-black.png            |  Bin 0 -> 705 bytes
 .../lib/home/js/orbit/right-arrow.png           |  Bin 0 -> 825 bytes
 .../lib/home/js/orbit/rotator-black.png         |  Bin 0 -> 733 bytes
 .../lib/home/js/orbit/timer-black.png           |  Bin 0 -> 705 bytes
 .../modules/distribution/lib/home/style.css     |  160 ++
 .../1.0.0/modules/distribution/pom.xml          |  744 +++++
 .../distribution/qpid-resources/etc/config.xml  |  103 +
 .../qpid-resources/etc/jmxremote.access         |   23 +
 .../qpid-resources/etc/virtualhosts.xml         |   64 +
 .../distribution/qpid-resources/qpid.xml        |   22 +
 .../modules/distribution/release-notes.html     |  132 +
 .../resources/dbscripts/metering_h2.sql         |  114 +
 .../resources/dbscripts/metering_mysql.sql      |  120 +
 .../resources/dbscripts/wso2_rss.sql            |   81 +
 .../modules/distribution/src/assembly/bin.xml   |  555 ++++
 .../modules/distribution/src/assembly/dist.xml  |   44 +
 .../distribution/src/assembly/filter.properties |    7 +
 .../distribution/src/bin/add_entry_zone_file.sh |   50 +
 .../src/bin/git-folder-structure.sh             |   47 +
 .../distribution/src/bin/manage-git-repo.sh     |  118 +
 .../src/bin/remove_entry_zone_file.sh           |   55 +
 .../distribution/src/bin/set-mysql-password.sh  |   45 +
 .../distribution/src/bin/update-instance.sh     |   34 +
 .../modules/distribution/src/bin/wso2server.bat |  170 ++
 .../modules/distribution/src/bin/wso2server.sh  |  298 ++
 .../WebContent/META-INF/MANIFEST.MF             |    3 +
 .../WebContent/WEB-INF/web.xml                  |    7 +
 .../WebContent/dashboards/as.html               |   69 +
 .../WebContent/dashboards/bam.html              |   88 +
 .../WebContent/dashboards/bps.html              |   51 +
 .../WebContent/dashboards/brs.html              |   22 +
 .../WebContent/dashboards/cep.html              |   82 +
 .../WebContent/dashboards/csg.html              |   11 +
 .../dashboards/css/features-dashboard.css       |   55 +
 .../WebContent/dashboards/dss.html              |   75 +
 .../WebContent/dashboards/esb.html              |   70 +
 .../WebContent/dashboards/greg.html             |   94 +
 .../WebContent/dashboards/gs.html               |   90 +
 .../WebContent/dashboards/images/black.png      |  Bin 0 -> 7338 bytes
 .../dashboards/images/configure_db.png          |  Bin 0 -> 43279 bytes
 .../dashboards/images/tenant_isolation.png      |  Bin 0 -> 67219 bytes
 .../images/usage_metering_and_throttling.jpg    |  Bin 0 -> 44100 bytes
 .../WebContent/dashboards/is.html               |   98 +
 .../WebContent/dashboards/manager.html          |   68 +
 .../WebContent/dashboards/mb.html               |   81 +
 .../WebContent/dashboards/ms.html               |   81 +
 .../WebContent/dashboards/server.jsp            |  151 ++
 .../css/features-dashboard-new.css              |  155 ++
 .../WebContent/tenant-dashboard/css/ie7.css     |    8 +
 .../tenant-dashboard/images/arrow-blue.png      |  Bin 0 -> 815 bytes
 .../tenant-dashboard/images/arrow-white.png     |  Bin 0 -> 846 bytes
 .../WebContent/tenant-dashboard/images/back.jpg |  Bin 0 -> 1496 bytes
 .../tenant-dashboard/images/boxes.png           |  Bin 0 -> 645 bytes
 .../images/dashboard-back-repeat.png            |  Bin 0 -> 696 bytes
 .../tenant-dashboard/images/workAreaBack.png    |  Bin 0 -> 760 bytes
 .../WebContent/tenant-dashboard/index.html      |  173 ++
 .../WebContent/tenant-dashboard/index.jsp       |  205 ++
 .../tenant-dashboard/js/jquery-1.7.1.min.js     |    4 +
 .../tenant-dashboard/js/jquery.masonry.min.js   |   10 +
 .../js/jquery/jquery-1.5.1.min.js               |   16 +
 .../js/jquery/jquery.ui.core.js                 |    1 +
 .../js/jquery/jquery.ui.core.min.js             |   17 +
 .../js/jquery/jquery.ui.tabs.min.js             |   35 +
 .../js/jquery/jquery.ui.widget.min.js           |   15 +
 .../js/jquery/jquery.validate.js                | 1166 ++++++++
 .../ui-bg_diagonals-thick_18_b81900_40x40.png   |  Bin 0 -> 260 bytes
 .../ui-bg_diagonals-thick_20_666666_40x40.png   |  Bin 0 -> 251 bytes
 .../images/ui-bg_flat_10_000000_40x100.png      |  Bin 0 -> 178 bytes
 .../images/ui-bg_glass_100_f6f6f6_1x400.png     |  Bin 0 -> 104 bytes
 .../images/ui-bg_glass_100_fdf5ce_1x400.png     |  Bin 0 -> 125 bytes
 .../images/ui-bg_glass_65_ffffff_1x400.png      |  Bin 0 -> 105 bytes
 .../ui-bg_gloss-wave_35_f6a828_500x100.png      |  Bin 0 -> 3762 bytes
 .../ui-bg_highlight-soft_100_eeeeee_1x100.png   |  Bin 0 -> 90 bytes
 .../ui-bg_highlight-soft_75_ffe45c_1x100.png    |  Bin 0 -> 129 bytes
 .../images/ui-icons_222222_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_228ef1_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_ef8c08_256x240.png          |  Bin 0 -> 5355 bytes
 .../images/ui-icons_ffd27a_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_ffffff_256x240.png          |  Bin 0 -> 4369 bytes
 .../ui-lightness/jquery-ui-1.8.14.custom.css    |  568 ++++
 .../themes/ui-lightness/jquery.ui.accordion.css |   19 +
 .../themes/ui-lightness/jquery.ui.all.css       |   11 +
 .../ui-lightness/jquery.ui.autocomplete.css     |   53 +
 .../themes/ui-lightness/jquery.ui.base.css      |   11 +
 .../themes/ui-lightness/jquery.ui.button.css    |   38 +
 .../themes/ui-lightness/jquery.ui.core.css      |   41 +
 .../ui-lightness/jquery.ui.datepicker.css       |   68 +
 .../themes/ui-lightness/jquery.ui.dialog.css    |   21 +
 .../ui-lightness/jquery.ui.progressbar.css      |   11 +
 .../themes/ui-lightness/jquery.ui.resizable.css |   20 +
 .../ui-lightness/jquery.ui.selectable.css       |   10 +
 .../themes/ui-lightness/jquery.ui.slider.css    |   24 +
 .../themes/ui-lightness/jquery.ui.tabs.css      |   18 +
 .../themes/ui-lightness/jquery.ui.theme.css     |  249 ++
 .../features-dashboard/features-dashboard.xml   |  762 ++++++
 .../1.0.0/modules/features-dashboard/pom.xml    |  139 +
 .../manager/feature/dashbord/ui/beans/Data.java |   43 +
 .../manager/feature/dashbord/ui/beans/Link.java |   23 +
 .../feature/dashbord/ui/beans/Service.java      |   54 +
 .../feature/dashbord/ui/beans/Story.java        |   44 +
 .../feature/dashbord/ui/utils/Utils.java        |  159 ++
 .../1.0.0/modules/features/pom.xml              |   46 +
 .../features/service/etc/feature.properties     |  242 ++
 .../service/org.wso2.stratos2.feature/pom.xml   |   83 +
 .../org.wso2.stratos2.server.feature/pom.xml    |  237 ++
 .../org.wso2.stratos2.ui.feature/pom.xml        |  218 ++
 .../1.0.0/modules/features/service/pom.xml      |   49 +
 .../1.0.0/modules/integration/pom.xml           |  146 +
 .../integration/tests/LoginLogoutTestCase.java  |   48 +
 .../tests/SecurityVerificationTestCase.java     |   26 +
 .../tests/StratosManagerTestServerManager.java  |   54 +
 .../integration/tests/TenantMgtTestCase.java    |   91 +
 .../src/test/resources/instrumentation.txt      |    2 +
 .../src/test/resources/keys/wso2carbon.jks      |  Bin 0 -> 33260 bytes
 .../integration/src/test/resources/testng.xml   |   17 +
 .../1.0.0/modules/login/pom.xml                 |  140 +
 .../src/main/resources/META-INF/component.xml   |   20 +
 .../login/src/main/resources/TenantService.wsdl |  576 ++++
 .../web/tenant-login/css/loginpage.css          |  268 ++
 .../resources/web/tenant-login/css/tenant.css   |   62 +
 .../docs/images/sign-in-no-domain.png           |  Bin 0 -> 10682 bytes
 .../docs/images/sign-in-with-domain.png         |  Bin 0 -> 8233 bytes
 .../web/tenant-login/docs/userguide.html        |  113 +
 .../domain_rename_checker_ajaxprocessor.jsp     |   46 +
 .../web/tenant-login/images/body-bg.gif         |  Bin 0 -> 923 bytes
 .../web/tenant-login/images/feature-01-icon.gif |  Bin 0 -> 2825 bytes
 .../web/tenant-login/images/feature-02-icon.gif |  Bin 0 -> 3361 bytes
 .../web/tenant-login/images/feature-03-icon.gif |  Bin 0 -> 3285 bytes
 .../tenant-login/images/google-apps-login.gif   |  Bin 0 -> 4189 bytes
 .../web/tenant-login/images/link-icon.gif       |  Bin 0 -> 118 bytes
 .../web/tenant-login/images/login-bg.gif        |  Bin 0 -> 56670 bytes
 .../resources/web/tenant-login/images/logo.gif  |  Bin 0 -> 17603 bytes
 .../tenant-login/images/paas-login-1pix-1.gif   |  Bin 0 -> 43 bytes
 .../web/tenant-login/images/paas-login-1pix.gif |  Bin 0 -> 43 bytes
 .../web/tenant-login/images/powered.gif         |  Bin 0 -> 1280 bytes
 .../tenant-login/images/reg-button-hover.gif    |  Bin 0 -> 3824 bytes
 .../web/tenant-login/images/reg-button.gif      |  Bin 0 -> 3852 bytes
 .../web/tenant-login/images/register.gif        |  Bin 0 -> 4099 bytes
 .../tenant-login/images/st-login-body-bg.gif    |  Bin 0 -> 2215 bytes
 .../tenant-login/images/st-login-content-bg.gif |  Bin 0 -> 1060 bytes
 .../tenant-login/images/st-login-footer-bg.gif  |  Bin 0 -> 749 bytes
 .../tenant-login/images/st-login-header-bg.gif  |  Bin 0 -> 64503 bytes
 .../web/tenant-login/images/t-right-logo.gif    |  Bin 0 -> 2445 bytes
 .../main/resources/web/tenant-login/js/login.js |   27 +
 .../web/tenant-login/login_ajaxprocessor.jsp    |  345 +++
 .../web/tenant-login/terms/policy.html          |   71 +
 .../web/tenant-login/terms/support.html         |   38 +
 .../resources/web/tenant-login/terms/terms.html |   73 +
 .../1.0.0/modules/p2-profile-gen/pom.xml        |  451 +++
 .../1.0.0/modules/s2-gitblit-plugin/lib/LICENSE |  201 ++
 .../1.0.0/modules/s2-gitblit-plugin/lib/NOTICE  |  217 ++
 .../lib/gitblit-manager-1.0.0.jar               |  Bin 0 -> 561475 bytes
 .../1.0.0/modules/s2-gitblit-plugin/pom.xml     |  188 ++
 .../s2/gitblit/service/GitAuthService.java      |   80 +
 .../src/main/resources/AuthenticationAdmin.wsdl | 1370 ++++++++++
 .../1.0.0/modules/styles/pom.xml                |   46 +
 .../1.0.0/modules/styles/service/pom.xml        |  142 +
 .../src/main/resources/META-INF/product.xml     |   26 +
 .../service/src/main/resources/web/favicon.ico  |  Bin 0 -> 17542 bytes
 .../src/main/resources/web/styles/css/main.css  |  240 ++
 .../resources/web/styles/images/def-body-bg.gif |  Bin 0 -> 419 bytes
 .../web/styles/images/def-header-bg.gif         |  Bin 0 -> 17875 bytes
 .../web/styles/images/def-header-region-bg.gif  |  Bin 0 -> 22784 bytes
 .../main/resources/web/styles/images/logo.gif   |  Bin 0 -> 1815 bytes
 .../resources/web/styles/images/powered.gif     |  Bin 0 -> 1773 bytes
 .../resources/web/styles/images/right-logo.gif  |  Bin 0 -> 6102 bytes
 .../web/styles/images/t-right-logo.gif          |  Bin 0 -> 3629 bytes
 .../stratos2/stratos_controller/1.0.0/pom.xml   |  418 +++
 .../resources/allthemes/Dark/admin/logo.gif     |  Bin 0 -> 1551 bytes
 .../resources/allthemes/Dark/admin/main.css     |  232 ++
 .../allthemes/Dark/admin/powered-stratos.gif    |  Bin 0 -> 1515 bytes
 .../allthemes/Dark/admin/right-logo.gif         |  Bin 0 -> 2325 bytes
 .../allthemes/Dark/admin/theme-header-bg.gif    |  Bin 0 -> 4245 bytes
 .../Dark/admin/theme-header-region-bg.gif       |  Bin 0 -> 793 bytes
 .../allthemes/Dark/admin/theme-menu-header.gif  |  Bin 0 -> 261 bytes
 .../Dark/admin/theme-menu-panel-l-bg.gif        |  Bin 0 -> 312 bytes
 .../Dark/admin/theme-menu-table-bg.gif          |  Bin 0 -> 5671 bytes
 .../Dark/admin/theme-right-links-bg.gif         |  Bin 0 -> 1005 bytes
 .../1.0.0/resources/allthemes/Dark/thumb.png    |  Bin 0 -> 19546 bytes
 .../allthemes/Default/admin/def-body-bg.gif     |  Bin 0 -> 419 bytes
 .../allthemes/Default/admin/def-header-bg.gif   |  Bin 0 -> 17875 bytes
 .../Default/admin/def-header-region-bg.gif      |  Bin 0 -> 22784 bytes
 .../resources/allthemes/Default/admin/logo.gif  |  Bin 0 -> 1815 bytes
 .../resources/allthemes/Default/admin/main.css  |  229 ++
 .../allthemes/Default/admin/powered-stratos.gif |  Bin 0 -> 1515 bytes
 .../allthemes/Default/admin/right-logo.gif      |  Bin 0 -> 3629 bytes
 .../1.0.0/resources/allthemes/Default/thumb.png |  Bin 0 -> 24432 bytes
 .../resources/allthemes/Light/admin/logo.gif    |  Bin 0 -> 1551 bytes
 .../resources/allthemes/Light/admin/main.css    |  229 ++
 .../allthemes/Light/admin/menu_header.gif       |  Bin 0 -> 243 bytes
 .../allthemes/Light/admin/powered-stratos.gif   |  Bin 0 -> 1515 bytes
 .../allthemes/Light/admin/right-links-bg.gif    |  Bin 0 -> 1191 bytes
 .../allthemes/Light/admin/right-logo.gif        |  Bin 0 -> 2325 bytes
 .../allthemes/Light/admin/theme-header-bg.gif   |  Bin 0 -> 3792 bytes
 .../Light/admin/theme-header-region-b-bg.gif    |  Bin 0 -> 121 bytes
 .../Light/admin/theme-header-region-bg.gif      |  Bin 0 -> 534 bytes
 .../Light/admin/theme-menu-panel-l-bg.gif       |  Bin 0 -> 772 bytes
 .../Light/admin/theme-menu-table-bg.gif         |  Bin 0 -> 5991 bytes
 .../1.0.0/resources/allthemes/Light/thumb.png   |  Bin 0 -> 18102 bytes
 .../cloud-services-icons/appserver.gif          |  Bin 0 -> 2086 bytes
 .../resources/cloud-services-icons/bam.gif      |  Bin 0 -> 1773 bytes
 .../resources/cloud-services-icons/bps.gif      |  Bin 0 -> 1531 bytes
 .../resources/cloud-services-icons/brs-old.gif  |  Bin 0 -> 1772 bytes
 .../resources/cloud-services-icons/brs.gif      |  Bin 0 -> 2170 bytes
 .../resources/cloud-services-icons/cep.png      |  Bin 0 -> 3218 bytes
 .../1.0.0/resources/cloud-services-icons/cg.gif |  Bin 0 -> 2385 bytes
 .../cloud-services-icons/csg-inactive.gif       |  Bin 0 -> 3188 bytes
 .../resources/cloud-services-icons/csg.gif      |  Bin 0 -> 3176 bytes
 .../1.0.0/resources/cloud-services-icons/ds.gif |  Bin 0 -> 2012 bytes
 .../resources/cloud-services-icons/esb.gif      |  Bin 0 -> 1787 bytes
 .../resources/cloud-services-icons/gadget.gif   |  Bin 0 -> 2242 bytes
 .../cloud-services-icons/governance.gif         |  Bin 0 -> 1977 bytes
 .../resources/cloud-services-icons/identity.gif |  Bin 0 -> 1936 bytes
 .../cloud-services-icons/inactive-appserver.gif |  Bin 0 -> 1957 bytes
 .../cloud-services-icons/inactive-bam.gif       |  Bin 0 -> 1647 bytes
 .../cloud-services-icons/inactive-brs.gif       |  Bin 0 -> 1874 bytes
 .../cloud-services-icons/inactive-cep.png       |  Bin 0 -> 2959 bytes
 .../cloud-services-icons/inactive-esb.gif       |  Bin 0 -> 1656 bytes
 .../cloud-services-icons/inactive-gadget.gif    |  Bin 0 -> 2087 bytes
 .../inactive-governance.gif                     |  Bin 0 -> 1850 bytes
 .../cloud-services-icons/inactive-identity.gif  |  Bin 0 -> 1794 bytes
 .../cloud-services-icons/inactive-mashup.gif    |  Bin 0 -> 1772 bytes
 .../cloud-services-icons/inactive-mb.png        |  Bin 0 -> 2746 bytes
 .../resources/cloud-services-icons/mashup.gif   |  Bin 0 -> 1850 bytes
 .../1.0.0/resources/cloud-services-icons/mb.png |  Bin 0 -> 3139 bytes
 .../resources/cloud-services-icons/pom.xml      |   71 +
 .../1.0.0/resources/cloud-services-icons/ss.gif |  Bin 0 -> 2432 bytes
 .../1.0.0/resources/cloud-services-icons/ts.gif |  Bin 0 -> 2475 bytes
 .../powerded-by-logos/appserver-logo.gif        |  Bin 0 -> 1473 bytes
 .../resources/powerded-by-logos/bam-logo.gif    |  Bin 0 -> 1690 bytes
 .../resources/powerded-by-logos/bps-logo.gif    |  Bin 0 -> 1606 bytes
 .../resources/powerded-by-logos/brs-logo.gif    |  Bin 0 -> 1596 bytes
 .../resources/powerded-by-logos/csg-logo.gif    |  Bin 0 -> 2030 bytes
 .../resources/powerded-by-logos/ds-logo.gif     |  Bin 0 -> 1528 bytes
 .../resources/powerded-by-logos/esb-logo.gif    |  Bin 0 -> 1598 bytes
 .../resources/powerded-by-logos/gadget-logo.gif |  Bin 0 -> 1368 bytes
 .../powerded-by-logos/governance-logo.gif       |  Bin 0 -> 1525 bytes
 .../powerded-by-logos/identity-logo.gif         |  Bin 0 -> 1398 bytes
 .../resources/powerded-by-logos/mashup-logo.gif |  Bin 0 -> 1440 bytes
 .../1.0.1/billing-script/billing-h2.sql         |  109 +
 .../1.0.1/billing-script/billing-mysql.sql      |  120 +
 .../1.0.1/billing-script/metering_h2.sql        |  114 +
 .../1.0.1/billing-script/metering_mysql.sql     |  149 +
 .../1.0.1/billing-script/migration.sql          |    7 +
 .../1.0.1/billing-script/s2_h2.sql              |   96 +
 .../1.0.1/billing-script/wso2_rss.sql           |   81 +
 .../1.0.1/conf/README-STRATOS                   |   90 +
 .../stratos_controller/1.0.1/conf/axis2.xml     |  525 ++++
 .../stratos_controller/1.0.1/conf/bam.xml       |   26 +
 .../1.0.1/conf/billing-config.xml               |   67 +
 .../1.0.1/conf/cipher-text.properties           |   23 +
 .../1.0.1/conf/cloud-services-desc.xml          |  176 ++
 .../1.0.1/conf/datasources.properties           |   55 +
 .../1.0.1/conf/email-bill-generated.xml         |   38 +
 .../1.0.1/conf/email-billing-notifications.xml  |   49 +
 .../1.0.1/conf/email-new-tenant-activation.xml  |   46 +
 .../conf/email-new-tenant-registration.xml      |   46 +
 .../1.0.1/conf/email-password-reset.xml         |   42 +
 .../conf/email-payment-received-customer.xml    |   38 +
 .../1.0.1/conf/email-payment-received-wso2.xml  |   38 +
 .../1.0.1/conf/email-registration-complete.xml  |   37 +
 .../conf/email-registration-moderation.xml      |   46 +
 ...l-registration-payment-received-customer.xml |   38 +
 .../1.0.1/conf/email-registration.xml           |   45 +
 .../1.0.1/conf/email-update.xml                 |   38 +
 .../1.0.1/conf/embedded-ldap.xml                |  162 ++
 .../1.0.1/conf/event-broker.xml                 |   44 +
 .../1.0.1/conf/features-dashboard.xml           |  807 ++++++
 .../stratos_controller/1.0.1/conf/identity.xml  |  107 +
 .../stratos_controller/1.0.1/conf/jaas.conf     |   10 +
 .../1.0.1/conf/loadbalancer.conf                |   29 +
 .../1.0.1/conf/metering-config-non-manager.xml  |  103 +
 .../1.0.1/conf/multitenancy-billing-rules.drl   |   34 +
 .../1.0.1/conf/nhttp.properties                 |   39 +
 .../1.0.1/conf/passthru-http.properties         |   31 +
 .../1.0.1/conf/rule-component.conf              |    3 +
 .../1.0.1/conf/samples-desc.xml                 |   32 +
 .../1.0.1/conf/sso-idp-config.xml               |   26 +
 .../1.0.1/conf/status-monitor-config.xml        |   52 +
 .../1.0.1/conf/stratos-datasources.xml          |   50 +
 .../conf/synapse-configs/default/registry.xml   |   25 +
 .../default/sequences/errorHandler.xml          |   30 +
 .../synapse-configs/default/sequences/fault.xml |   75 +
 .../synapse-configs/default/sequences/main.xml  |  109 +
 .../conf/synapse-configs/default/synapse.xml    |   24 +
 .../1.0.1/conf/synapse.properties               |   35 +
 .../1.0.1/conf/tenant-reg-agent.xml             |   24 +
 .../1.0.1/conf/throttling-rules.drl             |  251 ++
 .../stratos_controller/1.0.1/conf/user-mgt.xml  |  238 ++
 .../stratos_controller/1.0.1/conf/zoo.cfg       |    4 +
 .../1.0.1/modules/cloud-service-mgt/pom.xml     |   96 +
 .../services/mgt/beans/CloudService.java        |   82 +
 .../CloudServiceMgtServiceComponent.java        |   73 +
 .../mgt/services/CloudManagerService.java       |  121 +
 .../manager/services/mgt/util/Constants.java    |   26 +
 .../stratos/manager/services/mgt/util/Util.java |  261 ++
 .../src/main/resources/META-INF/component.xml   |   29 +
 .../src/main/resources/META-INF/services.xml    |   41 +
 .../1.0.1/modules/dashboard/pom.xml             |  153 ++
 .../ui/clients/CloudManagerServiceClient.java   |  123 +
 .../manager/dashboard/ui/utils/Util.java        |   45 +
 .../src/main/resources/CloudManagerService.wsdl |  312 +++
 .../src/main/resources/META-INF/component.xml   |   35 +
 .../dashboard/ui/i18n/JSResources.properties    |    3 +
 .../dashboard/ui/i18n/Resources.properties      |    3 +
 .../cloud_services_configuration.jsp            |  203 ++
 .../cloud_services_save_ajaxprocessor.jsp       |   34 +
 .../web/tenant-dashboard/css/dashboard.css      |  231 ++
 .../tenant-dashboard/docs/images/dashboard.png  |  Bin 0 -> 139674 bytes
 .../tenant-dashboard/docs/userguide-old.html    |  101 +
 .../web/tenant-dashboard/docs/userguide.html    |   37 +
 .../images/WSO2-Cloud-Gateway-logo.gif          |  Bin 0 -> 2506 bytes
 .../images/WSO2-Storage-Server-logo.gif         |  Bin 0 -> 2490 bytes
 .../WSO2-Stratos-Application-Server-logo.gif    |  Bin 0 -> 1473 bytes
 ...2-Stratos-Business-Activity-Monitor-logo.gif |  Bin 0 -> 1690 bytes
 ...SO2-Stratos-Business-Process-Server-logo.gif |  Bin 0 -> 1606 bytes
 .../WSO2-Stratos-Business-Rules-Server-logo.gif |  Bin 0 -> 1596 bytes
 ...WSO2-Stratos-Cloud-Services-Gateway-logo.gif |  Bin 0 -> 2030 bytes
 ...tos-Complex-Event-Processing-Server-logo.gif |  Bin 0 -> 1998 bytes
 .../WSO2-Stratos-Data-Services-Server-logo.gif  |  Bin 0 -> 1528 bytes
 ...WSO2-Stratos-Enterprise-Service-Bus-logo.gif |  Bin 0 -> 1598 bytes
 .../images/WSO2-Stratos-Gadget-Server-logo.gif  |  Bin 0 -> 1368 bytes
 .../images/WSO2-Stratos-Governance-logo.gif     |  Bin 0 -> 1525 bytes
 .../images/WSO2-Stratos-Identity-logo.gif       |  Bin 0 -> 1398 bytes
 .../images/WSO2-Stratos-Mashup-Server-logo.gif  |  Bin 0 -> 1440 bytes
 .../images/WSO2-Stratos-Message-Broker-logo.gif |  Bin 0 -> 1603 bytes
 .../images/WSO2-Tasks-Server-logo.gif           |  Bin 0 -> 2350 bytes
 .../web/tenant-dashboard/images/aas-top.gif     |  Bin 0 -> 4659 bytes
 .../tenant-dashboard/images/activate-button.gif |  Bin 0 -> 2601 bytes
 .../tenant-dashboard/images/appserver-logo.gif  |  Bin 0 -> 1473 bytes
 .../web/tenant-dashboard/images/bam-logo.gif    |  Bin 0 -> 1690 bytes
 .../web/tenant-dashboard/images/bps-logo.gif    |  Bin 0 -> 1606 bytes
 .../web/tenant-dashboard/images/brs-logo.gif    |  Bin 0 -> 1596 bytes
 .../web/tenant-dashboard/images/cep_logo.gif    |  Bin 0 -> 1998 bytes
 .../web/tenant-dashboard/images/csg-logo.gif    |  Bin 0 -> 2030 bytes
 .../images/deactivate-button.gif                |  Bin 0 -> 2448 bytes
 .../web/tenant-dashboard/images/ds-logo.gif     |  Bin 0 -> 1528 bytes
 .../web/tenant-dashboard/images/esb-logo.gif    |  Bin 0 -> 1598 bytes
 .../web/tenant-dashboard/images/gadget-logo.gif |  Bin 0 -> 1368 bytes
 .../web/tenant-dashboard/images/go-button.gif   |  Bin 0 -> 2165 bytes
 .../tenant-dashboard/images/governance-logo.gif |  Bin 0 -> 1525 bytes
 .../tenant-dashboard/images/identity-logo.gif   |  Bin 0 -> 1398 bytes
 .../images/inactive-go-button.gif               |  Bin 0 -> 2135 bytes
 .../web/tenant-dashboard/images/mashup-logo.gif |  Bin 0 -> 1440 bytes
 .../web/tenant-dashboard/images/mb_logo.gif     |  Bin 0 -> 1603 bytes
 .../images/service-configuration.gif            |  Bin 0 -> 389 bytes
 .../resources/web/tenant-dashboard/index.jsp    |  243 ++
 .../web/tenant-dashboard/js/configurations.js   |  381 +++
 .../web/tenant-dashboard/js/dashboard.js        |   12 +
 .../1.0.1/modules/distribution/INSTALL.txt      |   61 +
 .../1.0.1/modules/distribution/LICENSE.txt      |  488 ++++
 .../1.0.1/modules/distribution/README.txt       |   69 +
 .../modules/distribution/lib/home/faq.html      |  392 +++
 .../distribution/lib/home/images/bottom.gif     |  Bin 0 -> 523 bytes
 .../distribution/lib/home/images/bullet-01.gif  |  Bin 0 -> 159 bytes
 .../distribution/lib/home/images/content-bg.gif |  Bin 0 -> 233 bytes
 .../distribution/lib/home/images/favicon.ico    |  Bin 0 -> 17542 bytes
 .../lib/home/images/feature-01-icon.gif         |  Bin 0 -> 2825 bytes
 .../lib/home/images/feature-02-icon.gif         |  Bin 0 -> 3361 bytes
 .../lib/home/images/feature-03-icon.gif         |  Bin 0 -> 3285 bytes
 .../lib/home/images/feature-middle-bg.gif       |  Bin 0 -> 1139 bytes
 .../distribution/lib/home/images/intro-bg.gif   |  Bin 0 -> 3964 bytes
 .../distribution/lib/home/images/intro-text.gif |  Bin 0 -> 4082 bytes
 .../distribution/lib/home/images/left-bg.gif    |  Bin 0 -> 1135 bytes
 .../distribution/lib/home/images/logo.gif       |  Bin 0 -> 11127 bytes
 .../lib/home/images/powered-logo.gif            |  Bin 0 -> 1280 bytes
 .../distribution/lib/home/images/register.gif   |  Bin 0 -> 6946 bytes
 .../distribution/lib/home/images/sign-in.gif    |  Bin 0 -> 3150 bytes
 .../lib/home/images/stratos-products-new.jpg    |  Bin 0 -> 25720 bytes
 .../distribution/lib/home/images/title-bg.gif   |  Bin 0 -> 1182 bytes
 .../distribution/lib/home/images/top.gif        |  Bin 0 -> 16149 bytes
 .../distribution/lib/home/images/webinar.png    |  Bin 0 -> 12318 bytes
 .../lib/home/images/white-paper.png             |  Bin 0 -> 15148 bytes
 .../modules/distribution/lib/home/index.html    |  119 +
 .../lib/home/js/jquery-1.5.1.min.js             |   16 +
 .../lib/home/js/jquery.orbit-1.2.3.min.js       |   17 +
 .../distribution/lib/home/js/orbit-1.2.3.css    |  202 ++
 .../lib/home/js/orbit/left-arrow.png            |  Bin 0 -> 860 bytes
 .../distribution/lib/home/js/orbit/loading.gif  |  Bin 0 -> 2608 bytes
 .../lib/home/js/orbit/mask-black.png            |  Bin 0 -> 705 bytes
 .../lib/home/js/orbit/right-arrow.png           |  Bin 0 -> 825 bytes
 .../lib/home/js/orbit/rotator-black.png         |  Bin 0 -> 733 bytes
 .../lib/home/js/orbit/timer-black.png           |  Bin 0 -> 705 bytes
 .../modules/distribution/lib/home/style.css     |  160 ++
 .../1.0.1/modules/distribution/pom.xml          |  772 ++++++
 .../distribution/qpid-resources/etc/config.xml  |  103 +
 .../qpid-resources/etc/jmxremote.access         |   23 +
 .../qpid-resources/etc/virtualhosts.xml         |   64 +
 .../distribution/qpid-resources/qpid.xml        |   22 +
 .../modules/distribution/release-notes.html     |  132 +
 .../modules/distribution/src/assembly/bin.xml   |  570 ++++
 .../modules/distribution/src/assembly/dist.xml  |   44 +
 .../distribution/src/assembly/filter.properties |    7 +
 .../distribution/src/bin/add_entry_zone_file.sh |   50 +
 .../src/bin/git-folder-structure.sh             |   47 +
 .../distribution/src/bin/manage-git-repo.sh     |  118 +
 .../src/bin/remove_entry_zone_file.sh           |   55 +
 .../distribution/src/bin/set-mysql-password.sh  |   45 +
 .../distribution/src/bin/update-instance.sh     |   34 +
 .../modules/distribution/src/bin/wso2server.bat |  170 ++
 .../modules/distribution/src/bin/wso2server.sh  |  298 ++
 .../WebContent/META-INF/MANIFEST.MF             |    3 +
 .../WebContent/WEB-INF/web.xml                  |    7 +
 .../WebContent/dashboards/as.html               |   69 +
 .../WebContent/dashboards/bam.html              |   88 +
 .../WebContent/dashboards/bps.html              |   51 +
 .../WebContent/dashboards/brs.html              |   22 +
 .../WebContent/dashboards/cep.html              |   82 +
 .../WebContent/dashboards/csg.html              |   11 +
 .../dashboards/css/features-dashboard.css       |   55 +
 .../WebContent/dashboards/dss.html              |   75 +
 .../WebContent/dashboards/esb.html              |   70 +
 .../WebContent/dashboards/greg.html             |   94 +
 .../WebContent/dashboards/gs.html               |   90 +
 .../WebContent/dashboards/images/black.png      |  Bin 0 -> 7338 bytes
 .../dashboards/images/configure_db.png          |  Bin 0 -> 43279 bytes
 .../dashboards/images/tenant_isolation.png      |  Bin 0 -> 67219 bytes
 .../images/usage_metering_and_throttling.jpg    |  Bin 0 -> 44100 bytes
 .../WebContent/dashboards/is.html               |   98 +
 .../WebContent/dashboards/manager.html          |   68 +
 .../WebContent/dashboards/mb.html               |   81 +
 .../WebContent/dashboards/ms.html               |   81 +
 .../WebContent/dashboards/server.jsp            |  151 ++
 .../css/features-dashboard-new.css              |  155 ++
 .../WebContent/tenant-dashboard/css/ie7.css     |    8 +
 .../tenant-dashboard/images/arrow-blue.png      |  Bin 0 -> 815 bytes
 .../tenant-dashboard/images/arrow-white.png     |  Bin 0 -> 846 bytes
 .../WebContent/tenant-dashboard/images/back.jpg |  Bin 0 -> 1496 bytes
 .../tenant-dashboard/images/boxes.png           |  Bin 0 -> 645 bytes
 .../images/dashboard-back-repeat.png            |  Bin 0 -> 696 bytes
 .../tenant-dashboard/images/workAreaBack.png    |  Bin 0 -> 760 bytes
 .../WebContent/tenant-dashboard/index.html      |  173 ++
 .../WebContent/tenant-dashboard/index.jsp       |  205 ++
 .../tenant-dashboard/js/jquery-1.7.1.min.js     |    4 +
 .../tenant-dashboard/js/jquery.masonry.min.js   |   10 +
 .../js/jquery/jquery-1.5.1.min.js               |   16 +
 .../js/jquery/jquery.ui.core.js                 |    1 +
 .../js/jquery/jquery.ui.core.min.js             |   17 +
 .../js/jquery/jquery.ui.tabs.min.js             |   35 +
 .../js/jquery/jquery.ui.widget.min.js           |   15 +
 .../js/jquery/jquery.validate.js                | 1166 ++++++++
 .../ui-bg_diagonals-thick_18_b81900_40x40.png   |  Bin 0 -> 260 bytes
 .../ui-bg_diagonals-thick_20_666666_40x40.png   |  Bin 0 -> 251 bytes
 .../images/ui-bg_flat_10_000000_40x100.png      |  Bin 0 -> 178 bytes
 .../images/ui-bg_glass_100_f6f6f6_1x400.png     |  Bin 0 -> 104 bytes
 .../images/ui-bg_glass_100_fdf5ce_1x400.png     |  Bin 0 -> 125 bytes
 .../images/ui-bg_glass_65_ffffff_1x400.png      |  Bin 0 -> 105 bytes
 .../ui-bg_gloss-wave_35_f6a828_500x100.png      |  Bin 0 -> 3762 bytes
 .../ui-bg_highlight-soft_100_eeeeee_1x100.png   |  Bin 0 -> 90 bytes
 .../ui-bg_highlight-soft_75_ffe45c_1x100.png    |  Bin 0 -> 129 bytes
 .../images/ui-icons_222222_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_228ef1_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_ef8c08_256x240.png          |  Bin 0 -> 5355 bytes
 .../images/ui-icons_ffd27a_256x240.png          |  Bin 0 -> 4369 bytes
 .../images/ui-icons_ffffff_256x240.png          |  Bin 0 -> 4369 bytes
 .../ui-lightness/jquery-ui-1.8.14.custom.css    |  568 ++++
 .../themes/ui-lightness/jquery.ui.accordion.css |   19 +
 .../themes/ui-lightness/jquery.ui.all.css       |   11 +
 .../ui-lightness/jquery.ui.autocomplete.css     |   53 +
 .../themes/ui-lightness/jquery.ui.base.css      |   11 +
 .../themes/ui-lightness/jquery.ui.button.css    |   38 +
 .../themes/ui-lightness/jquery.ui.core.css      |   41 +
 .../ui-lightness/jquery.ui.datepicker.css       |   68 +
 .../themes/ui-lightness/jquery.ui.dialog.css    |   21 +
 .../ui-lightness/jquery.ui.progressbar.css      |   11 +
 .../themes/ui-lightness/jquery.ui.resizable.css |   20 +
 .../ui-lightness/jquery.ui.selectable.css       |   10 +
 .../themes/ui-lightness/jquery.ui.slider.css    |   24 +
 .../themes/ui-lightness/jquery.ui.tabs.css      |   18 +
 .../themes/ui-lightness/jquery.ui.theme.css     |  249 ++
 .../features-dashboard/features-dashboard.xml   |  762 ++++++
 .../1.0.1/modules/features-dashboard/pom.xml    |  139 +
 .../manager/feature/dashbord/ui/beans/Data.java |   43 +
 .../manager/feature/dashbord/ui/beans/Link.java |   23 +
 .../feature/dashbord/ui/beans/Service.java      |   54 +
 .../feature/dashbord/ui/beans/Story.java        |   44 +
 .../feature/dashbord/ui/utils/Utils.java        |  159 ++
 .../1.0.1/modules/features/pom.xml              |   46 +
 .../features/service/etc/feature.properties     |  242 ++
 .../service/org.wso2.stratos2.feature/pom.xml   |   83 +
 .../org.wso2.stratos2.server.feature/pom.xml    |  237 ++
 .../org.wso2.stratos2.ui.feature/pom.xml        |  218 ++
 .../1.0.1/modules/features/service/pom.xml      |   49 +
 .../1.0.1/modules/integration/pom.xml           |  146 +
 .../integration/tests/LoginLogoutTestCase.java  |   48 +
 .../tests/SecurityVerificationTestCase.java     |   26 +
 .../tests/StratosManagerTestServerManager.java  |   54 +
 .../integration/tests/TenantMgtTestCase.java    |   91 +
 .../src/test/resources/instrumentation.txt      |    2 +
 .../src/test/resources/keys/wso2carbon.jks      |  Bin 0 -> 33260 bytes
 .../integration/src/test/resources/testng.xml   |   17 +
 .../1.0.1/modules/login/pom.xml                 |  140 +
 .../src/main/resources/META-INF/component.xml   |   20 +
 .../login/src/main/resources/TenantService.wsdl |  576 ++++
 .../web/tenant-login/css/loginpage.css          |  268 ++
 .../resources/web/tenant-login/css/tenant.css   |   62 +
 .../docs/images/sign-in-no-domain.png           |  Bin 0 -> 10682 bytes
 .../docs/images/sign-in-with-domain.png         |  Bin 0 -> 8233 bytes
 .../web/tenant-login/docs/userguide.html        |  113 +
 .../domain_rename_checker_ajaxprocessor.jsp     |   46 +
 .../web/tenant-login/images/body-bg.gif         |  Bin 0 -> 923 bytes
 .../web/tenant-login/images/feature-01-icon.gif |  Bin 0 -> 2825 bytes
 .../web/tenant-login/images/feature-02-icon.gif |  Bin 0 -> 3361 bytes
 .../web/tenant-login/images/feature-03-icon.gif |  Bin 0 -> 3285 bytes
 .../tenant-login/images/google-apps-login.gif   |  Bin 0 -> 4189 bytes
 .../web/tenant-login/images/link-icon.gif       |  Bin 0 -> 118 bytes
 .../web/tenant-login/images/login-bg.gif        |  Bin 0 -> 56670 bytes
 .../resources/web/tenant-login/images/logo.gif  |  Bin 0 -> 17603 bytes
 .../tenant-login/images/paas-login-1pix-1.gif   |  Bin 0 -> 43 bytes
 .../web/tenant-login/images/paas-login-1pix.gif |  Bin 0 -> 43 bytes
 .../web/tenant-login/images/powered.gif         |  Bin 0 -> 1280 bytes
 .../tenant-login/images/reg-button-hover.gif    |  Bin 0 -> 3824 bytes
 .../web/tenant-login/images/reg-button.gif      |  Bin 0 -> 3852 bytes
 .../web/tenant-login/images/register.gif        |  Bin 0 -> 4099 bytes
 .../tenant-login/images/st-login-body-bg.gif    |  Bin 0 -> 2215 bytes
 .../tenant-login/images/st-login-content-bg.gif |  Bin 0 -> 1060 bytes
 .../tenant-login/images/st-login-footer-bg.gif  |  Bin 0 -> 749 bytes
 .../tenant-login/images/st-login-header-bg.gif  |  Bin 0 -> 64503 bytes
 .../web/tenant-login/images/t-right-logo.gif    |  Bin 0 -> 2445 bytes
 .../main/resources/web/tenant-login/js/login.js |   27 +
 .../web/tenant-login/login_ajaxprocessor.jsp    |  345 +++
 .../web/tenant-login/terms/policy.html          |   71 +
 .../web/tenant-login/terms/support.html         |   38 +
 .../resources/web/tenant-login/terms/terms.html |   73 +
 .../1.0.1/modules/p2-profile-gen/pom.xml        |  471 ++++
 .../1.0.1/modules/styles/pom.xml                |   47 +
 .../1.0.1/modules/styles/product/pom.xml        |   88 +
 .../src/main/resources/META-INF/product.xml     |   27 +
 .../src/main/resources/web/product/about.html   |  130 +
 .../src/main/resources/web/styles/css/main.css  |  155 ++
 .../main/resources/web/styles/images/1px.gif    |  Bin 0 -> 43 bytes
 .../styles/images/esb-server-menu-header.gif    |  Bin 0 -> 176 bytes
 .../web/styles/images/leftRightSlider-dark.png  |  Bin 0 -> 1103 bytes
 .../resources/web/styles/images/menu_header.png |  Bin 0 -> 227 bytes
 .../web/styles/images/right-links-bg.gif        |  Bin 0 -> 1070 bytes
 .../web/styles/images/right-logo-bg.gif         |  Bin 0 -> 3445 bytes
 .../resources/web/styles/images/sc-back.png     |  Bin 0 -> 16781 bytes
 .../web/styles/images/sc-header-repeat.png      |  Bin 0 -> 178 bytes
 .../main/resources/web/styles/images/sclogo.png |  Bin 0 -> 5136 bytes
 .../1.0.1/modules/styles/service/pom.xml        |  142 +
 .../src/main/resources/META-INF/product.xml     |   26 +
 .../service/src/main/resources/web/favicon.ico  |  Bin 0 -> 17542 bytes
 .../src/main/resources/web/styles/css/main.css  |  240 ++
 .../resources/web/styles/images/def-body-bg.gif |  Bin 0 -> 419 bytes
 .../web/styles/images/def-header-bg.gif         |  Bin 0 -> 17875 bytes
 .../web/styles/images/def-header-region-bg.gif  |  Bin 0 -> 22784 bytes
 .../main/resources/web/styles/images/logo.gif   |  Bin 0 -> 1815 bytes
 .../resources/web/styles/images/powered.gif     |  Bin 0 -> 1773 bytes
 .../resources/web/styles/images/right-logo.gif  |  Bin 0 -> 6102 bytes
 .../web/styles/images/t-right-logo.gif          |  Bin 0 -> 3629 bytes
 .../stratos2/stratos_controller/1.0.1/pom.xml   |  418 +++
 .../resources/allthemes/Dark/admin/logo.gif     |  Bin 0 -> 1551 bytes
 .../resources/allthemes/Dark/admin/main.css     |  232 ++
 .../allthemes/Dark/admin/powered-stratos.gif    |  Bin 0 -> 1515 bytes
 .../allthemes/Dark/admin/right-logo.gif         |  Bin 0 -> 2325 bytes
 .../allthemes/Dark/admin/theme-header-bg.gif    |  Bin 0 -> 4245 bytes
 .../Dark/admin/theme-header-region-bg.gif       |  Bin 0 -> 793 bytes
 .../allthemes/Dark/admin/theme-menu-header.gif  |  Bin 0 -> 261 bytes
 .../Dark/admin/theme-menu-panel-l-bg.gif        |  Bin 0 -> 312 bytes
 .../Dark/admin/theme-menu-table-bg.gif          |  Bin 0 -> 5671 bytes
 .../Dark/admin/theme-right-links-bg.gif         |  Bin 0 -> 1005 bytes
 .../1.0.1/resources/allthemes/Dark/thumb.png    |  Bin 0 -> 19546 bytes
 .../allthemes/Default/admin/def-body-bg.gif     |  Bin 0 -> 419 bytes
 .../allthemes/Default/admin/def-header-bg.gif   |  Bin 0 -> 17875 bytes
 .../Default/admin/def-header-region-bg.gif      |  Bin 0 -> 22784 bytes
 .../resources/allthemes/Default/admin/logo.gif  |  Bin 0 -> 1815 bytes
 .../resources/allthemes/Default/admin/main.css  |  229 ++
 .../allthemes/Default/admin/powered-stratos.gif |  Bin 0 -> 1515 bytes
 .../allthemes/Default/admin/right-logo.gif      |  Bin 0 -> 3629 bytes
 .../1.0.1/resources/allthemes/Default/thumb.png |  Bin 0 -> 24432 bytes
 .../resources/allthemes/Light/admin/logo.gif    |  Bin 0 -> 1551 bytes
 .../resources/allthemes/Light/admin/main.css    |  229 ++
 .../allthemes/Light/admin/menu_header.gif       |  Bin 0 -> 243 bytes
 .../allthemes/Light/admin/powered-stratos.gif   |  Bin 0 -> 1515 bytes
 .../allthemes/Light/admin/right-links-bg.gif    |  Bin 0 -> 1191 bytes
 .../allthemes/Light/admin/right-logo.gif        |  Bin 0 -> 2325 bytes
 .../allthemes/Light/admin/theme-header-bg.gif   |  Bin 0 -> 3792 bytes
 .../Light/admin/theme-header-region-b-bg.gif    |  Bin 0 -> 121 bytes
 .../Light/admin/theme-header-region-bg.gif      |  Bin 0 -> 534 bytes
 .../Light/admin/theme-menu-panel-l-bg.gif       |  Bin 0 -> 772 bytes
 .../Light/admin/theme-menu-table-bg.gif         |  Bin 0 -> 5991 bytes
 .../1.0.1/resources/allthemes/Light/thumb.png   |  Bin 0 -> 18102 bytes
 .../cloud-services-icons/appserver.gif          |  Bin 0 -> 2086 bytes
 .../resources/cloud-services-icons/bam.gif      |  Bin 0 -> 1773 bytes
 .../resources/cloud-services-icons/bps.gif      |  Bin 0 -> 1531 bytes
 .../resources/cloud-services-icons/brs-old.gif  |  Bin 0 -> 1772 bytes
 .../resources/cloud-services-icons/brs.gif      |  Bin 0 -> 2170 bytes
 .../resources/cloud-services-icons/cep.png      |  Bin 0 -> 3218 bytes
 .../1.0.1/resources/cloud-services-icons/cg.gif |  Bin 0 -> 2385 bytes
 .../cloud-services-icons/csg-inactive.gif       |  Bin 0 -> 3188 bytes
 .../resources/cloud-services-icons/csg.gif      |  Bin 0 -> 3176 bytes
 .../1.0.1/resources/cloud-services-icons/ds.gif |  Bin 0 -> 2012 bytes
 .../resources/cloud-services-icons/esb.gif      |  Bin 0 -> 1787 bytes
 .../resources/cloud-services-icons/gadget.gif   |  Bin 0 -> 2242 bytes
 .../cloud-services-icons/governance.gif         |  Bin 0 -> 1977 bytes
 .../resources/cloud-services-icons/identity.gif |  Bin 0 -> 1936 bytes
 .../cloud-services-icons/inactive-appserver.gif |  Bin 0 -> 1957 bytes
 .../cloud-services-icons/inactive-bam.gif       |  Bin 0 -> 1647 bytes
 .../cloud-services-icons/inactive-brs.gif       |  Bin 0 -> 1874 bytes
 .../cloud-services-icons/inactive-cep.png       |  Bin 0 -> 2959 bytes
 .../cloud-services-icons/inactive-esb.gif       |  Bin 0 -> 1656 bytes
 .../cloud-services-icons/inactive-gadget.gif    |  Bin 0 -> 2087 bytes
 .../inactive-governance.gif                     |  Bin 0 -> 1850 bytes
 .../cloud-services-icons/inactive-identity.gif  |  Bin 0 -> 1794 bytes
 .../cloud-services-icons/inactive-mashup.gif    |  Bin 0 -> 1772 bytes
 .../cloud-services-icons/inactive-mb.png        |  Bin 0 -> 2746 bytes
 .../resources/cloud-services-icons/mashup.gif   |  Bin 0 -> 1850 bytes
 .../1.0.1/resources/cloud-services-icons/mb.png |  Bin 0 -> 3139 bytes
 .../resources/cloud-services-icons/pom.xml      |   71 +
 .../1.0.1/resources/cloud-services-icons/ss.gif |  Bin 0 -> 2432 bytes
 .../1.0.1/resources/cloud-services-icons/ts.gif |  Bin 0 -> 2475 bytes
 .../powerded-by-logos/appserver-logo.gif        |  Bin 0 -> 1473 bytes
 .../resources/powerded-by-logos/bam-logo.gif    |  Bin 0 -> 1690 bytes
 .../resources/powerded-by-logos/bps-logo.gif    |  Bin 0 -> 1606 bytes
 .../resources/powerded-by-logos/brs-logo.gif    |  Bin 0 -> 1596 bytes
 .../resources/powerded-by-logos/csg-logo.gif    |  Bin 0 -> 2030 bytes
 .../resources/powerded-by-logos/ds-logo.gif     |  Bin 0 -> 1528 bytes
 .../resources/powerded-by-logos/esb-logo.gif    |  Bin 0 -> 1598 bytes
 .../resources/powerded-by-logos/gadget-logo.gif |  Bin 0 -> 1368 bytes
 .../powerded-by-logos/governance-logo.gif       |  Bin 0 -> 1525 bytes
 .../powerded-by-logos/identity-logo.gif         |  Bin 0 -> 1398 bytes
 .../resources/powerded-by-logos/mashup-logo.gif |  Bin 0 -> 1440 bytes
 .../4.1.0/pom.xml                               |  134 +
 .../src/main/resources/AccountMgtService.wsdl   |  628 +++++
 .../resources/BillingDataAccessService.wsdl     |  910 +++++++
 .../main/resources/EmailValidationService.wsdl  |   95 +
 .../4.1.3/pom.xml                               |  135 +
 .../src/main/resources/AccountMgtService.wsdl   |  628 +++++
 .../resources/BillingDataAccessService.wsdl     |  913 +++++++
 .../main/resources/EmailValidationService.wsdl  |   95 +
 .../4.1.1/pom.xml                               |  119 +
 .../InstanceInformationManagementService.wsdl   |   65 +
 .../org.wso2.carbon.adc.mgt.stub/4.1.1/pom.xml  |  118 +
 .../resources/ApplicationManagementService.wsdl |  807 ++++++
 .../org.wso2.carbon.adc.mgt.stub/4.1.3/pom.xml  |  118 +
 .../resources/ApplicationManagementService.wsdl | 1192 ++++++++
 .../4.1.1/pom.xml                               |  121 +
 .../main/resources/RepoNotificationService.wsdl |  121 +
 .../4.1.1/pom.xml                               |  113 +
 .../resources/RepositoryInformationService.wsdl |  173 ++
 .../4.1.1/pom.xml                               |  110 +
 .../src/main/resources/TopologyMgtService.wsdl  |  201 ++
 .../4.1.0/pom.xml                               |  115 +
 .../resources/MultitenancyBillingService.wsdl   |  762 ++++++
 .../4.1.1/pom.xml                               |  121 +
 .../main/resources/CartridgeAgentService.wsdl   |  190 ++
 .../4.1.0/pom.xml                               |  110 +
 .../src/main/resources/AutoscalerService.wsdl   |  401 +++
 .../4.1.0/pom.xml                               |  113 +
 .../main/resources/CloudControllerService.wsdl  |  708 +++++
 .../4.1.1/pom.xml                               |  113 +
 .../main/resources/CloudControllerService.wsdl  |  659 +++++
 .../4.1.3/pom.xml                               |  113 +
 .../main/resources/CloudControllerService.wsdl  |  659 +++++
 .../4.1.0/pom.xml                               |  120 +
 .../src/main/resources/PackageInfoServce.wsdl   |  114 +
 .../4.1.0/pom.xml                               |  116 +
 .../src/main/resources/CloudManagerService.wsdl |  312 +++
 .../4.1.0/pom.xml                               |  114 +
 .../main/resources/TenantActivityService.wsdl   |  259 ++
 .../main/resources/TenantMonitoringService.wsdl |  389 +++
 .../4.1.0/pom.xml                               |  115 +
 .../main/resources/TenantMgtAdminService.wsdl   |  616 +++++
 .../4.1.0/pom.xml                               |  133 +
 .../GAppTenantRegistrationService.wsdl          |  212 ++
 .../4.1.0/pom.xml                               |  114 +
 .../src/main/resources/TenantMgtService.wsdl    |  392 +++
 .../4.1.0/pom.xml                               |  121 +
 .../src/main/resources/ThemeMgtService.wsdl     | 1157 ++++++++
 .../org.wso2.carbon.throttle.stub/4.1.0/pom.xml |  119 +
 .../main/resources/ThrottleAdminService.wsdl    |  634 +++++
 .../4.1.0/pom.xml                               |  113 +
 .../MultitenancyThrottlingService.wsdl          |   82 +
 .../4.1.0/pom.xml                               |  114 +
 .../resources/ThrottlingRuleEditorService.wsdl  |  148 +
 .../4.1.0/pom.xml                               |  117 +
 .../src/main/resources/MeteringQueryDS.wsdl     |  635 +++++
 .../4.1.0/pom.xml                               |  120 +
 .../resources/MeteringSummaryGenerationDS.wsdl  | 1395 ++++++++++
 .../org.wso2.carbon.usage.stub/4.1.0/pom.xml    |  118 +
 .../4.1.0/src/main/resources/UsageService.wsdl  |  540 ++++
 .../org.wso2.carbon.usage.stub/4.1.1/pom.xml    |  118 +
 .../4.1.1/src/main/resources/UsageService.wsdl  |  533 ++++
 .../org.wso2.carbon.usage.stub/4.1.2/pom.xml    |  118 +
 .../4.1.2/src/main/resources/UsageService.wsdl  |  533 ++++
 .../org.wso2.carbon.usage.stub/4.1.3/pom.xml    |  118 +
 .../4.1.3/src/main/resources/UsageService.wsdl  |  542 ++++
 .../4.1.0/pom.xml                               |  122 +
 .../resources/ValidateDomainAdminService.wsdl   |  238 ++
 .../main/resources/ValidateDomainService.wsdl   |  238 ++
 4907 files changed, 347587 insertions(+)
----------------------------------------------------------------------



[06/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
new file mode 100644
index 0000000..d5289e8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/impl/CloudControllerServiceImpl.java
@@ -0,0 +1,1123 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadata.Status;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.ntask.common.TaskException;
+import org.wso2.carbon.ntask.core.TaskInfo;
+import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
+import org.wso2.carbon.ntask.core.TaskManager;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.stratos.cloud.controller.consumers.TopologyBuilder;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredCartridgeException;
+import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredServiceException;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.wso2.carbon.stratos.cloud.controller.persist.Deserializer;
+import org.wso2.carbon.stratos.cloud.controller.publisher.CartridgeInstanceDataPublisherTask;
+import org.wso2.carbon.stratos.cloud.controller.registry.RegistryManager;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.topic.TopologySynchronizerTask;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInfo;
+import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasContext;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.stratos.cloud.controller.util.Properties;
+import org.wso2.carbon.stratos.cloud.controller.util.Property;
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Cloud Controller Service is responsible for starting up new server instances,
+ * terminating already started instances, providing pending instance count etc.
+ * 
+ */
+public class CloudControllerServiceImpl implements CloudControllerService {
+
+	private static final Log log = LogFactory.getLog(CloudControllerServiceImpl.class);
+	private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+
+	public CloudControllerServiceImpl() {
+
+		// acquire serialized data from registry
+		acquireData();
+
+		// gets the task service
+		TaskService taskService =
+		                          DeclarativeServiceReferenceHolder.getInstance()
+		                                                               .getTaskService();
+
+		if (dataHolder.getEnableBAMDataPublisher()) {
+
+			// register and schedule, BAM data publisher task 
+			registerAndScheduleDataPublisherTask(taskService);
+		}
+
+		if (dataHolder.getEnableTopologySync()) {
+
+			// start the topology builder thread
+			startTopologyBuilder();
+
+			// register and schedule, topology synchronizer task
+			registerAndScheduleTopologySyncerTask(taskService);
+		}
+	}
+
+    private void registerAndScheduleTopologySyncerTask(TaskService taskService) {
+	    TaskInfo taskInfo;
+	    TaskManager tm = null;
+	    try {
+
+	    	if (!taskService.getRegisteredTaskTypes()
+	    	                .contains(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE)) {
+
+	    		// topology sync
+	    		taskService.registerTaskType(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
+
+	    		tm =
+	    		     taskService.getTaskManager(CloudControllerConstants.TOPOLOGY_SYNC_TASK_TYPE);
+
+	    		TriggerInfo triggerInfo =
+	    		                          new TriggerInfo(
+	    		                                          dataHolder.getTopologySynchronizerCron());
+	    		taskInfo =
+	    		           new TaskInfo(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME,
+	    		                        TopologySynchronizerTask.class.getName(),
+	    		                        new HashMap<String, String>(), triggerInfo);
+	    		tm.registerTask(taskInfo);
+	    	}
+
+	    } catch (Exception e) {
+	    	String msg =
+	    	             "Error scheduling task: " +
+	    	                     CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME;
+	    	log.error(msg, e);
+	    	if (tm != null) {
+	    		try {
+	    			tm.deleteTask(CloudControllerConstants.TOPOLOGY_SYNC_TASK_NAME);
+	    		} catch (TaskException e1) {
+	    			log.error(e1);
+	    		}
+	    	}
+	    	throw new CloudControllerException(msg, e);
+	    }
+    }
+
+    private void startTopologyBuilder() {
+	    // initialize TopologyBuilder Consumer
+	    Thread topologyBuilder =
+	                              new Thread(
+	                                         new TopologyBuilder(
+	                                                             dataHolder.getSharedTopologyDiffQueue()));
+	    // start consumer
+	    topologyBuilder.start();
+    }
+
+    private TaskManager registerAndScheduleDataPublisherTask(TaskService taskService) {
+	    TaskInfo taskInfo;
+	    TaskManager tm = null;
+	    // initialize and schedule the data publisher task
+	    try {
+
+	    	if (!taskService.getRegisteredTaskTypes()
+	    	                .contains(CloudControllerConstants.DATA_PUB_TASK_TYPE)) {
+
+	    		taskService.registerTaskType(CloudControllerConstants.DATA_PUB_TASK_TYPE);
+
+	    		tm = taskService.getTaskManager(CloudControllerConstants.DATA_PUB_TASK_TYPE);
+
+	    		if (!tm.isTaskScheduled(CloudControllerConstants.DATA_PUB_TASK_NAME)) {
+
+	    			TriggerInfo triggerInfo =
+	    			                          new TriggerInfo(
+	    			                                          FasterLookUpDataHolder.getInstance()
+	    			                                                                .getDataPublisherCron());
+	    			taskInfo =
+	    			           new TaskInfo(CloudControllerConstants.DATA_PUB_TASK_NAME,
+	    			                        CartridgeInstanceDataPublisherTask.class.getName(),
+	    			                        new HashMap<String, String>(), triggerInfo);
+	    			tm.registerTask(taskInfo);
+
+	    			// Following code is currently not required, due to an issue in TS API.
+	    			// tm.scheduleTask(taskInfo.getName());
+	    		}
+	    	}
+
+	    } catch (Exception e) {
+	    	String msg =
+	    	             "Error scheduling task: " +
+	    	                     CloudControllerConstants.DATA_PUB_TASK_NAME;
+	    	log.error(msg, e);
+	    	if (tm != null) {
+	    		try {
+	    			tm.deleteTask(CloudControllerConstants.DATA_PUB_TASK_NAME);
+	    		} catch (TaskException e1) {
+	    			log.error(e1);
+	    		}
+	    	}
+	    	throw new CloudControllerException(msg, e);
+	    }
+	    return tm;
+    }
+
+	private void acquireData() {
+
+		Object obj = RegistryManager.getInstance().retrieve();
+		if (obj != null) {
+			try {
+				Object dataObj = Deserializer.deserializeFromByteArray((byte[]) obj);
+				if (dataObj instanceof FasterLookUpDataHolder) {
+					FasterLookUpDataHolder serializedObj = (FasterLookUpDataHolder) dataObj;
+					FasterLookUpDataHolder currentData = FasterLookUpDataHolder.getInstance();
+					
+					// assign necessary data
+					currentData.setNodeIdToServiceContextMap(serializedObj.getNodeIdToServiceContextMap());
+					
+					// traverse through current Service Contexts
+					for (ServiceContext ctxt : currentData.getServiceCtxtList()) {
+						// traverse through serialized Service Contexts
+	                    for (ServiceContext serializedCtxt : serializedObj.getServiceCtxtList()) {
+	                    	// if a matching Service Context found
+	                        if(ctxt.equals(serializedCtxt)){
+	                        	// persisted node ids of this Service Context
+	                        	List<Object> nodeIds = serializedObj.getNodeIdsOfServiceCtxt(serializedCtxt);
+	                        	for (Object nodeIdObj : nodeIds) {
+	                                String nodeId = (String) nodeIdObj;
+	                                
+	                                // assign persisted data
+	                                currentData.addNodeId(nodeId, ctxt);
+	                                
+                                }
+	                        	
+	                        	ctxt.setIaasContextMap(serializedCtxt.getIaasCtxts());
+	                        	appendToPublicIpProperty(serializedCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY), ctxt);
+	                        	
+	                        	// assign lastly used IaaS
+	                        	if(serializedCtxt.getCartridge() != null && serializedCtxt.getCartridge().getLastlyUsedIaas() != null){
+	                        		
+	                        		if(ctxt.getCartridge() == null){
+	                        			// load Cartridge
+	                        			ctxt.setCartridge(loadCartridge(ctxt.getCartridgeType(), ctxt.getPayload(), serializedObj.getCartridges()));
+	                        		}
+	                        		
+	                        		IaasProvider serializedIaas = serializedCtxt.getCartridge().getLastlyUsedIaas();
+	                        		ctxt.getCartridge().setLastlyUsedIaas(serializedIaas);
+	                        		
+	                        	}
+	                        }
+                        }
+                    }
+					
+					log.debug("Data is retrieved from registry.");
+				} else {
+					log.debug("No data is persisted in registry.");
+				}
+			} catch (Exception e) {
+
+				String msg =
+				             "Unable to acquire data from Registry. Hence, any historical data will not get reflected.";
+				log.warn(msg, e);
+			}
+
+		}
+	}
+
+	@Override
+	public String startInstance(String domainName, String subDomainName) {
+
+		ComputeService computeService;
+		Template template;
+		String ip = "";
+		final Lock lock = new ReentrantLock();
+
+		// check for sub domain
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting new instance of domain : " + domainName + " and sub domain : " +
+		         subDomainName);
+
+		// get the subjected ServiceContext
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge
+		serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+		                                       serviceCtxt.getPayload(),
+		                                       FasterLookUpDataHolder.getInstance().getCartridges()));
+
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		if (serviceCtxt.getCartridge().getIaases().isEmpty()) {
+			String msg =
+			             "There's no registered IaaSes found for Cartridge type: " +
+			                     serviceCtxt.getCartridge().getType();
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale up order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_UP_SORT)));
+
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			IaasContext ctxt = null;
+			if ((ctxt = serviceCtxt.getIaasContext(iaas.getType())) == null) {
+				ctxt = serviceCtxt.addIaasContext(iaas.getType());
+			}
+
+			if (iaas.getMaxInstanceLimit() > ctxt.getCurrentInstanceCount()) {
+				try {
+
+					iaas.getIaas().setDynamicPayload(iaas);
+
+					// get the ComputeService
+					computeService = iaas.getComputeService();
+
+					// corresponding Template
+					template = iaas.getTemplate();
+
+					if (template == null) {
+						String msg =
+						             "Failed to start an instance in " +
+						                     iaas.getType() +
+						                     ". Reason : Template is null. You have not specify a matching service " +
+						                     "element in the configuration file of Autoscaler.\n Hence, will try to " +
+						                     "start in another IaaS if available.";
+						log.error(msg);
+						continue;
+					}
+
+					// set instance name as the host name
+					// template.getOptions().userMetadata("Name",
+					// serviceCtxt.getHostName());
+					// template.getOptions().as(TemplateOptions.class).userMetadata("Name",
+					// serviceCtxt.getHostName());
+
+					// generate the group id from domain name and sub domain name.
+					// Should have lower-case ASCII letters, numbers, or dashes.
+					// Should have a length between 3-15
+					String str = domainName.concat("-" + subDomainName).substring(0, 10);
+					String group = str.replaceAll("[^a-z0-9-]", "");
+
+					NodeMetadata node;
+
+					// create and start a node
+					Set<? extends NodeMetadata> nodes =
+					                                    computeService.createNodesInGroup(group, 1,
+					                                                                      template);
+
+					node = nodes.iterator().next();
+
+					String autoAssignIpProp =
+					                          iaas.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
+
+					// acquire the lock
+					lock.tryLock();
+
+					try {
+						// reset ip
+						ip = "";
+						// default behavior is autoIpAssign=false
+						if (autoAssignIpProp == null ||
+						    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
+							// allocate an IP address - manual IP assigning mode
+							ip = iaas.getIaas().associateAddress(iaas, node);
+						}
+
+						if (ip.isEmpty() && node.getPublicAddresses() != null &&
+						    node.getPublicAddresses().iterator().hasNext()) {
+							ip = node.getPublicAddresses().iterator().next();
+						}
+
+						// if not public IP is assigned, we're using private IP
+						if (ip.isEmpty() && node.getPrivateAddresses() != null &&
+						    node.getPrivateAddresses().iterator().hasNext()) {
+							ip = node.getPrivateAddresses().iterator().next();
+						}
+
+						if (node.getId() == null) {
+							String msg =
+							             "Node id of the starting instance is null.\n" +
+							                     node.toString();
+							log.fatal(msg);
+							throw new CloudControllerException(msg);
+						}
+
+						// add node ID
+						ctxt.addNodeId(node.getId());
+						ctxt.addNodeToPublicIp(node.getId(), ip);
+
+						// to faster look up
+						FasterLookUpDataHolder.getInstance().addNodeId(node.getId(), serviceCtxt);
+
+						serviceCtxt.getCartridge().setLastlyUsedIaas(iaas);
+
+						// add this ip to the topology
+						appendToPublicIpProperty(ip, serviceCtxt);
+
+						ctxt.incrementCurrentInstanceCountByOne();
+						
+						// persist in registry
+						persist();
+
+						// trigger topology consumers
+						List<ServiceContext> list = new ArrayList<ServiceContext>();
+						list.add(serviceCtxt);
+						try {
+							dataHolder.getSharedTopologyDiffQueue().put(list);
+							
+							// publish data
+							CartridgeInstanceDataPublisherTask.publish();
+						} catch (InterruptedException ignore) {
+						}
+
+						if (log.isDebugEnabled()) {
+							log.debug("Node details: \n" + node.toString() + "\n***************\n");
+						}
+
+						log.info("Instance is successfully starting up in IaaS " + iaas.getType() +
+						         ".\tIP Address(public/private): " + ip + "\tNode Id: " +
+						         node.getId());
+
+						return ip;
+
+					} finally {
+						// release the lock
+						lock.unlock();
+					}
+
+				} catch (Exception e) {
+					log.warn("Failed to start an instance in " + iaas.getType() +
+					         ". Hence, will try to start in another IaaS if available.", e);
+					continue;
+				}
+			} else {
+				log.warn("Max instance limit is reached in the IaaS " + iaas.getType() +
+				          " : Max instance limit: " + iaas.getMaxInstanceLimit());
+			}
+
+		}
+
+		log.error("Failed to start an instance, in any available IaaS: " + domainName +
+		          " and sub domain : " + subDomainName);
+
+		return null;
+
+	}
+
+	/**
+	 * Appends this ip to the Service Context's {@link CloudControllerConstants#PUBLIC_IP_PROPERTY}
+     * @param ip
+     * @param serviceCtxt
+     */
+	private void appendToPublicIpProperty(String ip, ServiceContext serviceCtxt) {
+		String ipStr = serviceCtxt.getProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY);
+		if (ip != null && !"".equals(ip)) {
+			serviceCtxt.setProperty(CloudControllerConstants.PUBLIC_IP_PROPERTY,
+			                        ("".equals(ipStr) ? ""
+			                                         : ipStr +
+			                                           CloudControllerConstants.ENTRY_SEPARATOR) +
+			                                ip);
+		}
+	}
+
+	/**
+     * Persist data in registry.
+     */
+    private void persist() {
+	    try {
+	        RegistryManager.getInstance().persist(FasterLookUpDataHolder.getInstance());
+	    } catch (RegistryException e) {
+
+	    	String msg = "Failed to persist the Cloud Controller data in registry. Further, transaction roll back also failed.";
+	    	log.fatal(msg);
+	    	throw new CloudControllerException(msg, e);
+	    }
+    }
+
+	private Cartridge loadCartridge(String cartridgeType, byte[] payload, List<Cartridge> cartridges) {
+
+		for (Cartridge cartridge : cartridges) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				for (IaasProvider iaas : cartridge.getIaases()) {
+					iaas.setPayload(payload);
+				}
+				return cartridge;
+			}
+		}
+
+		return null;
+	}
+
+	@Override
+	public boolean terminateInstance(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate an instance of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		// if still, Cartridge is null
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale down order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
+
+		// traverse in scale down order
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			String msg =
+			             "Failed to terminate an instance in " + iaas.getType() +
+			                     ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+			String nodeId = null;
+
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+
+			// terminate the last instance first
+			for (String id : Lists.reverse(ctxt.getNodeIds())) {
+				if (id != null) {
+					nodeId = id;
+					break;
+				}
+			}
+
+			// if no matching node id can be found.
+			if (nodeId == null) {
+
+				log.warn(msg + " : Reason- No matching instance found for domain: " + domainName +
+				         " and sub domain: " + subDomainName + ".");
+				continue;
+			}
+
+			// terminate it!
+			terminate(iaas, ctxt, nodeId);
+			
+			// log information
+			logTermination(nodeId, ctxt, serviceCtxt);
+
+			return true;
+
+		}
+
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		         "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		         "running instance found in any available IaaS.");
+
+		return false;
+
+	}
+
+	@Override
+	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate the last instance spawned, of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		IaasProvider iaas = serviceCtxt.getCartridge().getLastlyUsedIaas();
+		// this is required since, we need to find the correct reference.
+		// caz if the lastly used iaas retrieved from registry, it is not a reference.
+		iaas = serviceCtxt.getCartridge().getIaasProvider(iaas.getType());
+
+		if (iaas != null) {
+
+			String nodeId = null;
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+
+			int i=0;
+			for (i = ctxt.getNodeIds().size()-1; i >= 0 ; i--) {
+	            String id = ctxt.getNodeIds().get(i);
+				if (id != null) {
+					nodeId = id;
+					break;
+				}
+            }
+
+			if (nodeId != null) {
+
+				// terminate it!
+				iaas = terminate(iaas, ctxt, nodeId);
+				
+				// log information
+				logTermination(nodeId, ctxt, serviceCtxt);
+
+				return true;
+			}
+
+		}
+
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		          "running instance found in lastly used IaaS.");
+
+		return false;
+
+	}
+
+	@Override
+	public boolean terminateAllInstances(String domainName, String subDomainName) {
+
+		boolean isAtLeastOneTerminated = false;
+		
+		subDomainName = checkSubDomain(subDomainName);
+
+		log.info("Starting to terminate all instances of domain : " + domainName +
+		         " and sub domain : " + subDomainName);
+
+		ServiceContext serviceCtxt =
+		                             FasterLookUpDataHolder.getInstance()
+		                                                   .getServiceContext(domainName,
+		                                                                      subDomainName);
+
+		if (serviceCtxt == null) {
+			String msg =
+			             "Not a registered service: domain - " + domainName + ", sub domain - " +
+			                     subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// load Cartridge, if null
+		if (serviceCtxt.getCartridge() == null) {
+			serviceCtxt.setCartridge(loadCartridge(serviceCtxt.getCartridgeType(),
+			                                       serviceCtxt.getPayload(),
+			                                       FasterLookUpDataHolder.getInstance()
+			                                                             .getCartridges()));
+		}
+		
+		if (serviceCtxt.getCartridge() == null) {
+			String msg =
+			             "There's no registered Cartridge found. Domain - " + domainName +
+			                     ", sub domain - " + subDomainName;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// sort the IaasProviders according to scale down order
+		Collections.sort(serviceCtxt.getCartridge().getIaases(),
+		                 IaasProviderComparator.ascending(IaasProviderComparator.getComparator(IaasProviderComparator.SCALE_DOWN_SORT)));
+
+		// traverse in scale down order
+		for (IaasProvider iaas : serviceCtxt.getCartridge().getIaases()) {
+
+			IaasContext ctxt = serviceCtxt.getIaasContext(iaas.getType());
+			
+			if (ctxt == null) {
+				log.error("Iaas Context for " + iaas.getType() + " not found. Cannot terminate instances");
+				continue;
+			}
+
+			ArrayList<String> temp = new ArrayList<String>(ctxt.getNodeIds());
+			for (String id : temp) {
+				if (id != null) {
+					// terminate it!
+					terminate(iaas, ctxt, id);
+					
+					// log information
+					logTermination(id, ctxt, serviceCtxt);
+					
+					isAtLeastOneTerminated = true;
+				}
+			}
+		}
+		
+		if(isAtLeastOneTerminated){
+			return true;
+		}
+		
+		log.info("Termination of an instance which is belong to domain '" + domainName +
+		          "' and sub domain '" + subDomainName + "' , failed! Reason: No matching " +
+		          "running instance found in lastly used IaaS.");
+
+		return false;
+
+	}
+	
+	public int getPendingInstanceCount(String domainName, String subDomainName) {
+
+		subDomainName = checkSubDomain(subDomainName);
+
+		int pendingInstanceCount = 0;
+
+		ServiceContext subjectedSerCtxt =
+		                                  FasterLookUpDataHolder.getInstance()
+		                                                        .getServiceContext(domainName,
+		                                                                           subDomainName);
+
+		if (subjectedSerCtxt != null && subjectedSerCtxt.getCartridgeType() != null) {
+			
+			// load cartridge
+			subjectedSerCtxt.setCartridge(loadCartridge(subjectedSerCtxt.getCartridgeType(),
+			                                            subjectedSerCtxt.getPayload(),
+			                                            FasterLookUpDataHolder.getInstance()
+			                                                                  .getCartridges()));
+			
+			if(subjectedSerCtxt.getCartridge() == null){
+				return pendingInstanceCount;
+			}
+			
+			List<IaasProvider> iaases = subjectedSerCtxt.getCartridge().getIaases();
+			
+			for (IaasProvider iaas : iaases) {
+
+				ComputeService computeService = iaas.getComputeService();
+
+				IaasContext ctxt = null;
+				if ((ctxt = subjectedSerCtxt.getIaasContext(iaas.getType())) == null) {
+					ctxt = subjectedSerCtxt.addIaasContext(iaas.getType());
+				}
+
+				// get list of node Ids which are belong to this domain- sub
+				// domain
+				List<String> nodeIds = ctxt.getNodeIds();
+
+				if (nodeIds.isEmpty()) {
+					log.debug("Zero nodes spawned in the IaaS " + iaas.getType() + " of domain: " +
+					          domainName + " and sub domain: " + subDomainName);
+					continue;
+				}
+
+				// get all the nodes spawned by this IaasContext
+				Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+				Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+				// traverse through all nodes of this ComputeService object
+				while (iterator.hasNext()) {
+					NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+					// if this node belongs to the requested domain
+					if (nodeIds.contains(nodeMetadata.getId())) {
+
+						// get the status of the node
+						Status nodeStatus = nodeMetadata.getStatus();
+
+						// count nodes that are in pending state
+						if (nodeStatus.equals(Status.PENDING)) {
+							pendingInstanceCount++;
+						}
+					}
+
+				}
+			}
+		}
+
+		log.debug("Pending instance count of domain '" + domainName + "' and sub domain '" +
+		          subDomainName + "' is " + pendingInstanceCount);
+
+		return pendingInstanceCount;
+
+	}
+
+	
+	/**
+	 * A helper method to terminate an instance.
+	 */
+	private IaasProvider terminate(IaasProvider iaasTemp, IaasContext ctxt, String nodeId) {
+
+		// this is just to be safe
+		if (iaasTemp.getComputeService() == null) {
+			String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
+			log.error(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		// destroy the node
+		iaasTemp.getComputeService().destroyNode(nodeId);
+		
+		
+		String autoAssignIpProp =
+			iaasTemp.getProperty(CloudControllerConstants.AUTO_ASSIGN_IP_PROPERTY);
+		
+		// release allocated IP address
+		if (autoAssignIpProp == null ||
+			    (autoAssignIpProp != null && autoAssignIpProp.equals("false"))) {
+				// allocate an IP address - manual IP assigning mode
+			iaasTemp.getIaas().releaseAddress(iaasTemp, ctxt.getPublicIp(nodeId));
+		}		
+
+		// remove the node id
+		ctxt.removeNodeId(nodeId);
+		
+		ctxt.decrementCurrentInstanceCountByOne();
+		
+		// publish data to BAM
+		CartridgeInstanceDataPublisherTask.publish();
+
+		log.info("Node with Id: '" + nodeId + "' is terminated!");
+		return iaasTemp;
+	}
+	
+	private void logTermination(String nodeId, IaasContext ctxt, ServiceContext serviceCtxt) {
+
+		// get the ip of the terminated node
+		String ip = ctxt.getPublicIp(nodeId);
+		String ipProp = CloudControllerConstants.PUBLIC_IP_PROPERTY;
+		String ipStr = serviceCtxt.getProperty(ipProp);
+		StringBuilder newIpStr = new StringBuilder("");
+
+		for (String str : ipStr.split(CloudControllerConstants.ENTRY_SEPARATOR)) {
+			if (!str.equals(ip)) {
+				newIpStr.append(str + CloudControllerConstants.ENTRY_SEPARATOR);
+			}
+		}
+
+		// add this ip to the topology
+		serviceCtxt.setProperty(ipProp,
+		                        newIpStr.length() == 0
+		                                              ? ""
+		                                              : newIpStr.substring(0, newIpStr.length() - 1)
+		                                                        .toString());
+
+		// remove the reference
+		ctxt.removeNodeIdToPublicIp(nodeId);
+
+		// persist
+		persist();
+		
+		// trigger topology consumers
+		List<ServiceContext> list = new ArrayList<ServiceContext>();
+		list.add(serviceCtxt);
+		try {
+			dataHolder.getSharedTopologyDiffQueue().put(list);
+		} catch (InterruptedException ignore) {
+		}
+
+	}
+
+	/**
+	 * Comparator to compare {@link IaasProvider} on different attributes.
+	 */
+	public enum IaasProviderComparator implements Comparator<IaasProvider> {
+		SCALE_UP_SORT {
+			public int compare(IaasProvider o1, IaasProvider o2) {
+				return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
+			}
+		},
+		SCALE_DOWN_SORT {
+			public int compare(IaasProvider o1, IaasProvider o2) {
+				return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
+			}
+		};
+
+		public static Comparator<IaasProvider> ascending(final Comparator<IaasProvider> other) {
+			return new Comparator<IaasProvider>() {
+				public int compare(IaasProvider o1, IaasProvider o2) {
+					return other.compare(o1, o2);
+				}
+			};
+		}
+
+		public static Comparator<IaasProvider> getComparator(final IaasProviderComparator... multipleOptions) {
+			return new Comparator<IaasProvider>() {
+				public int compare(IaasProvider o1, IaasProvider o2) {
+					for (IaasProviderComparator option : multipleOptions) {
+						int result = option.compare(o1, o2);
+						if (result != 0) {
+							return result;
+						}
+					}
+					return 0;
+				}
+			};
+		}
+	}
+
+	@Override
+	public boolean registerService(String domain, String subDomain, String tenantRange,
+	                               String cartridgeType, String hostName, Properties properties, byte[] payload)
+	                                                                                     throws UnregisteredCartridgeException {
+
+		// create a ServiceContext dynamically
+		ServiceContext newServiceCtxt = new ServiceContext();
+		newServiceCtxt.setDomainName(domain);
+		newServiceCtxt.setSubDomainName(subDomain);
+		newServiceCtxt.setTenantRange(tenantRange);
+		newServiceCtxt.setHostName(hostName);
+		
+		if (properties != null && properties.getProperties() != null ) {
+			// add properties
+			for (Property property : properties.getProperties()) {
+				if (property != null && property.getName() != null) {
+					newServiceCtxt.setProperty(property.getName(), property.getValue());
+				}
+			}
+		}
+		
+		newServiceCtxt.setCartridgeType(cartridgeType);
+
+		for (Cartridge cartridge : FasterLookUpDataHolder.getInstance().getCartridges()) {
+			if (cartridge.getType().equals(cartridgeType)) {
+				newServiceCtxt.setCartridge(cartridge);
+				break;
+			}
+		}
+
+		if (newServiceCtxt.getCartridge() == null) {
+			String msg = "Registration failed - Unregistered Cartridge type: " + cartridgeType;
+			log.error(msg);
+			throw new UnregisteredCartridgeException(msg);
+		}
+
+		if (payload != null && payload.length != 0) {
+
+			// write payload file
+			try {
+				String uniqueName = domain + "-" + subDomain + ".txt";
+				FileUtils.forceMkdir(new File(CloudControllerConstants.PAYLOAD_DIR));
+				File payloadFile = new File(CloudControllerConstants.PAYLOAD_DIR + uniqueName);
+				FileUtils.writeByteArrayToFile(payloadFile, payload);
+				newServiceCtxt.setPayloadFile(payloadFile.getPath());
+
+			} catch (IOException e) {
+				String msg =
+				             "Failed while persisting the payload of domain : " + domain +
+				                     ", sub domain : " + subDomain;
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+
+		} else {
+			log.debug("Payload is null or empty for :\n "+newServiceCtxt.toNode().toString());
+		}
+
+		// persist
+		try {
+			String uniqueName = domain + "-" + subDomain + "-" + UUID.randomUUID() + ".xml";
+			FileUtils.writeStringToFile(new File(CloudControllerConstants.SERVICES_DIR + uniqueName),
+			                            newServiceCtxt.toXml());
+		} catch (IOException e) {
+			String msg =
+			             "Failed while persisting the service configuration - domain : " + domain +
+			                     ", sub domain : " + subDomain + ", tenant range: " + tenantRange +
+			                     ", cartridge type: " + cartridgeType;
+			log.error(msg, e);
+			throw new CloudControllerException(msg, e);
+		}
+
+		log.info("Service successfully registered! Domain - " + domain + ", Sub domain - " +
+		         newServiceCtxt.getSubDomainName() + ", Cartridge type - " + cartridgeType);
+
+		return true;
+	}
+
+	@Override
+	public String[] getRegisteredCartridges() {
+		// get the list of cartridges registered
+		List<Cartridge> cartridges = FasterLookUpDataHolder.getInstance().getCartridges();
+
+		if (cartridges == null) {
+			return new String[0];
+		}
+
+		String[] cartridgeTypes = new String[cartridges.size()];
+		int i = 0;
+
+		for (Cartridge cartridge : cartridges) {
+			cartridgeTypes[i] = cartridge.getType();
+			i++;
+		}
+
+		return cartridgeTypes;
+	}
+
+	@Override
+	public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
+	                                          String publicKey) {
+
+		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
+
+		if (cartridge == null) {
+			String msg = "Invalid Cartridge type specified : " + cartridgeType;
+			log.fatal(msg);
+			throw new CloudControllerException(msg);
+		}
+
+		for (IaasProvider iaas : cartridge.getIaases()) {
+			String region = ComputeServiceBuilderUtil.extractRegion(iaas);
+
+			if (region == null) {
+				String msg =
+				             "Cannot find a region to create the key pair. Please add a property called 'region' under IaaS '" +
+				                     iaas.getType() + "' of Cartridge - " + cartridgeType;
+				log.fatal(msg);
+				throw new CloudControllerException(msg);
+			}
+
+			return iaas.getIaas().createKeyPairFromPublicKey(iaas, region, keyPairName, publicKey);
+		}
+
+		return false;
+	}
+
+	private String checkSubDomain(String subDomainName) {
+		// if sub domain is null, we assume it as default one.
+		if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
+			subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+			log.debug("Sub domain is null, hence using the default value : " + subDomainName);
+		}
+
+		return subDomainName;
+	}
+
+	@Override
+	public CartridgeInfo getCartridgeInfo(String cartridgeType)
+	                                                           throws UnregisteredCartridgeException {
+		Cartridge cartridge = FasterLookUpDataHolder.getInstance().getCartridge(cartridgeType);
+
+		if (cartridge != null) {
+
+			return CloudControllerUtil.toCartridgeInfo(cartridge);
+
+		}
+
+		String msg =
+		             "Cannot find a Cartridge having a type of " + cartridgeType +
+		                     ". Hence unable to find information.";
+		log.error(msg);
+		throw new UnregisteredCartridgeException(msg);
+	}
+
+	@Override
+    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException{
+		
+		subDomain = checkSubDomain(subDomain);
+
+		// find the service context
+		ServiceContext subjectedSerCtxt =
+		                                  FasterLookUpDataHolder.getInstance()
+		                                                        .getServiceContext(domain,
+		                                                                           subDomain);
+		
+		if(subjectedSerCtxt == null){
+			throw new UnregisteredServiceException("No registered service found for domain: "+domain+" - sub domain: "+subDomain);
+		}
+		
+		// get the service definition file.
+		File serviceDefFile = subjectedSerCtxt.getFile();
+		
+		// delete that file, so that it gets automatically undeployed.
+	    return serviceDefFile.delete();
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
new file mode 100644
index 0000000..c33be4e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/CloudControllerService.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.interfaces;
+
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredCartridgeException;
+import org.wso2.carbon.stratos.cloud.controller.exception.UnregisteredServiceException;
+import org.wso2.carbon.stratos.cloud.controller.util.Cartridge;
+import org.wso2.carbon.stratos.cloud.controller.util.CartridgeInfo;
+import org.wso2.carbon.stratos.cloud.controller.util.Properties;
+
+/**
+ * This Interface provides a way to communicate with underline
+ * Infrastructure which are supported by <i>JClouds</i>.
+ * 
+ */
+public interface CloudControllerService {
+
+    /**
+     * Creates a key pair in all IaaSes that are configured for the given cartridge,
+     * having the given name and public key.
+     * 
+     * <p/>
+     * <h4>Supported Formats</h4>
+     * <ul>
+     * <li>OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)</li>
+     * <li>Base64 encoded DER format</li>
+     * <li>SSH public key file format as specified in RFC4716</li>
+     * </ul>
+     * DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
+     * <p/>
+     * Supported lengths: 1024, 2048, and 4096.
+     * <p/>
+     * 
+     * @param cartridgeType
+     *            type of the cartridge. Note this cartridge type should be already
+     *            registered one.
+     * @param keyPairName
+     *            name of the key pair which is going to get created in IaaSes.
+     * @param publicKey
+     *            The public key.
+     * 
+     */
+	@Deprecated
+    public boolean createKeyPairFromPublicKey(String cartridgeType, String keyPairName,
+        String publicKey);
+
+    /**
+     * This method will return the information regarding the given cartridge, if present.
+     * Else this will return <code>null</code>.
+     * 
+     * @param cartridgeType
+     *            type of the cartridge.
+     * @return {@link CartridgeInfo} of the given cartridge type or <code>null</code>.
+     * @throws UnregisteredCartridgeException if there is no registered cartridge with this type.
+     */
+    public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException;
+
+    /**
+     * Calling this method will result in returning the pending instances
+     * count of a particular domain.
+     * 
+     * @param domainName
+     *            service cluster domain
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be started up.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return number of pending instances for this domain. If no instances of this
+     *         domain is present, this will return zero.
+     */
+    public int getPendingInstanceCount(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in returning the types of {@link Cartridge}s
+     * registered in Cloud Controller.
+     * 
+     * @return String array containing types of registered {@link Cartridge}s.
+     */
+    public String[] getRegisteredCartridges();
+    
+    /**
+     * <p>
+     * Registers the details of a newly created service cluster. This will override an already
+     * present service cluster, if there is any. A service cluster is uniquely identified by its
+     * domain and sub domain combination.
+     * </p>
+     * @param domain
+     *            service cluster domain
+     * @param subDomain
+     *            service cluster sub domain
+     * @param tenantRange 
+     * 			  tenant range eg: '1-10' or '2'
+     * @param cartridgeType
+     *            cartridge type of the new service. This should be an already registered cartridge
+     *            type.
+     * @param hostName
+     * 			  host name of this service instance
+     * @param properties
+     * 			  Set of properties related to this service definition.
+     * @param payload
+     *            payload which will be passed to instance to be started. Payload shouldn't contain 
+     *            xml tags.
+     * @return whether the registration is successful or not.
+     * 
+     * @throws UnregisteredCartridgeException
+     *             when the cartridge type requested by this service is
+     *             not a registered one.
+     */
+    public boolean registerService(String domain, String subDomain, String tenantRange, String cartridgeType,
+        String hostName, Properties properties, byte[] payload) throws UnregisteredCartridgeException;
+
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. Also note that the instance that is starting up
+     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
+     * by a hyphen (<i>-</i>).
+     * 
+     * @param domainName
+     *            service clustering domain of the instance to be started up.
+     * @param subDomainName
+     *            service clustering sub domain of the instance to be started up.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return public IP which is associated with the newly started instance.
+     */
+    public String startInstance(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in termination of all instances belong
+     * to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instances to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+    public boolean terminateAllInstances(String domainName, String subDomainName);
+
+    /**
+     * Calling this method will result in termination of an instance which is belong
+     * to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+    public boolean terminateInstance(String domainName, String subDomainName);
+    
+    /**
+     * Calling this method will result in termination of the lastly spawned instance which is
+     * belong to the provided service domain and sub domain.
+     * 
+     * @param domainName
+     *            service domain of the instance to be terminated.
+     * @param sudDomainName
+     *            service clustering sub domain of the instance to be terminated.
+     *            If this is null, the default value will be used. Default value is
+     *            {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether the termination is successful or not.
+     */
+    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
+
+    /**
+     * Unregister the service cluster which represents by this domain and sub domain.
+     * @param domain service cluster domain
+     * @param subDomain service cluster sub domain
+     * @return whether the unregistration was successful or not.
+     * @throws UnregisteredServiceException if the service cluster requested is not a registered one.
+     */
+    public boolean unregisterService(String domain, String subDomain) throws UnregisteredServiceException;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
new file mode 100644
index 0000000..a34a8ad
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/interfaces/Iaas.java
@@ -0,0 +1,73 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.interfaces;
+
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+
+/**
+ * All IaaSes that are going to support by Cloud Controller, should extend this abstract class.
+ */
+public abstract class Iaas {
+    
+    /**
+     * This should build the {@link ComputeService} object and the {@link Template} object,
+     * using the information from {@link IaasProvider} and should set the built 
+     * {@link ComputeService} object in the {@link IaasProvider#setComputeService(ComputeService)}
+     * and also should set the built {@link Template} object in the 
+     * {@link IaasProvider#setTemplate(Template)}.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     */
+    public abstract void buildComputeServiceAndTemplate(IaasProvider iaasInfo);
+    
+    /**
+     * This method provides a way to set payload that can be obtained from {@link IaasProvider#getPayload()}
+     * in the {@link Template} of this IaaS.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     */
+    public abstract void setDynamicPayload(IaasProvider iaasInfo);
+    
+    /**
+     * This will obtain an IP address from the allocated list and associate that IP with this node.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     * @param node Node to be associated with an IP.
+     * @return associated public IP.
+     */
+    public abstract String associateAddress(IaasProvider iaasInfo, NodeMetadata node);
+    
+    /**
+     * This will deallocate/release the given IP address back to pool.
+     * @param iaasInfo corresponding {@link IaasProvider}
+     * @param ip public IP address to be released.
+     */
+    public abstract void releaseAddress(IaasProvider iaasInfo, String ip);
+    
+    /**
+     * This method should create a Key Pair corresponds to a given public key in the respective region having the name given.
+     * Also should override the value of the key pair in the {@link Template} of this IaaS.
+     * @param iaasInfo {@link IaasProvider} 
+     * @param region region that the key pair will get created.
+     * @param keyPairName name of the key pair. NOTE: Jclouds adds a prefix : <code>jclouds#</code>
+     * @param publicKey public key, from which the key pair will be created.
+     * @return whether the key pair creation is successful or not.
+     */
+    public abstract boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName, String publicKey);
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
new file mode 100644
index 0000000..a658fbf
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/internal/CloudControllerDSComponent.java
@@ -0,0 +1,85 @@
+package org.wso2.carbon.stratos.cloud.controller.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.impl.CloudControllerServiceImpl;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.stratos.cloud.controller.topic.ConfigurationPublisher;
+import org.wso2.carbon.stratos.cloud.controller.util.DeclarativeServiceReferenceHolder;
+
+/**
+ * Registering Cloud Controller Service.
+ * 
+ * @scr.component name="org.wso2.carbon.stratos.cloud.controller" immediate="true"
+ * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
+ *                cardinality="1..1" policy="dynamic" bind="setTaskService"
+ *                unbind="unsetTaskService"
+ * @scr.reference name="registry.service"
+ *                interface=
+ *                "org.wso2.carbon.registry.core.service.RegistryService"
+ *                cardinality="1..1" policy="dynamic" bind="setRegistryService"
+ *                unbind="unsetRegistryService"
+ */
+public class CloudControllerDSComponent {
+
+    private static final Log log = LogFactory.getLog(CloudControllerDSComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+        	if (DeclarativeServiceReferenceHolder.getInstance().getConfigPub() == null) {
+        		DeclarativeServiceReferenceHolder.getInstance()
+        		.setConfigPub(new ConfigurationPublisher());
+        	}
+            
+            BundleContext bundleContext = context.getBundleContext();
+            bundleContext.registerService(CloudControllerService.class.getName(),
+                                          new CloudControllerServiceImpl(), null);
+            
+
+            log.debug("******* Cloud Controller Service bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Cloud Controller Service bundle is failed to activate ****", e);
+        }
+    }
+    
+    protected void setTaskService(TaskService taskService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the Task Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setTaskService(taskService);
+    }
+
+    protected void unsetTaskService(TaskService taskService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Task Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setTaskService(null);
+    }
+    
+	protected void setRegistryService(RegistryService registryService) {
+		if (log.isDebugEnabled()) {
+			log.debug("Setting the Registry Service");
+		}
+		try {
+	        DeclarativeServiceReferenceHolder.getInstance()
+	                                             .setRegistry(registryService.getGovernanceSystemRegistry());
+        } catch (RegistryException e) {
+        	String msg = "Failed when retrieving Governance System Registry.";
+        	log.error(msg, e);
+        	throw new CloudControllerException(msg, e);
+        }
+	}
+
+	protected void unsetRegistryService(RegistryService registryService) {
+		if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Registry Service");
+        }
+        DeclarativeServiceReferenceHolder.getInstance().setRegistry(null);
+	}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
new file mode 100644
index 0000000..05bb39f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/jcloud/ComputeServiceBuilderUtil.java
@@ -0,0 +1,182 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.jcloud;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.jclouds.ContextBuilder;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
+import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
+import org.jclouds.sshj.config.SshjSshClientModule;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.inject.Module;
+
+/**
+ * This class is responsible for creating a JClouds specific ComputeService object.
+ */
+public class ComputeServiceBuilderUtil {
+    
+    private static final Log log = LogFactory.getLog(ComputeServiceBuilderUtil.class);
+    
+    public static byte[] getUserData(String payloadFileName) {
+        // String userData = null;
+        byte[] bytes = 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");
+            }
+            bytes = getBytesFromFile(file);
+
+        } catch (IOException e) {
+            handleException("Cannot read data from payload file " + payloadFileName, e);
+        }
+        return bytes;
+    }
+
+    
+    public static void buildDefaultComputeService(IaasProvider iaas) {
+
+        Properties properties = new Properties();
+
+        // load properties
+        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
+            properties.put(entry.getKey(), entry.getValue());
+        }
+
+        // set modules
+        Iterable<Module> modules =
+            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
+                                     new EnterpriseConfigurationModule());
+
+        // build context
+        ContextBuilder builder =
+            ContextBuilder.newBuilder(iaas.getProvider())
+                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
+                          .overrides(properties);
+
+        // set the compute service object
+        iaas.setComputeService(builder.buildView(ComputeServiceContext.class).getComputeService());
+    }
+    
+    public static String extractRegion(IaasProvider iaas) {
+        String region;
+        // try to find region
+        if ((region = iaas.getProperty(CloudControllerConstants.REGION_PROPERTY)) == null) {
+            // if the property, isn't specified, try to obtain from the image id
+            // image id can be in following format - {region}/{UUID}
+            region = iaas.getImage().contains("/") ? iaas.getImage().split("/")[0] : null;
+        }
+
+        return region;
+    }
+    
+    /** 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;
+    }
+    
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     */
+    private static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     * @param e
+     *            exception
+     */
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
new file mode 100644
index 0000000..f1f1a31
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Deserializer.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.persist;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Deserializer {
+    
+    private static final Log log = LogFactory.getLog(Deserializer.class);
+
+    /**
+     * We deserialize only if the path to the serialized object file is exists.
+     * @param filePath path to the serialized object file
+     * @return the object obtained after deserialization or null if file isn't valid.
+     * @throws Exception
+     */
+    public static Object deserialize(String filePath) throws Exception {
+
+        ObjectInputStream objIn = null; 
+        Object obj = null;
+        
+        if(!new File(filePath).isFile()){
+            return obj;
+        }
+        
+        try {
+
+            objIn = new ObjectInputStream(new FileInputStream(filePath));
+            obj = objIn.readObject();
+
+        } catch (IOException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } catch (ClassNotFoundException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } finally{
+            objIn.close();
+        }
+        
+        return obj;
+
+    }
+    
+    /**
+     * Deserialize a byte array and retrieve the object.
+     * @param bytes bytes to be deserialized
+     * @return the deserialized {@link Object}
+     * @throws Exception if the deserialization is failed.
+     */
+    public static Object deserializeFromByteArray(byte[] bytes) throws Exception {
+
+    	ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
+    	ObjectInput in = null;
+    	try {
+    	  in = new ObjectInputStream(bis);
+    	  Object o = in.readObject(); 
+    	  
+    	  return o;
+    	  
+    	} finally {
+    	  bis.close();
+    	  in.close();
+    	}
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
new file mode 100644
index 0000000..672b704
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/persist/Serializer.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.stratos.cloud.controller.persist;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+
+public class Serializer {
+    
+    private static final Log log = LogFactory.getLog(Serializer.class);
+
+    public static void serializeToFile(Object serializableObj, String filePath) throws IOException {
+
+        File outFile = new File(filePath);
+        ObjectOutput ObjOut = null;
+        
+        try {
+
+            if(outFile.createNewFile()){
+                log.debug("Serialization file is created at "+filePath);
+            } else{
+                log.debug("Serialization file is already existing at "+filePath);
+            }
+            
+            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
+            ObjOut.writeObject(serializableObj);
+
+        } catch (IOException e) {
+            log.error("Failed to serialize the object "+serializableObj.toString()
+                      + " to file "+filePath , e);
+            throw e;
+            
+        } finally{
+            ObjOut.close();
+        }
+
+    }
+    
+    /**
+     * Serialize a {@link FasterLookUpDataHolder} to a byte array.
+     * @param serializableObj
+     * @return byte[] 
+     * @throws IOException
+     */
+    public static byte[] serializeToByteArray(FasterLookUpDataHolder serializableObj) throws IOException {
+
+    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
+    	ObjectOutput out = null;
+    	try {
+    	  out = new ObjectOutputStream(bos);   
+    	  out.writeObject(serializableObj);
+    	  
+    	  return bos.toByteArray();
+    	  
+    	} finally {
+    	  out.close();
+    	  bos.close();
+    	}
+
+    }
+
+}


[04/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
new file mode 100644
index 0000000..1c693bd
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasContext.java
@@ -0,0 +1,149 @@
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.jclouds.compute.domain.NodeMetadata;
+
+/**
+ * 
+ * Holds runtime data of an IaaS
+ */
+public class IaasContext implements Serializable{
+	
+    private static final long serialVersionUID = 3370272526949562217L;
+
+	private String type;
+	
+	private List<String> nodeIds;
+	
+	private Map<String, String> nodeToPublicIp;
+	
+	private transient Map<String, NodeMetadata> nodes;
+	
+	private List<String> toBeRemovedNodeIds;
+	
+	private int currentInstanceCount = 0;
+	
+	public IaasContext(String iaasType) {
+		this.type = iaasType;
+		nodeToPublicIp = new HashMap<String, String>();
+		nodeIds = new ArrayList<String>();
+		nodes = new HashMap<String, NodeMetadata>();
+		toBeRemovedNodeIds = new ArrayList<String>();
+    }
+
+	public Map<String, String> getNodeToPublicIp() {
+		return nodeToPublicIp;
+	}
+	
+	public Map<String, NodeMetadata> getNodes() {
+		return nodes;
+	}
+	
+	public void setToBeRemovedNodeIds(List<String> list) {
+		this.toBeRemovedNodeIds = list;
+	}
+	
+	public List<String> getAllNodeIds() {
+		List<String> allNodeIds = new ArrayList<String>(nodeIds);
+		allNodeIds.addAll(toBeRemovedNodeIds);
+		return allNodeIds;
+	}
+	
+	public List<String> getNodeIds() {
+		return nodeIds;
+	}
+	
+	public List<String> getToBeRemovedNodeIds() {
+		return toBeRemovedNodeIds;
+	}
+	
+	public boolean didISpawn(String nodeId) {
+		if(nodeIds.contains(nodeId) || toBeRemovedNodeIds.contains(nodeId)){
+			return true;
+		}
+		return false;
+	}
+	
+	public void addNodeId(String nodeId) {
+		nodeIds.add(nodeId);
+	}
+	
+	public void addNodeToPublicIp(String nodeId, String publicIp) {
+		nodeToPublicIp.put(nodeId, publicIp);
+	}
+	
+	public void addToBeRemovedNodeId(String nodeId) {
+		toBeRemovedNodeIds.add(nodeId);
+	}
+	
+	public void removeNodeId(String nodeId) {
+		if(nodeIds.remove(nodeId)){
+			toBeRemovedNodeIds.add(nodeId);
+		}
+	}
+	
+	public void removeToBeRemovedNodeId(String nodeId) {
+		toBeRemovedNodeIds.remove(nodeId);
+	}
+	
+	public void setNodeIds(List<String> nodeIds) {
+		this.nodeIds = nodeIds;
+	}
+	
+	public String lastlySpawnedNode() {
+		return nodeIds.get(nodeIds.size()-1);
+	}
+	
+	public void addNodeMetadata(NodeMetadata node) {
+	    if(nodes == null){
+	        nodes = new HashMap<String, NodeMetadata>();
+	    }
+		nodes.put(node.getId(), node);
+	}
+	
+    public void removeNodeMetadata(NodeMetadata node) {
+        if (nodes != null) {
+            nodes.remove(node.getId());
+        }
+    }
+	
+	public void removeNodeIdToPublicIp(String nodeId){
+		nodeToPublicIp.remove(nodeId);
+	}
+	
+	public NodeMetadata getNode(String nodeId) {
+	    if(nodes == null) {
+	        return null;
+	    }
+		return nodes.get(nodeId);
+	}
+	
+	public String getPublicIp(String nodeId){
+		return nodeToPublicIp.get(nodeId);
+	}
+
+	public String getType() {
+        return type;
+    }
+
+	public void setType(String type) {
+        this.type = type;
+    }
+
+	public int getCurrentInstanceCount() {
+	    return currentInstanceCount;
+    }
+
+	public void incrementCurrentInstanceCountByOne() {
+	    this.currentInstanceCount += 1;
+    }
+	
+	public void decrementCurrentInstanceCountByOne() {
+	    this.currentInstanceCount -= 1;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
new file mode 100644
index 0000000..99ae511
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/IaasProvider.java
@@ -0,0 +1,263 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.Template;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
+
+/**
+ * This is the basic data structure which holds an IaaS specific details.
+ * NOTE: If you add a new attribute, please assign it in the constructor too.
+ */
+public class IaasProvider implements Serializable{
+   
+    private static final long serialVersionUID = -940288190885166118L;
+
+	/**
+     * Unique id to identify this IaaS provider.
+     */
+    private String type;
+    
+    /**
+     * Fully qualified class name of an implementation of {@link Iaas}
+     */
+    private String className;
+    
+    /**
+     * human description of this IaaS provider
+     */
+    private String name;
+    
+    /**
+     * Property map of this IaaS provider.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * Image identifier.
+     */
+    private String image;
+    
+    /**
+     * Max instance limit that an IaaS can spawn.
+     */
+    private int maxInstanceLimit = -1;
+    
+    /**
+     * Scale up order and scale down order of the IaaS.
+     */
+    private int scaleUpOrder = -1, scaleDownOrder = -1;
+    
+    private String provider, identity, credential;
+    
+    private transient ComputeService computeService;
+    
+    private transient Template template;
+    
+    private byte[] payload;
+    
+    /** 
+     * Corresponding {@link Iaas} implementation
+     */
+    private transient Iaas iaas;
+    
+    public IaasProvider(){}
+    
+    public IaasProvider(IaasProvider anIaasProvider){
+    	this.type = anIaasProvider.getType();
+    	this.name = anIaasProvider.getName();
+    	this.className = anIaasProvider.getClassName();
+    	this.properties = anIaasProvider.getProperties();
+    	this.image = anIaasProvider.getImage();
+    	this.scaleUpOrder = anIaasProvider.getScaleUpOrder();
+    	this.scaleDownOrder = anIaasProvider.getScaleDownOrder();
+    	this.provider = anIaasProvider.getProvider();
+    	this.identity = anIaasProvider.getIdentity();
+    	this.credential = anIaasProvider.getCredential();
+    	this.computeService = anIaasProvider.getComputeService();
+    	this.template = anIaasProvider.getTemplate();
+    	this.payload = anIaasProvider.getPayload();
+    	this.iaas = anIaasProvider.getIaas();
+    	this.maxInstanceLimit = anIaasProvider.getMaxInstanceLimit();
+    }
+    
+    public String getType() {
+        return type;
+    }
+    
+    public void setType(String id) {
+        this.type = id;
+    }
+    
+    public String getProperty(String key) {
+        return properties.get(key);
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public void setProperty(String key, String value) {
+        
+        if(key != null && value != null){
+            properties.put(key, value);
+        }
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+
+    public String getImage() {
+        return image;
+    }
+
+    public void setImage(String image) {
+        this.image = image;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getProvider() {
+        return provider;
+    }
+
+    public void setProvider(String provider) {
+        this.provider = provider;
+    }
+
+    public String getIdentity() {
+        return identity;
+    }
+
+    public void setIdentity(String identity) {
+        this.identity = identity;
+    }
+
+    public String getCredential() {
+        return credential;
+    }
+
+    public void setCredential(String credential) {
+        this.credential = credential;
+    }
+
+    public ComputeService getComputeService() {
+        return computeService;
+    }
+
+    public void setComputeService(ComputeService computeService) {
+        this.computeService = computeService;
+    }
+
+    public Template getTemplate() {
+        return template;
+    }
+
+    public void setTemplate(Template template) {
+        this.template = template;
+    }
+    
+    
+
+    public boolean equals(Object o) {
+        if(o instanceof IaasProvider){
+            return ((IaasProvider) o).getType().equals(this.getType());
+        }
+        
+        return false;
+    }
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(type).
+            toHashCode();
+    }
+    
+    public IaasProvider copy(){
+		return new IaasProvider(this);
+	}
+
+    public String getClassName() {
+        return className;
+    }
+
+    public void setClassName(String className) {
+        this.className = className;
+    }
+
+    public byte[] getPayload() {
+        return payload;
+    }
+
+    public void setPayload(byte[] payload) {
+        this.payload = payload;
+    }
+
+    public Iaas getIaas() {
+        return iaas;
+    }
+
+    public void setIaas(Iaas iaas) {
+        this.iaas = iaas;
+    }
+    
+    public void reset(){
+//    	nodeIds = new ArrayList<String>();
+//    	nodes = new HashMap<String, NodeMetadata>();
+//    	toBeRemovedNodeIds = new ArrayList<String>();
+    }
+
+	public int getMaxInstanceLimit() {
+	    return this.maxInstanceLimit;
+    }
+
+	public void setMaxInstanceLimit(int maxInstanceLimit) {
+	    this.maxInstanceLimit = maxInstanceLimit;
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
new file mode 100644
index 0000000..53649a8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/PortMapping.java
@@ -0,0 +1,46 @@
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.Serializable;
+
+public class PortMapping implements Serializable{
+	
+    private static final long serialVersionUID = -5387564414633460306L;
+	private String protocol;
+	private String port;
+	private String proxyPort;
+	
+	public PortMapping(){
+		
+	}
+	
+	public PortMapping(String protocol, String port, String proxyPort){
+		this.protocol = protocol;
+		this.port = port;
+		this.proxyPort = proxyPort;
+	}
+
+	public String getProtocol() {
+    	return protocol;
+    }
+
+	public void setProtocol(String protocol) {
+    	this.protocol = protocol;
+    }
+
+	public String getPort() {
+    	return port;
+    }
+
+	public void setPort(String port) {
+    	this.port = port;
+    }
+
+	public String getProxyPort() {
+    	return proxyPort;
+    }
+
+	public void setProxyPort(String proxyPort) {
+    	this.proxyPort = proxyPort;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
new file mode 100644
index 0000000..88c5d92
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Properties.java
@@ -0,0 +1,36 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+/**
+ * Had to wrap {@link Property} array using a class, since there's a bug in current 
+ * stub generation.
+ */
+public class Properties {
+
+	private Property[] properties;
+
+	public Property[] getProperties() {
+	    return properties;
+    }
+
+	public void setProperties(Property[] properties) {
+	    this.properties = properties;
+    }
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
new file mode 100644
index 0000000..63dac14
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/Property.java
@@ -0,0 +1,35 @@
+package org.wso2.carbon.stratos.cloud.controller.util;
+/**
+ * Holds a property 
+ */
+public class Property {
+	
+	private String name;
+	private String value;
+	
+	public Property(){
+		
+	}
+	
+	public Property(String name, String value){
+		this.setName(name);
+		this.setValue(value);
+	}
+
+	public String getName() {
+	    return name;
+    }
+
+	public void setName(String name) {
+	    this.name = name;
+    }
+
+	public String getValue() {
+	    return value;
+    }
+
+	public void setValue(String value) {
+	    this.value = value;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
new file mode 100644
index 0000000..4e589ae
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/util/ServiceContext.java
@@ -0,0 +1,283 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.util;
+
+import java.io.File;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+
+/**
+ * We keep information regarding a service (i.e. a cartridge instance)
+ * in this object.
+ */
+public class ServiceContext implements Serializable{
+
+    private static final long serialVersionUID = -6740964802890082678L;
+    private File file;
+	private String domainName;
+    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+    private String tenantRange;
+    private String hostName;
+    private String payloadFilePath;
+    private String cartridgeType;
+    private Cartridge cartridge;
+    private byte[] payload;
+    /**
+     * Key - Value pair.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    /**
+     * Key - IaaS Type
+     * Value - {@link IaasContext} object
+     */
+    private Map<String, IaasContext> iaasCtxts = new HashMap<String, IaasContext>();
+	
+    public Map<String, IaasContext> getIaasCtxts() {
+    	return iaasCtxts;
+    }
+
+	public String getDomainName() {
+        return domainName;
+    }
+    
+    public boolean setDomainName(String domainName) {
+        if (!"".equals(domainName)) {
+            this.domainName = domainName;
+            return true;
+        }
+        
+        return false;
+    }
+    
+    public void setProperty(String key, String value) {
+        properties.put(key, value);
+    }
+    
+    public String getProperty(String key) {
+        
+        if(properties.containsKey(key)){
+            return properties.get(key);
+        }
+        
+        return "";
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public String getSubDomainName() {
+        return subDomainName;
+    }
+
+    public void setSubDomainName(String subDomainName) {
+        if(subDomainName == null || "".equals(subDomainName)){
+            return;
+        }
+        this.subDomainName = subDomainName;
+    }
+
+    public Cartridge getCartridge() {
+        return cartridge;
+    }
+
+    public void setCartridge(Cartridge cartridge) {
+        this.cartridge = cartridge;
+    }
+
+	public String getTenantRange() {
+	    return tenantRange;
+    }
+
+	public void setTenantRange(String tenantRange) {
+	    this.tenantRange = tenantRange;
+    }
+	
+	public IaasContext addIaasContext(String iaasType){
+		IaasContext ctxt = new IaasContext(iaasType);
+		iaasCtxts.put(iaasType, ctxt);
+		return ctxt;
+	}
+	
+	public IaasContext getIaasContext(String type){
+		return iaasCtxts.get(type);
+	}
+	
+	public void setIaasContextMap(Map<String, IaasContext> map){
+		iaasCtxts = map;
+	}
+	
+//	public byte[] getPayload() {
+//    	return payload;
+//    }
+//
+//	public void setPayload(byte[] payload) {
+//    	this.payload = payload;
+//    }
+
+
+	public String getPayloadFile() {
+	    return payloadFilePath;
+    }
+
+	public void setPayloadFile(String payloadFile) {
+	    this.payloadFilePath = payloadFile;
+    }
+
+	public String getHostName() {
+		if(cartridge != null && (hostName == null || hostName.isEmpty())){
+			return cartridge.getHostName();
+		}
+	    return hostName;
+    }
+
+	public void setHostName(String hostName) {
+	    this.hostName = hostName;
+    }
+
+	public String getCartridgeType() {
+	    return cartridgeType;
+    }
+
+	public void setCartridgeType(String cartridgeType) {
+	    this.cartridgeType = cartridgeType;
+    }
+
+	public byte[] getPayload() {
+	    return payload;
+    }
+
+	public void setPayload(byte[] payload) {
+	    this.payload = payload;
+    }
+	
+	public String toXml() {
+		String str =
+				payloadFilePath == null ? "<service domain=\"" + domainName +
+				                        "\" subDomain=\"" + subDomainName +
+				                        "\" tenantRange=\"" + tenantRange + "\">\n" +
+				                        "\t<cartridge type=\"" + cartridgeType +
+				                        "\"/>\n" + "\t<host>" + hostName +
+				                        "</host>\n" + "</service>"
+				                        
+		                                    : "<service domain=\"" + domainName +
+		                                    "\" subDomain=\"" + subDomainName +
+		                                    "\" tenantRange=\"" + tenantRange + "\">\n" +
+		                                    "\t<cartridge type=\"" + cartridgeType +
+		                                    "\"/>\n"  + "\t<host>" + hostName +
+		                                    "</host>\n" + "\t<payload>" + payloadFilePath +
+		                                    "</payload>\n" +
+		                                    propertiesToXml() +
+		                                    "</service>";
+		return str;
+	}
+	
+	public Node toNode() {
+		Node node = new Node();
+		node.setName(cartridgeType);
+		String sbrace = Constants.NGINX_NODE_START_BRACE;
+		String ebrace = Constants.NGINX_NODE_END_BRACE;
+		String delimiter = Constants.NGINX_LINE_DELIMITER;
+		String newLine = "\n";
+		String nginx = 
+				Constants.DOMAIN_ELEMENT+sbrace+newLine+
+				domainName+sbrace+newLine+
+				Constants.HOSTS_ELEMENT+" "+hostName+delimiter+newLine+
+				Constants.SUB_DOMAIN_ELEMENT+" "+subDomainName+delimiter+newLine+
+				Constants.TENANT_RANGE_ELEMENT+" "+tenantRange+delimiter+newLine+
+				propertiesToNginx()+
+				ebrace+newLine+
+				ebrace+newLine;
+		
+		return NodeBuilder.buildNode(node, nginx);
+		
+	}
+	
+	/**
+	 * Had to made this public in order to access from a test case.
+	 * @return
+	 */
+	public String propertiesToNginx() {
+		StringBuilder builder = new StringBuilder("");
+		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
+			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
+
+			String key = prop.getKey();
+			String value = prop.getValue();
+			if (key != null) {
+				builder.append(key + " " + (value == null ? "" : value) +
+				               Constants.NGINX_LINE_DELIMITER + "\n");
+			}
+
+		}
+
+		return builder.toString();
+	}
+	
+	public String propertiesToXml() {
+		StringBuilder builder = new StringBuilder("");
+		for (Iterator<Entry<String, String>> iterator = getProperties().entrySet().iterator(); iterator.hasNext();) {
+			Map.Entry<String, String> prop = (Map.Entry<String, String>) iterator.next();
+
+			String key = prop.getKey();
+			String value = prop.getValue();
+			if (key != null) {
+				builder.append("\t<property name=\""+key +"\" value=\"" + (value == null ? "" : value) +"\"/>\n");
+			}
+
+		}
+
+		return builder.toString();
+	}
+	
+	public File getFile() {
+		return file;
+	}
+	
+	public void setFile(File file) {
+		this.file = file;
+	}
+	
+	public boolean equals(Object obj) {
+		if (obj instanceof ServiceContext) {
+			return this.domainName.equals(((ServiceContext) obj).getDomainName()) &&
+			       this.subDomainName.equals(((ServiceContext) obj).getSubDomainName());
+		}
+		return false;
+	}
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+            append(domainName).
+            append(subDomainName).
+            toHashCode();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..e3e9861
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/component.xml
@@ -0,0 +1,36 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <deployers>
+    	<deployer>
+            <directory>../../conf</directory>
+            <extension>xml</extension>
+            <class>org.wso2.carbon.stratos.cloud.controller.deployers.CloudControllerDeployer</class>
+        </deployer>
+        <deployer>
+            <directory>cartridges</directory>
+            <extension>xml</extension>
+            <class>org.wso2.carbon.stratos.cloud.controller.deployers.CartridgeDeployer</class>
+        </deployer>
+        <deployer>
+            <directory>services</directory>
+            <extension>xml</extension>
+            <class>org.wso2.carbon.stratos.cloud.controller.deployers.ServiceDeployer</class>
+        </deployer>
+    </deployers>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..7d71f78
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="CloudControllerService" scope="application">
+        <parameter name="ServiceClass">org.wso2.carbon.stratos.cloud.controller.impl.CloudControllerServiceImpl</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/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
new file mode 100644
index 0000000..6887211
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridge.xsd
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="cartridge">
+    <xs:annotation>
+      <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+    	<xs:choice maxOccurs="unbounded">
+    		<xs:element name="property" maxOccurs="unbounded"
+    			minOccurs="0">
+    			<xs:annotation>
+    				<xs:documentation>
+    					cartridge element can have 0..n properties, and
+    					they'll be overwritten by the properties
+    					specified under iaasProvider child elements of
+    					cartridge element.
+    				</xs:documentation>
+    			</xs:annotation>
+    			<xs:complexType>
+    				<xs:simpleContent>
+    					<xs:extension base="xs:string">
+    						<xs:attribute type="xs:string" name="name" />
+    						<xs:attribute type="xs:string" name="value" />
+    					</xs:extension>
+    				</xs:simpleContent>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="displayName" maxOccurs="1" minOccurs="0" />
+    		<xs:element name="description" maxOccurs="1" minOccurs="0" />
+    		<xs:element name="iaasProvider" maxOccurs="unbounded"
+    			minOccurs="1">
+    			<xs:annotation>
+    				<xs:documentation>
+    					A cartridge element should add a reference to an
+    					existing IaaS provider (specified in the above
+    					&amp;lt;iaasProviders&amp;gt; section) or it can
+    					create a completely new IaaS Provider (which
+    					should have a unique "type" attribute.
+    				</xs:documentation>
+    			</xs:annotation>
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+                        <xs:element type="xs:string" name="scaleUpOrder"
+    						minOccurs="0" maxOccurs="1" />
+                        <xs:element type="xs:string" name="scaleDownOrder"
+    						minOccurs="0" maxOccurs="1" />
+                        <xs:element type="xs:string" name="maxInstanceLimit"
+    						minOccurs="0" maxOccurs="1" />
+    					<xs:element type="xs:string" name="imageId"
+    						minOccurs="0" maxOccurs="1" />
+    					<xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    				<xs:attribute type="xs:string" name="type" />
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="deployment" maxOccurs="1" minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="dir" maxOccurs="unbounded"
+    						minOccurs="0" type="xs:string">
+    					</xs:element>
+    				</xs:choice>
+    				<xs:attribute name="baseDir" type="xs:string">
+    				</xs:attribute>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="portMapping" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="http" maxOccurs="1"
+    						minOccurs="1">
+    						<xs:complexType>
+    							<xs:attribute name="port"
+    								type="xs:string" />
+    							<xs:attribute name="proxyPort"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    					<xs:element name="https" maxOccurs="1"
+    						minOccurs="0">
+    						<xs:complexType>
+    							<xs:attribute name="port"
+    								type="xs:string" />
+    							<xs:attribute name="proxyPort"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+    		<xs:element name="appTypes" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="appType" maxOccurs="unbounded"
+    						minOccurs="1">
+    						<xs:complexType>
+                                    <xs:attribute name="name" type="xs:string" use="required" />
+                                    <xs:attribute name="appSpecificMapping"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+    	</xs:choice>
+    	<xs:attribute type="xs:string" name="type" />
+    	<xs:attribute type="xs:string" name="host" />
+    	<xs:attribute type="xs:string" name="provider" />
+    	<xs:attribute type="xs:string" name="version" />
+    	<xs:attribute type="xs:boolean" name="multiTenant" />
+    </xs:complexType>
+  </xs:element>
+
+  <!-- <xs:complexType name="deploymentType">
+  	<xs:sequence>
+  		<xs:element name="dir" type="xs:string" maxOccurs="1" minOccurs="1"></xs:element>
+  	</xs:sequence>
+  </xs:complexType> -->
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
new file mode 100644
index 0000000..3b187a7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/cartridges.xsd
@@ -0,0 +1,144 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="cartridges" >
+    <xs:annotation>
+      <xs:documentation>Use below section to specify properties that are needed in order to start Cartridges.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+    <xs:sequence>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element name="cartridge" maxOccurs="unbounded" minOccurs="1">
+          <xs:annotation>
+            <xs:documentation>You can have 1..n cartridge elements.</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+            <xs:choice maxOccurs="unbounded">
+            	<xs:element name="property" maxOccurs="unbounded"
+            		minOccurs="0">
+            		<xs:annotation>
+            			<xs:documentation>
+            				cartridge element can have 0..n properties,
+            				and they'll be overwritten by the properties
+            				specified under iaasProvider child elements
+            				of cartridge element.
+            			</xs:documentation>
+            		</xs:annotation>
+            		<xs:complexType>
+            			<xs:simpleContent>
+            				<xs:extension base="xs:string">
+            					<xs:attribute type="xs:string"
+            						name="name" />
+            					<xs:attribute type="xs:string"
+            						name="value" />
+            				</xs:extension>
+            			</xs:simpleContent>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="displayName" maxOccurs="1"
+            		minOccurs="0" />
+            	<xs:element name="description" maxOccurs="1"
+            		minOccurs="0" />
+            	<xs:element name="iaasProvider" maxOccurs="unbounded"
+            		minOccurs="1">
+            		<xs:annotation>
+            			<xs:documentation>
+            				A cartridge element should add a reference
+            				to an existing IaaS provider (specified in
+            				the above &amp;lt;iaasProviders&amp;gt;
+            				section) or it can create a completely new
+            				IaaS Provider (which should have a unique
+            				"type" attribute.
+            			</xs:documentation>
+            		</xs:annotation>
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+                            <xs:element type="xs:string" name="scaleUpOrder"
+    						    minOccurs="0" maxOccurs="1" />
+                            <xs:element type="xs:string" name="scaleDownOrder"
+    						    minOccurs="0" maxOccurs="1" />
+                            <xs:element type="xs:string" name="maxInstanceLimit"
+    						    minOccurs="0" maxOccurs="1" />
+            				<xs:element type="xs:string" name="imageId"
+            					minOccurs="0" maxOccurs="1" />
+            				<xs:element name="property"
+            					maxOccurs="unbounded" minOccurs="0">
+            					<xs:complexType>
+            						<xs:simpleContent>
+            							<xs:extension
+            								base="xs:string">
+            								<xs:attribute
+            									type="xs:string" name="name" />
+            								<xs:attribute
+            									type="xs:string" name="value" />
+            							</xs:extension>
+            						</xs:simpleContent>
+            					</xs:complexType>
+            				</xs:element>
+            			</xs:choice>
+            			<xs:attribute type="xs:string" name="type" />
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="deployment" maxOccurs="1">
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+            				<xs:element name="dir" maxOccurs="unbounded"
+            					minOccurs="0" type="xs:string">
+            				</xs:element>
+            			</xs:choice>
+            			<xs:attribute name="baseDir" type="xs:string">
+            			</xs:attribute>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="portMapping" maxOccurs="1"
+            		minOccurs="1">
+            		<xs:complexType>
+            			<xs:choice maxOccurs="unbounded">
+            				<xs:element name="http" maxOccurs="1"
+            					minOccurs="1">
+            					<xs:complexType>
+            						<xs:attribute name="port"
+            							type="xs:string" />
+            						<xs:attribute name="proxyPort"
+            							type="xs:string" />
+            					</xs:complexType>
+            				</xs:element>
+            				<xs:element name="https" maxOccurs="1"
+            					minOccurs="0">
+            					<xs:complexType>
+            						<xs:attribute name="port"
+            							type="xs:string" />
+            						<xs:attribute name="proxyPort"
+            							type="xs:string" />
+            					</xs:complexType>
+            				</xs:element>
+            			</xs:choice>
+            		</xs:complexType>
+            	</xs:element>
+            	<xs:element name="appTypes" maxOccurs="1"
+    			minOccurs="1">
+    			<xs:complexType>
+    				<xs:choice maxOccurs="unbounded">
+    					<xs:element name="appType" maxOccurs="unbounded"
+    						minOccurs="1">
+    						<xs:complexType>
+                                    <xs:attribute name="name" type="xs:string" use="required" />
+                                    <xs:attribute name="appSpecificMapping"
+    								type="xs:string" />
+    						</xs:complexType>
+    					</xs:element>
+    				</xs:choice>
+    			</xs:complexType>
+    		</xs:element>
+            </xs:choice>
+            <xs:attribute type="xs:string" name="type"/>
+            <xs:attribute type="xs:string" name="host" />
+            <xs:attribute type="xs:string" name="provider" />
+            <xs:attribute type="xs:string" name="version" />
+            <xs:attribute type="xs:boolean" name="multiTenant" />
+          </xs:complexType>
+        </xs:element>
+      </xs:choice>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
new file mode 100644
index 0000000..48a8532
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/service.xsd
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+        <xs:element name="service">
+          <xs:annotation>
+            <xs:documentation>you can have 0..n service elements</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+          	<xs:choice maxOccurs="unbounded">
+          		<xs:element name="cartridge">
+          			<xs:annotation>
+          				<xs:documentation>
+          					this element's value should be a reference
+          					to an existing cartridge
+          				</xs:documentation>
+          			</xs:annotation>
+          			<xs:complexType>
+          				<xs:simpleContent>
+          					<xs:extension base="xs:string">
+          						<xs:attribute type="xs:string"
+          							name="type" />
+          					</xs:extension>
+          				</xs:simpleContent>
+          			</xs:complexType>
+          		</xs:element>
+          		<xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+          		<xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+          		<xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+          	</xs:choice>
+          	<xs:attribute type="xs:string" name="domain" />
+          	<xs:attribute type="xs:string" name="tenantRange" />
+          	<xs:attribute type="xs:string" name="subDomain" />
+          </xs:complexType>
+        </xs:element>
+</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
new file mode 100644
index 0000000..5fc9fb7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/resources/services.xsd
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+  <xs:element name="services">
+    <xs:annotation>
+      <xs:documentation>Here you specify the service domains related details.</xs:documentation>
+    </xs:annotation>
+    <xs:complexType>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element name="service" maxOccurs="unbounded" minOccurs="1">
+          <xs:annotation>
+            <xs:documentation>you can have 0..n service elements</xs:documentation>
+          </xs:annotation>
+          <xs:complexType>
+            <xs:choice maxOccurs="unbounded">
+              <xs:element name="cartridge">
+                <xs:annotation>
+                  <xs:documentation>this element's value should be a reference to an existing cartridge</xs:documentation>
+                </xs:annotation>
+                <xs:complexType>
+                  <xs:simpleContent>
+                    <xs:extension base="xs:string">
+                      <xs:attribute type="xs:string" name="type"/>
+                    </xs:extension>
+                  </xs:simpleContent>
+                </xs:complexType>
+              </xs:element>
+              <xs:element name="payload" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+              <xs:element name="host" type="xs:string" maxOccurs="1" minOccurs="0"></xs:element>
+              <xs:element name="property"
+    						maxOccurs="unbounded" minOccurs="0">
+    						<xs:complexType>
+    							<xs:simpleContent>
+    								<xs:extension base="xs:string">
+    									<xs:attribute type="xs:string"
+    										name="name" />
+    									<xs:attribute type="xs:string"
+    										name="value" />
+    								</xs:extension>
+    							</xs:simpleContent>
+    						</xs:complexType>
+    					</xs:element>
+            </xs:choice>
+            <xs:attribute type="xs:string" name="domain"/>
+            <xs:attribute type="xs:string" name="subDomain"/>
+            <xs:attribute type="xs:string" name="tenantRange" />
+          </xs:complexType>
+        </xs:element>
+      </xs:choice>
+    </xs:complexType>
+  </xs:element>
+</xs:schema>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
new file mode 100644
index 0000000..c277203
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomValidationTest.java
@@ -0,0 +1,125 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.autoscaler.service.axiom;
+
+import java.io.File;
+
+import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.xml.sax.SAXParseException;
+
+import junit.framework.TestCase;
+
+public class AxiomValidationTest extends TestCase {
+    
+    AxiomXpathParser util1, util2, util3, util4, util5, util6, util7, util8, util9;
+    File xmlSchemaCartridges = new File("src/main/resources/cartridges.xsd");
+    File xmlSchemaCartridge = new File("src/main/resources/cartridge.xsd");
+    String dir = "src/test/resources/";
+
+    public AxiomValidationTest(String name) {
+        super(name);
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        util1 = new AxiomXpathParser(new File(dir+"cartridges-1.xml"));
+        util2 = new AxiomXpathParser(new File(dir+"cartridges-2.xml"));
+        util3 = new AxiomXpathParser(new File(dir+"cartridges-3.xml"));
+        util4 = new AxiomXpathParser(new File(dir+"cartridges-4.xml"));
+        util5 = new AxiomXpathParser(new File(dir+"cartridges-5.xml"));
+        util6 = new AxiomXpathParser(new File(dir+"cartridges-6.xml"));
+        util7 = new AxiomXpathParser(new File(dir+"cartridges-7.xml"));
+        util8 = new AxiomXpathParser(new File(dir+"cartridges-8.xml"));
+        util9 = new AxiomXpathParser(new File(dir+"cartridges-9.xml"));
+        util1.parse();
+        util2.parse();
+        util3.parse();
+        util4.parse();
+        util5.parse();
+        util6.parse();
+        util7.parse();
+        util8.parse();
+        util9.parse();
+    }
+
+    public final void testCartridgeValidation() throws Exception {
+        
+        // schema 1 - cartridges 
+        assertEquals(true, util1.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util5.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util6.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util7.validate(xmlSchemaCartridges));
+        
+        assertEquals(true, util9.validate(xmlSchemaCartridges));
+        
+        // schema 2 - cartridge
+        assertEquals(true, util2.validate(xmlSchemaCartridge));
+        
+        assertEquals(true, util8.validate(xmlSchemaCartridge));
+    }
+    
+    public final void testCartridgeInvalidation() {
+        
+     // schema 1 - cartridges 
+        try {
+            util2.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util3.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util4.validate(xmlSchemaCartridges);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        // schema 2 - cartridge
+        
+        try {
+            util1.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util3.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+        
+        try {
+            util4.validate(xmlSchemaCartridge);
+        } catch (Exception e) {
+
+            assertEquals(SAXParseException.class, e.getClass());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
new file mode 100644
index 0000000..d886db1
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/axiom/AxiomXpathParserTest.java
@@ -0,0 +1,51 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.autoscaler.service.axiom;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.axiom.om.OMNode;
+import org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+
+import junit.framework.TestCase;
+
+public class AxiomXpathParserTest extends TestCase {
+    AxiomXpathParser parser;
+    File xmlFile = new File("src/test/resources/cloud-controller.xml");
+
+    public AxiomXpathParserTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        parser = new AxiomXpathParser(xmlFile);
+        parser.parse();
+    }
+    
+    public void testGetMatchingNodes(){
+        List<OMNode> list = parser.getMatchingNodes("/cloudController/iaasProviders/iaasProvider/provider");
+        assertEquals(1, list.size());
+        parser.setIaasProvidersList();
+        assertEquals(1, FasterLookUpDataHolder.getInstance().getIaasProviders().size());
+        assertEquals(5, FasterLookUpDataHolder.getInstance().getIaasProviders().get(0).getMaxInstanceLimit());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
new file mode 100644
index 0000000..2cfcfa2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/java/org/wso2/carbon/cartridge/autoscaler/service/util/ServiceContextTest.java
@@ -0,0 +1,49 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.autoscaler.service.util;
+
+import org.wso2.carbon.stratos.cloud.controller.util.ServiceContext;
+import junit.framework.TestCase;
+
+public class ServiceContextTest extends TestCase {
+    
+    ServiceContext ctxt = new ServiceContext();
+
+    public ServiceContextTest(String name) {
+        super(name);
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        ctxt.setProperty("min_app_instances", "2");
+        ctxt.setProperty("max_app_instances", "5");
+        ctxt.setProperty("public_ip", null);
+    }
+
+    public final void testPropertiesToNginx() throws Exception {
+    	assertEquals(true, ctxt.propertiesToNginx().contains("min_app_instances 2;\n"));
+    	assertEquals(true, ctxt.propertiesToNginx().contains("max_app_instances 5;\n"));
+    	assertEquals(true, ctxt.propertiesToNginx().contains("public_ip ;\n"));
+    }
+    
+    public final void testPropertiesToXml() throws Exception {
+    	System.out.println(ctxt.propertiesToXml());
+    	assertEquals(true, ctxt.propertiesToXml().contains("name=\"min_app_instances\" value=\"2\""));
+    }
+   
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
new file mode 100644
index 0000000..2eccd3d
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-1.xml
@@ -0,0 +1,33 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" host="abc.com" provider="carbon">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a php cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
new file mode 100644
index 0000000..b0fe963
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-2.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
new file mode 100644
index 0000000..eb6d565
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-3.xml
@@ -0,0 +1,16 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+		
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
new file mode 100644
index 0000000..2f82ce8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-4.xml
@@ -0,0 +1,32 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+
+			<deployment>
+				<dir>abc</dir>
+				<dir>def</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
new file mode 100644
index 0000000..705d020
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-5.xml
@@ -0,0 +1,29 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
new file mode 100644
index 0000000..28ac6fb
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-6.xml
@@ -0,0 +1,19 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php">
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
new file mode 100644
index 0000000..0baa407
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-7.xml
@@ -0,0 +1,40 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5.1">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5.1">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+			</iaasProvider>
+		
+			<deployment>
+				<dir>abc</dir>
+			</deployment>
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
new file mode 100644
index 0000000..8d43239
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-8.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
+<?xml version="1.0" encoding="ISO-8859-1"?>
+	<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="php" version="5">
+			<!-- Display name of this cartridge -->
+			<displayName>PHP</displayName>
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+			<deployment>
+				<dir>abc/def</dir>
+			</deployment>
+			
+			<appTypes>
+				<appType name="axis2services" appSpecificMapping="true"/>
+				<appType name="webapps" appSpecificMapping="false"/>
+			</appTypes>
+		</cartridge>
+	
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
new file mode 100644
index 0000000..969091a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cartridges-9.xml
@@ -0,0 +1,66 @@
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a WSO2 AS cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
+<!-- Use below section to specify properties that are needed in order to start Cartridges.  -->
+	<cartridges>
+	
+		<!-- You can have 1..n cartridge elements. -->
+		<cartridge type="as" host="abc.com" provider="carbon" version="5.1.0" multiTenant="true">
+			<!-- cartridge element can have 0..n properties, and they'll be overwritten by the properties
+				 specified under iaasProvider child elements of cartridge element. -->
+			<property name="ss" value="slsls"/>
+			<property name="ss" value="slsls"/>
+			<description>This is a WSO2 AS cartridge.</description>
+			<deployment baseDir="xyz">
+				<dir>abc</dir>
+			</deployment>
+			<!-- A cartridge element should add a reference to an existing IaaS provider (specified
+				 in the above &lt;iaasProviders&gt; section) or it can create a completely new IaaS
+				 Provider (which should have a unique "type" attribute. -->
+			<iaasProvider type="openstack" >
+				<imageId>nova/xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="instanceType" value="1"/>
+				<property name="payload" value="resources/as.txt"/>
+			</iaasProvider>
+			<iaasProvider type="ec2" >
+				<imageId>xxxxxxxxxx</imageId>
+				<property name="keyPair" value="aa"/>
+				<property name="securityGroups" value="manager,cep,mb,default"/>
+				<property name="instanceType" value="m1.large"/>
+				<property name="payload" value="resources/as-ec2.txt"/>
+			</iaasProvider>
+			
+		</cartridge>
+	
+	</cartridges>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
new file mode 100644
index 0000000..1b5b160
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/test/resources/cloud-controller.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<!--
+  ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+  
+<cloudController xmlns:svns="http://org.wso2.securevault/configuration">
+
+	<svns:secureVault
+		provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler" />
+	
+	<dataPublisher enable="false">
+		<!-- BAM Server Info - default values are 'admin' and 'admin' 
+			 Optional element. -->
+		<bamServer>
+			<adminUserName>admin</adminUserName>
+			<adminPassword svns:secretAlias="cloud.controller.bam.server.admin.password">admin</adminPassword>
+		</bamServer>
+		<!-- Default cron expression is '1 * * * * ? *' meaning 'first second of every minute'.
+			 Optional element. -->
+		<cron>1 * * * * ? *</cron>
+		<!-- Cassandra cluster related info -->
+		<cassandraInfo>
+			<connectionUrl>localhost:9160</connectionUrl>
+			<userName>admin</userName>
+			<password svns:secretAlias="cloud.controller.cassandra.server.password">admin</password>
+		</cassandraInfo>
+	</dataPublisher>
+	
+	<topologySync enable="true">
+		<!-- MB server info -->
+		<mbServerUrl>localhost:5672</mbServerUrl>
+		<cron>1 * * * * ? *</cron>
+	</topologySync>
+	
+	<!-- Specify the properties that are common to an IaaS here. This element 
+		is not necessary [0..1]. But you can use this section to avoid specifying 
+		same property over and over again. -->
+	<iaasProviders>
+		<!--<iaasProvider type="ec2" name="EC2 specific details"> <provider>aws-ec2</provider> 
+			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity> 
+			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential> 
+			<scaleUpOrder>2</scaleUpOrder> <scaleDownOrder>1</scaleDownOrder> <property 
+			name="A.x" value="a"/> <property name="B" value="b"/> <imageId>tempEC2</imageId> 
+			</iaasProvider> -->
+		<iaasProvider type="openstack" name="openstack specific details">
+			<className>org.wso2.carbon.stratos.cloud.controller.iaases.OpenstackNovaIaas</className>
+			<provider>openstack-nova</provider>
+			<identity svns:secretAlias="cloud.controller.openstack.identity">demo:demo</identity>
+			<credential svns:secretAlias="cloud.controller.openstack.credential">openstack</credential>
+			<property name="jclouds.endpoint" value="http://172.17.0.1:5000/" />
+			<property name="jclouds.api-version" value="2.0/" />
+			<scaleUpOrder>1</scaleUpOrder>
+			<scaleDownOrder>2</scaleDownOrder>
+			<maxInstanceLimit>5</maxInstanceLimit>
+			<property name="region" value="x" />
+			<property name="Y" value="y" />
+			<imageId>tempLXC</imageId>
+		</iaasProvider>
+	</iaasProviders>
+</cloudController>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/pom.xml
new file mode 100644
index 0000000..3c31500
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/pom.xml
@@ -0,0 +1,87 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.stratos.common</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Common</name>
+
+    <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.wso2.carbon.stratos.common.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.user.core.*,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+            <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+           <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.mgt</artifactId>
+            <version>${carbon.platform.version}</version>
+        </dependency>
+        <dependency>
+             <groupId>junit</groupId>
+             <artifactId>junit</artifactId>
+             <scope>test</scope>
+         </dependency>        
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
new file mode 100644
index 0000000..e2bff75
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/TenantBillingService.java
@@ -0,0 +1,24 @@
+package org.wso2.carbon.stratos.common;
+
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.Tenant;
+
+/**
+ * The OSGI service interface that enables tenant related billing actions.
+ */
+public interface TenantBillingService {
+    
+    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException;
+    
+    public String getActiveUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException;
+    
+    public void activateUsagePlan(String tenantDomain) throws StratosException;
+    
+    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException;
+
+    public void deleteBillingData(int tenantId) throws StratosException;
+
+    
+}


[36/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PersistenceManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PersistenceManager.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PersistenceManager.java
new file mode 100644
index 0000000..8bc9a53
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PersistenceManager.java
@@ -0,0 +1,853 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.dao.CartridgeSubscription;
+import org.wso2.carbon.adc.mgt.dao.DataCartridge;
+import org.wso2.carbon.adc.mgt.dao.PortMapping;
+import org.wso2.carbon.adc.mgt.dao.Repository;
+import org.wso2.carbon.adc.mgt.dao.RepositoryCredentials;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * This class is responsible for handling persistence
+ * 
+ */
+public class PersistenceManager {
+
+	private static final Log log = LogFactory.getLog(PersistenceManager.class);
+
+	public static void persistCartridgeInstanceInfo(String instanceIp, String clusterDomain, String clusterSubDomain,
+			String cartridgeType, String state) throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		PreparedStatement updateStatement = null;
+		ResultSet resultSet = null;
+
+		boolean isUpdate = false;
+		int instanceId = 0;
+		try {
+			con = StratosDBUtils.getConnection();
+
+			// First check whether Ip exists..
+			String sql = "SELECT ID FROM CARTRIDGE_INSTANCE where INSTANCE_IP=? AND CARTRIDGE_TYPE=? "
+					+ " AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, instanceIp);
+			statement.setString(2, cartridgeType);
+			statement.setString(3, clusterDomain);
+			statement.setString(4, clusterSubDomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				isUpdate = true;
+				instanceId = resultSet.getInt("ID");
+			}
+
+			String persistQuery = null;
+			if (isUpdate) {
+				persistQuery = "UPDATE CARTRIDGE_INSTANCE SET STATE=?" + " WHERE ID=?";
+				updateStatement = con.prepareStatement(persistQuery);
+				updateStatement.setString(1, state);
+				updateStatement.setInt(2, instanceId);
+			} else {
+				persistQuery = "INSERT INTO CARTRIDGE_INSTANCE (INSTANCE_IP, CARTRIDGE_TYPE, STATE, CLUSTER_DOMAIN, CLUSTER_SUBDOMAIN)"
+						+ " VALUES (?, ?, ?, ?, ?)";
+				updateStatement = con.prepareStatement(persistQuery);
+				updateStatement.setString(1, instanceIp);
+				updateStatement.setString(2, cartridgeType);
+				updateStatement.setString(3, state);
+				updateStatement.setString(4, clusterDomain);
+				updateStatement.setString(5, clusterSubDomain);
+			}
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + persistQuery);
+			}
+			updateStatement.executeUpdate();
+			con.commit();
+		} catch (Exception e) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e1) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			log.error("Error", e);
+			throw e;
+		} finally {
+			StratosDBUtils.closeResultSet(resultSet);
+			StratosDBUtils.closeAllConnections(con, statement, updateStatement);
+		}
+	}
+
+	public static boolean isAlreadySubscribed(String cartridgeType, int tenantId) throws Exception {
+
+		Connection con = null;
+		PreparedStatement preparedStatement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT C.ALIAS FROM CARTRIDGE_SUBSCRIPTION C WHERE TENANT_ID = ? AND C.CARTRIDGE = ? AND C.STATE != 'UNSUBSCRIBED'";
+			preparedStatement = con.prepareStatement(sql);
+			preparedStatement.setInt(1, tenantId);
+			preparedStatement.setString(2, cartridgeType);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = preparedStatement.executeQuery();
+			if (resultSet.next()) {
+				String alias = resultSet.getString("ALIAS");
+				if (log.isDebugEnabled()) {
+					log.debug("Already subscribed to " + cartridgeType + " with alias " + alias);
+				}
+				return true;
+			} else {
+				return false;
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, preparedStatement, resultSet);
+		}
+	}
+
+	public static List<CartridgeSubscription> retrieveSubscribedCartridges(int tenantId) throws Exception {
+
+		List<CartridgeSubscription> subscribedCartridgeList = new ArrayList<CartridgeSubscription>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT C.CARTRIDGE, C.ALIAS, C.CLUSTER_DOMAIN, C.CLUSTER_SUBDOMAIN, C.POLICY, C.STATE, "
+					+ "C.TENANT_ID, C.SUBSCRIPTION_ID, C.DATA_CARTRIDGE_ID, D.TYPE, D.USER_NAME, D.PASSWORD, "
+					+ "C.PROVIDER, C.HOSTNAME, C.MAPPED_DOMAIN, R.REPO_NAME FROM CARTRIDGE_SUBSCRIPTION C "
+					+ "LEFT JOIN DATA_CARTRIDGE D on D.DATA_CART_ID=C.DATA_CARTRIDGE_ID  "
+					+ "LEFT JOIN REPOSITORY R ON C.REPO_ID=R.REPO_ID WHERE TENANT_ID=? AND C.STATE != 'UNSUBSCRIBED' "
+					+ "ORDER BY C.SUBSCRIPTION_ID";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				CartridgeSubscription cartridge = new CartridgeSubscription();
+				cartridge.setAlias(resultSet.getString("ALIAS"));
+				cartridge.setCartridge(resultSet.getString("CARTRIDGE"));
+				cartridge.setState(resultSet.getString("STATE"));
+				cartridge.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
+				cartridge.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
+				cartridge.setProvider(resultSet.getString("PROVIDER"));
+				cartridge.setPolicy(resultSet.getString("POLICY"));
+				cartridge.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
+				Repository repo = new Repository();
+				repo.setRepoName(resultSet.getString("REPO_NAME"));
+				cartridge.setRepository(repo);
+				cartridge.setHostName(resultSet.getString("HOSTNAME"));
+				int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
+				if (dataCartridgeId != 0) {
+					DataCartridge dataCartridge = new DataCartridge();
+					dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
+					dataCartridge.setPassword(resultSet.getString("PASSWORD"));
+					dataCartridge.setUserName(resultSet.getString("USER_NAME"));
+					cartridge.setDataCartridge(dataCartridge);
+				}
+				subscribedCartridgeList.add(cartridge);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return subscribedCartridgeList;
+	}
+
+	public static String getRepoURL(int tenantId, String cartridge) throws Exception {
+
+		String repoUrl = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT REPO_NAME FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
+					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? "
+					+ "AND C.STATE != 'UNSUBSCRIBED' ";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, cartridge);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				repoUrl = resultSet.getString("REPO_NAME");
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return repoUrl;
+	}
+
+	public static RepositoryCredentials getRepoCredentials(int tenantId, String cartridge, String alias)
+			throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+		RepositoryCredentials repoCredentials = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT REPO_NAME,REPO_USER_NAME,REPO_USER_PASSWORD FROM REPOSITORY R, CARTRIDGE_SUBSCRIPTION C "
+					+ "WHERE C.REPO_ID=R.REPO_ID AND C.TENANT_ID=? AND C.CARTRIDGE=? AND C.STATE != 'UNSUBSCRIBED' ";
+			if (alias != null) {
+				sql = sql + " AND C.ALIAS=?";
+			}
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, cartridge);
+			if (alias != null) {
+				statement.setString(3, alias);
+			}
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				repoCredentials = new RepositoryCredentials();
+				repoCredentials.setUrl(resultSet.getString("REPO_NAME"));
+				repoCredentials.setUserName(resultSet.getString("REPO_USER_NAME"));
+				repoCredentials.setPassword(decryptPassword(resultSet.getString("REPO_USER_PASSWORD")));
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return repoCredentials;
+	}
+
+	public static boolean isAliasAlreadyTaken(String alias, String cartridgeType) throws Exception {
+		boolean aliasAlreadyTaken = false;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT SUBSCRIPTION_ID FROM CARTRIDGE_SUBSCRIPTION where ALIAS=? AND CARTRIDGE=? AND STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, alias);
+			statement.setString(2, cartridgeType);
+			statement.setMaxRows(1);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				log.info("Already taken..");
+				aliasAlreadyTaken = true;
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return aliasAlreadyTaken;
+	}
+
+	public static int persistSubscription(CartridgeSubscription cartridgeSubscription) throws Exception {
+
+		int cartridgeSubscriptionId = 0;
+		int repoId = 0;
+		int dataCartridgeId = 0;
+		ResultSet res = null;
+		PreparedStatement insertSubscriptionStmt = null;
+		PreparedStatement insertRepoStmt = null;
+		PreparedStatement insertDataCartStmt = null;
+
+		Connection con = null;
+
+		// persist cartridge_subscription
+		try {
+			con = StratosDBUtils.getConnection();
+			// persist repo
+			if (cartridgeSubscription.getRepository() != null) {
+				String encryptedRepoUserPassword = encryptPassword(cartridgeSubscription.getRepository()
+						.getRepoUserPassword());
+				String insertRepo = "INSERT INTO REPOSITORY (REPO_NAME,STATE,REPO_USER_NAME,REPO_USER_PASSWORD)"
+						+ " VALUES (?,?,?,?)";
+
+				insertRepoStmt = con.prepareStatement(insertRepo, Statement.RETURN_GENERATED_KEYS);
+				insertRepoStmt.setString(1, cartridgeSubscription.getRepository().getRepoName());
+				insertRepoStmt.setString(2, "ACTIVE");
+				insertRepoStmt.setString(3, cartridgeSubscription.getRepository().getRepoUserName());
+				insertRepoStmt.setString(4, encryptedRepoUserPassword);
+				if (log.isDebugEnabled()) {
+					log.debug("Executing insert: " + insertRepo);
+				}
+				insertRepoStmt.executeUpdate();
+				res = insertRepoStmt.getGeneratedKeys();
+				if (res.next()) {
+					repoId = res.getInt(1);
+				}
+				StratosDBUtils.closeResultSet(res);
+			}
+
+			// persist data cartridge
+			if (cartridgeSubscription.getDataCartridge() != null) {
+				String insertDataCartridge = "INSERT INTO DATA_CARTRIDGE (TYPE,USER_NAME,PASSWORD,STATE)"
+						+ " VALUES (?,?,?,?)";
+				insertDataCartStmt = con.prepareStatement(insertDataCartridge, Statement.RETURN_GENERATED_KEYS);
+				insertDataCartStmt.setString(1, cartridgeSubscription.getDataCartridge().getDataCartridgeType());
+				insertDataCartStmt.setString(2, cartridgeSubscription.getDataCartridge().getUserName());
+				insertDataCartStmt.setString(3, cartridgeSubscription.getDataCartridge().getPassword());
+				insertDataCartStmt.setString(4, "ACTIVE");
+				if (log.isDebugEnabled()) {
+					log.debug("Executing insert: " + insertDataCartridge);
+				}
+				insertDataCartStmt.executeUpdate();
+				res = insertDataCartStmt.getGeneratedKeys();
+				if (res.next()) {
+					dataCartridgeId = res.getInt(1);
+				}
+				StratosDBUtils.closeResultSet(res);
+			}
+
+			String insertSubscription = "INSERT INTO CARTRIDGE_SUBSCRIPTION (TENANT_ID, CARTRIDGE, PROVIDER,"
+					+ "HOSTNAME, POLICY, CLUSTER_DOMAIN, " + "CLUSTER_SUBDOMAIN, MGT_DOMAIN, MGT_SUBDOMAIN, STATE, "
+					+ "ALIAS, TENANT_DOMAIN, BASE_DIR, REPO_ID, DATA_CARTRIDGE_ID)"
+					+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+
+			insertSubscriptionStmt = con.prepareStatement(insertSubscription, Statement.RETURN_GENERATED_KEYS);
+			insertSubscriptionStmt.setInt(1, cartridgeSubscription.getTenantId());
+			insertSubscriptionStmt.setString(2, cartridgeSubscription.getCartridge());
+			insertSubscriptionStmt.setString(3, cartridgeSubscription.getProvider());
+			insertSubscriptionStmt.setString(4, cartridgeSubscription.getHostName());
+			insertSubscriptionStmt.setString(5, cartridgeSubscription.getPolicy());
+			insertSubscriptionStmt.setString(6, cartridgeSubscription.getClusterDomain());
+			insertSubscriptionStmt.setString(7, cartridgeSubscription.getClusterSubdomain());
+			insertSubscriptionStmt.setString(8, cartridgeSubscription.getMgtClusterDomain());
+			insertSubscriptionStmt.setString(9, cartridgeSubscription.getMgtClusterSubDomain());
+			insertSubscriptionStmt.setString(10, cartridgeSubscription.getState());
+			insertSubscriptionStmt.setString(11, cartridgeSubscription.getAlias());
+			insertSubscriptionStmt.setString(12, cartridgeSubscription.getTenantDomain());
+			insertSubscriptionStmt.setString(13, cartridgeSubscription.getBaseDirectory());
+			insertSubscriptionStmt.setInt(14, repoId);
+			insertSubscriptionStmt.setInt(15, dataCartridgeId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing insert: " + insertSubscription);
+			}
+			insertSubscriptionStmt.executeUpdate();
+			res = insertSubscriptionStmt.getGeneratedKeys();
+			if (res.next()) {
+				cartridgeSubscriptionId = res.getInt(1);
+			}
+
+			List<PortMapping> portMapping = cartridgeSubscription.getPortMappings();
+			// persist port map
+			if (portMapping != null && !portMapping.isEmpty()) {
+				for (PortMapping portMap : portMapping) {
+					String insertPortMapping = "INSERT INTO PORT_MAPPING (SUBSCRIPTION_ID, TYPE, PRIMARY_PORT, PROXY_PORT, STATE)"
+							+ " VALUES (?,?,?,?,?)";
+
+					PreparedStatement insertPortsStmt = con.prepareStatement(insertPortMapping);
+					insertPortsStmt.setInt(1, cartridgeSubscriptionId);
+					insertPortsStmt.setString(2, portMap.getType());
+					insertPortsStmt.setString(3, portMap.getPrimaryPort());
+					insertPortsStmt.setString(4, portMap.getProxyPort());
+					insertPortsStmt.setString(5, "ACTIVE");
+					if (log.isDebugEnabled()) {
+						log.debug("Executing insert: " + insertPortMapping);
+					}
+					insertPortsStmt.executeUpdate();
+					StratosDBUtils.closeStatement(insertPortsStmt);
+				}
+			}
+			con.commit(); // Commit manually
+		} catch (Exception e) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e1) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			log.error(e.getMessage());
+			String msg = "Exception : " + e.getMessage();
+			log.error(msg, e);
+			throw new Exception("Subscription failed!", e);
+		} finally {
+			StratosDBUtils.closeResultSet(res);
+			StratosDBUtils.closeAllConnections(con, insertRepoStmt, insertDataCartStmt, insertSubscriptionStmt);
+		}
+		return cartridgeSubscriptionId;
+	}
+
+	public static String getHostNameForCartridgeName(int tenantId, String alias) throws Exception {
+
+		String hostName = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT HOSTNAME FROM CARTRIDGE_SUBSCRIPTION where TENANT_ID=?"
+					+ " AND ALIAS=? AND STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, tenantId);
+			statement.setString(2, alias);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				hostName = resultSet.getString("HOSTNAME");
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return hostName;
+	}
+
+	public static CartridgeSubscription getSubscription(String tenantDomain, String alias) throws Exception {
+
+		CartridgeSubscription cartridgeSubscription = null;
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * FROM CARTRIDGE_SUBSCRIPTION C left join REPOSITORY R on "
+					+ "C.REPO_ID=R.REPO_ID left join DATA_CARTRIDGE D on "
+					+ "D.DATA_CART_ID=C.DATA_CARTRIDGE_ID WHERE ALIAS=? AND TENANT_DOMAIN=? AND C.STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, alias);
+			statement.setString(2, tenantDomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			if (resultSet.next()) {
+				cartridgeSubscription = new CartridgeSubscription();
+				populateSubscription(cartridgeSubscription, resultSet);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+
+		return cartridgeSubscription;
+	}
+
+	private static void populateSubscription(CartridgeSubscription cartridgeSubscription, ResultSet resultSet)
+			throws Exception {
+		String repoName = resultSet.getString("REPO_NAME");
+		if (repoName != null) {
+			Repository repo = new Repository();
+			repo.setRepoName(repoName);
+			cartridgeSubscription.setRepository(repo);
+		}
+
+		int dataCartridgeId = resultSet.getInt("DATA_CARTRIDGE_ID");
+		if (dataCartridgeId != 0) {
+			DataCartridge dataCartridge = new DataCartridge();
+			dataCartridge.setDataCartridgeType(resultSet.getString("TYPE"));
+			dataCartridge.setPassword(resultSet.getString("PASSWORD"));
+			dataCartridge.setUserName(resultSet.getString("USER_NAME"));
+			cartridgeSubscription.setDataCartridge(dataCartridge);
+		}
+		cartridgeSubscription.setPortMappings(getPortMappings(resultSet.getInt("SUBSCRIPTION_ID")));
+		cartridgeSubscription.setTenantId(resultSet.getInt("TENANT_ID"));
+		cartridgeSubscription.setState(resultSet.getString("STATE"));
+		cartridgeSubscription.setPolicy(resultSet.getString("POLICY"));
+		cartridgeSubscription.setCartridge(resultSet.getString("CARTRIDGE"));
+		cartridgeSubscription.setAlias(resultSet.getString("ALIAS"));
+		cartridgeSubscription.setClusterDomain(resultSet.getString("CLUSTER_DOMAIN"));
+		cartridgeSubscription.setClusterSubdomain(resultSet.getString("CLUSTER_SUBDOMAIN"));
+		cartridgeSubscription.setMgtClusterDomain(resultSet.getString("MGT_DOMAIN"));
+		cartridgeSubscription.setMgtClusterSubDomain(resultSet.getString("MGT_SUBDOMAIN"));
+		cartridgeSubscription.setProvider(resultSet.getString("PROVIDER"));
+		cartridgeSubscription.setHostName(resultSet.getString("HOSTNAME"));
+		cartridgeSubscription.setTenantDomain(resultSet.getString("TENANT_DOMAIN"));
+		cartridgeSubscription.setBaseDirectory(resultSet.getString("BASE_DIR"));
+		cartridgeSubscription.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
+		cartridgeSubscription.setMappedDomain(resultSet.getString("MAPPED_DOMAIN"));
+	}
+
+	private static List<PortMapping> getPortMappings(int subscriptionId) throws Exception {
+
+		List<PortMapping> portMappingList = new ArrayList<PortMapping>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * FROM PORT_MAPPING WHERE SUBSCRIPTION_ID = ?";
+			statement = con.prepareStatement(sql);
+			statement.setInt(1, subscriptionId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				PortMapping portMapping = new PortMapping();
+				portMapping.setPrimaryPort(resultSet.getString("PRIMARY_PORT"));
+				portMapping.setProxyPort(resultSet.getString("PROXY_PORT"));
+				portMapping.setType(resultSet.getString("TYPE"));
+				portMappingList.add(portMapping);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return portMappingList;
+	}
+
+	public static void updateDomainMapping(int tenantId, String cartridgeAlias, String domain) throws Exception {
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET MAPPED_DOMAIN = ? WHERE TENANT_ID = ? AND ALIAS = ?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, domain);
+			statement.setInt(2, tenantId);
+			statement.setString(3, cartridgeAlias);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing update: " + sql);
+			}
+			statement.executeUpdate();
+			con.commit();
+		} catch (Exception s) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			String msg = "Error: " + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+	}
+
+	public static List<CartridgeSubscription> getSubscription(String repositoryURL) throws Exception {
+
+		List<CartridgeSubscription> subscriptionList = new ArrayList<CartridgeSubscription>();
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "SELECT * from CARTRIDGE_SUBSCRIPTION C, REPOSITORY R "
+					+ "where R.REPO_NAME LIKE ? AND C.REPO_ID = R.REPO_ID AND C.STATE != 'UNSUBSCRIBED'";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, repositoryURL + "%");
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				CartridgeSubscription cartridgeSubscription = new CartridgeSubscription();
+				populateSubscription(cartridgeSubscription, resultSet);
+				subscriptionList.add(cartridgeSubscription);
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return subscriptionList;
+	}
+
+	public static void updateSubscriptionState(int subscriptionId, String state) throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+
+		try {
+			con = StratosDBUtils.getConnection();
+			String sql = "UPDATE CARTRIDGE_SUBSCRIPTION SET STATE=? WHERE SUBSCRIPTION_ID=?";
+			statement = con.prepareStatement(sql);
+			statement.setString(1, state);
+			statement.setInt(2, subscriptionId);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing update: " + sql);
+			}
+			statement.executeUpdate();
+			con.commit();
+		} catch (Exception s) {
+			if (con != null) {
+				try {
+					con.rollback();
+				} catch (SQLException e) {
+					log.error("Failed to rollback", e);
+				}
+			}
+			;
+			String msg = "Error: " + s.getMessage();
+			log.error(msg, s);
+			throw s;
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+	}
+
+	public static Map<String, String> getCartridgeInstanceInfo(String[] ips, String clusterDomain, String clusterSubdomain)
+            throws Exception {
+		Map<String, String> instanceIpToStateMap = new HashMap<String, String>();
+		
+		Connection con = null;
+		PreparedStatement statement = null;
+		ResultSet resultSet = null;
+		
+		try {
+			con = StratosDBUtils.getConnection();
+			StringBuilder sqlBuilder = new StringBuilder(
+					"SELECT INSTANCE_IP, STATE FROM CARTRIDGE_INSTANCE WHERE INSTANCE_IP IN (");
+			for (int i = 0; i < ips.length; i++) {
+				if (i > 0) {
+					sqlBuilder.append(", ");
+				}
+				sqlBuilder.append("?");
+			}
+			sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=?");
+			String sql = sqlBuilder.toString();
+			
+			statement = con.prepareStatement(sql);
+			int i = 1;
+			for (int j = 0; j < ips.length; j++, i++) {
+				String ip = ips[j];
+				statement.setString(i, ip);
+			}
+			statement.setString(i++, clusterDomain);
+			statement.setString(i, clusterSubdomain);
+			if (log.isDebugEnabled()) {
+				log.debug("Executing query: " + sql);
+			}
+			resultSet = statement.executeQuery();
+			while (resultSet.next()) {
+				instanceIpToStateMap.put(resultSet.getString("INSTANCE_IP"), resultSet.getString("STATE"));
+			}
+		} catch (Exception s) {
+			String msg = "Error while sql connection :" + s.getMessage();
+			log.error(msg, s);
+			throw new Exception("Ann error occurred while listing cartridge information.");
+		} finally {
+			StratosDBUtils.closeAllConnections(con, statement, resultSet);
+		}
+		return instanceIpToStateMap;
+	}
+
+	public static String getSecurityKey() {
+		String securityKey = CartridgeConstants.DEFAULT_SECURITY_KEY;
+		OMElement documentElement = null;
+		File xmlFile = new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "conf"
+				+ File.separator + CartridgeConstants.SECURITY_KEY_FILE);
+
+		if (xmlFile.exists()) {
+			try {
+				documentElement = new StAXOMBuilder(xmlFile.getPath()).getDocumentElement();
+			} catch (Exception ex) {
+				String msg = "Error occurred when parsing the " + xmlFile.getPath() + ".";
+				log.error(msg, ex);
+				ex.printStackTrace();
+			}
+			if (documentElement != null) {
+				Iterator<?> it = documentElement.getChildrenWithName(new QName(CartridgeConstants.SECURITY_KEY));
+				if (it.hasNext()) {
+					OMElement securityKeyElement = (OMElement) it.next();
+					SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);
+					String alias = securityKeyElement.getAttributeValue(new QName(CartridgeConstants.ALIAS_NAMESPACE,
+							CartridgeConstants.ALIAS_LOCALPART, CartridgeConstants.ALIAS_PREFIX));
+
+					if (secretResolver != null && secretResolver.isInitialized()
+							&& secretResolver.isTokenProtected(alias)) {
+						securityKey = "";
+						securityKey = secretResolver.resolve(alias);
+						// TODO : a proper testing on the secure vault protected
+						// user defined encryption key
+					}
+				}
+			}
+		} else {
+			System.out.println("No such file ezoxists");
+		}
+		return securityKey;
+	}
+
+	public static void updateInstanceState(String state, String[] ips, String clusterDomain, String clusterSubDomain, String cartridgeType)
+			throws Exception {
+
+		Connection con = null;
+		PreparedStatement statement = null;
+
+		if (ips != null && ips.length > 0) {
+			try {
+				con = StratosDBUtils.getConnection();
+				StringBuilder sqlBuilder = new StringBuilder(
+						"UPDATE CARTRIDGE_INSTANCE SET STATE=? WHERE INSTANCE_IP IN (");
+				for (int i = 0; i < ips.length; i++) {
+					if (i > 0) {
+						sqlBuilder.append(", ");
+					}
+					sqlBuilder.append("?");
+				}
+				sqlBuilder.append(") AND CLUSTER_DOMAIN=? AND CLUSTER_SUBDOMAIN=? AND CARTRIDGE_TYPE=?");
+				String sql = sqlBuilder.toString();
+				statement = con.prepareStatement(sql);
+				statement.setString(1, state);
+				int i = 2;
+				for (int j = 0; j < ips.length; j++, i++) {
+					String ip = ips[j];
+					statement.setString(i, ip);
+				}
+				statement.setString(i++, clusterDomain);
+				statement.setString(i++, clusterSubDomain);
+				statement.setString(i, cartridgeType);
+				if (log.isDebugEnabled()) {
+					log.debug("Executing query: " + sql);
+				}
+				statement.executeUpdate();
+				con.commit();
+			} catch (Exception s) {
+				if (con != null) {
+					try {
+						con.rollback();
+					} catch (SQLException e) {
+						log.error("Failed to rollback", e);
+					}
+				}
+				String msg = "Error: " + s.getMessage();
+				log.error(msg, s);
+				throw s;
+			} finally {
+				StratosDBUtils.closeAllConnections(con, statement);
+			}
+		}
+
+	}
+
+	private static String encryptPassword(String repoUserPassword) {
+		String encryptPassword = "";
+		String secret = getSecurityKey(); // secret key length must be 16
+		SecretKey key;
+		Cipher cipher;
+		Base64 coder;
+		key = new SecretKeySpec(secret.getBytes(), "AES");
+		try {
+			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+			coder = new Base64();
+			cipher.init(Cipher.ENCRYPT_MODE, key);
+			byte[] cipherText = cipher.doFinal(repoUserPassword.getBytes());
+			encryptPassword = new String(coder.encode(cipherText));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return encryptPassword;
+	}
+
+	private static String decryptPassword(String repoUserPassword) {
+		String decryptPassword = "";
+		String secret = getSecurityKey(); // secret key length must be 16
+		SecretKey key;
+		Cipher cipher;
+		Base64 coder;
+		key = new SecretKeySpec(secret.getBytes(), "AES");
+		try {
+			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
+			coder = new Base64();
+			byte[] encrypted = coder.decode(repoUserPassword.getBytes());
+			cipher.init(Cipher.DECRYPT_MODE, key);
+			byte[] decrypted = cipher.doFinal(encrypted);
+			decryptPassword = new String(decrypted);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		return decryptPassword;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PolicyHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PolicyHolder.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PolicyHolder.java
new file mode 100644
index 0000000..2cfa0ba
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/PolicyHolder.java
@@ -0,0 +1,289 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import javax.xml.validation.Validator;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
+import org.apache.axiom.om.impl.dom.ElementImpl;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.w3c.dom.Element;
+import org.wso2.carbon.adc.mgt.dto.Policy;
+import org.wso2.carbon.adc.mgt.dto.PolicyDefinition;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.xml.sax.SAXException;
+
+import com.google.gson.Gson;
+
+public class PolicyHolder {
+
+	private static Log log = LogFactory.getLog(PolicyHolder.class);
+
+	private static final String POLICIES_ELEMENT = "policies";
+	private static final String POLICY_ELEMENT = "policy";
+
+	private static final String POLICIES_ELEMENT_XPATH = "/" + POLICIES_ELEMENT + "/" + POLICY_ELEMENT;
+
+	private static final String NAME_ATTR = "name";
+	private static final String IS_DEFAULT_ATTR = "isDefault";
+	private static final String DESCRIPTION_ELEMENT = "description";
+	private static final String MIN_APP_INSTANCES_ELEMENT = "min_app_instances";
+	private static final String MAX_APP_INSTANCES_ELEMENT = "max_app_instances";
+	private static final String MAX_REQUESTS_PER_SECOND_ELEMENT = "max_requests_per_second";
+	private static final String ALARMING_UPPER_RATE_ELEMENT = "alarming_upper_rate";
+	private static final String ALARMING_LOWER_RATE_ELEMENT = "alarming_lower_rate";
+	private static final String SCALE_DOWN_FACTOR_ELEMENT = "scale_down_factor";
+	private static final String ROUNDS_TO_AVERAGE_ELEMENT = "rounds_to_average";
+
+	private Map<String, Policy> policyMap = new HashMap<String, Policy>();
+
+	private Policy defaultPolicy;
+
+	private List<PolicyDefinition> policyDefinitions = new ArrayList<PolicyDefinition>();
+
+	private PolicyHolder(File policiesSchema, File policiesXML) {
+		try {
+			readPolicies(policiesSchema, policiesXML);
+		} catch (Exception e) {
+			log.error("Error reading policies", e);
+		}
+	}
+
+	private static class SingletonHolder {
+		private final static PolicyHolder INSTANCE = new PolicyHolder(new File(CarbonUtils.getCarbonConfigDirPath()
+				+ File.separator + "etc" + File.separator, "policies.xsd"), new File(
+				CarbonUtils.getCarbonConfigDirPath(), "policies.xml"));
+	}
+
+	public static PolicyHolder getInstance() {
+		return SingletonHolder.INSTANCE;
+	}
+
+	public Policy getPolicy(String policyName) {
+		return policyMap.get(policyName);
+	}
+
+	public Policy getDefaultPolicy() {
+		return defaultPolicy;
+	}
+
+	public List<PolicyDefinition> getPolicyDefinitions() {
+		return policyDefinitions;
+	}
+
+	private void readPolicies(File policiesSchema, File policiesXML) throws XMLStreamException, JaxenException,
+			SAXException, IOException {
+		if (log.isDebugEnabled()) {
+			log.debug("Policies schema: " + policiesSchema.getPath());
+			log.debug("Loading policies from file: " + policiesXML.getPath());
+		}
+		OMElement documentElement;
+		if (policiesXML.exists()) {
+			documentElement = new StAXOMBuilder(policiesXML.getPath()).getDocumentElement();
+		} else {
+			throw new IllegalStateException("Policies file cannot be found : " + policiesXML.getPath());
+		}
+
+		// Validate XML
+		validate(documentElement, policiesSchema);
+		
+		String xpath = POLICIES_ELEMENT_XPATH;
+
+		AXIOMXPath axiomXpath;
+		axiomXpath = new AXIOMXPath(xpath);
+		@SuppressWarnings("unchecked")
+		List<OMNode> policyNodes = axiomXpath.selectNodes(documentElement);
+
+		if (policyNodes == null || policyNodes.isEmpty()) {
+			log.warn("No policies found in the file : " + policiesXML.getPath());
+			return;
+		}
+
+		for (OMNode policyNode : policyNodes) {
+
+			if (policyNode.getType() == OMNode.ELEMENT_NODE) {
+
+				OMElement policyElement = (OMElement) policyNode;
+
+				try {
+					readPolicy(policyElement);
+				} catch (Exception e) {
+					log.error("Error reading policy", e);
+				}
+			}
+		}
+	}
+
+	private void readPolicy(OMElement policyElement) {
+		// retrieve attributes
+		String name = policyElement.getAttributeValue(new QName(NAME_ATTR));
+		boolean isDefault = Boolean.valueOf(policyElement.getAttributeValue(new QName(IS_DEFAULT_ATTR)));
+
+		Policy policy = new Policy();
+		policy.setName(name);
+		policy.setDefaultPolicy(isDefault);
+
+		// read description
+		Iterator<?> it = policyElement.getChildrenWithName(new QName(DESCRIPTION_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setDescription(element.getText());
+		}
+
+		// read min_app_instances
+		it = policyElement.getChildrenWithName(new QName(MIN_APP_INSTANCES_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMinAppInstances(Integer.parseInt(element.getText()));
+		}
+
+		// read max_app_instances
+		it = policyElement.getChildrenWithName(new QName(MAX_APP_INSTANCES_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMaxAppInstances(Integer.parseInt(element.getText()));
+		}
+
+		// read max_requests_per_second
+		it = policyElement.getChildrenWithName(new QName(MAX_REQUESTS_PER_SECOND_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setMaxRequestsPerSecond(Integer.parseInt(element.getText()));
+		}
+
+		// read rounds_to_average
+		it = policyElement.getChildrenWithName(new QName(ROUNDS_TO_AVERAGE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setRoundsToAverage(Integer.parseInt(element.getText()));
+		}
+
+		// read alarming_upper_rate
+		it = policyElement.getChildrenWithName(new QName(ALARMING_UPPER_RATE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setAlarmingUpperRate(new BigDecimal(element.getText()));
+		}
+
+		// read alarming_lower_rate
+		it = policyElement.getChildrenWithName(new QName(ALARMING_LOWER_RATE_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setAlarmingLowerRate(new BigDecimal(element.getText()));
+		}
+
+		// read scale_down_factor
+		it = policyElement.getChildrenWithName(new QName(SCALE_DOWN_FACTOR_ELEMENT));
+
+		if (it.hasNext()) {
+			OMElement element = (OMElement) it.next();
+			policy.setScaleDownFactor(new BigDecimal(element.getText()));
+		}
+		if (log.isDebugEnabled()) {
+			log.debug("Policy: " + new Gson().toJson(policy));
+		}
+
+		policyMap.put(policy.getName(), policy);
+		PolicyDefinition policyDefinition = new PolicyDefinition();
+		policyDefinition.setName(policy.getName());
+		policyDefinition.setDescription(policy.getDescription());
+		policyDefinition.setDefaultPolicy(policy.isDefaultPolicy());
+		policyDefinitions.add(policyDefinition);
+		
+		// Set first default policy
+		if (defaultPolicy == null && policy.isDefaultPolicy()) {
+			defaultPolicy = policy;
+		}
+	}
+	
+	// TODO Following code is copied from
+	// org.wso2.carbon.stratos.cloud.controller.axiom.AxiomXpathParser
+	// There should be a common util to validate XML using a schema.
+	public void validate(final OMElement omElement, final File schemaFile) throws SAXException, IOException {
+
+		Element sourceElement;
+
+		// if the OMElement is created using DOM implementation use it
+		if (omElement instanceof ElementImpl) {
+			sourceElement = (Element) omElement;
+		} else { // else convert from llom to dom
+			sourceElement = getDOMElement(omElement);
+		}
+
+		// Create a SchemaFactory capable of understanding WXS schemas.
+
+		// Load a WXS schema, represented by a Schema instance.
+		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+		Source source = new StreamSource(schemaFile);
+
+		// Create a Validator object, which can be used to validate
+		// an instance document.
+		Schema schema = factory.newSchema(source);
+		Validator validator = schema.newValidator();
+
+		// Validate the DOM tree.
+		validator.validate(new DOMSource(sourceElement));
+	}
+
+	private Element getDOMElement(final OMElement omElement) {
+
+		// Get the StAX reader from the created element
+		XMLStreamReader llomReader = omElement.getXMLStreamReader();
+
+		// Create the DOOM OMFactory
+		OMFactory doomFactory = DOOMAbstractFactory.getOMFactory();
+
+		// Create the new builder
+		StAXOMBuilder doomBuilder = new StAXOMBuilder(doomFactory, llomReader);
+
+		// Get the document element
+		OMElement newElem = doomBuilder.getDocumentElement();
+
+		return newElem instanceof Element ? (Element) newElem : null;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryCreator.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryCreator.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryCreator.java
new file mode 100644
index 0000000..4a6bb29
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryCreator.java
@@ -0,0 +1,266 @@
+package org.wso2.carbon.adc.mgt.utils;
+
+import com.gitblit.Constants;
+import com.gitblit.models.RepositoryModel;
+import com.gitblit.utils.RpcUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.eclipse.jgit.api.*;
+import org.eclipse.jgit.storage.file.FileRepository;
+import org.eclipse.jgit.transport.CredentialsProvider;
+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+import org.wso2.carbon.adc.mgt.dao.Repository;
+import org.wso2.carbon.adc.mgt.exception.ADCException;
+import org.wso2.carbon.adc.mgt.service.RepositoryInfoBean;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.UUID;
+
+public class RepositoryCreator implements Runnable {
+
+	private static final Log log = LogFactory.getLog(RepositoryCreator.class);
+	private RepositoryInfoBean repoInfoBean;
+
+	public RepositoryCreator(RepositoryInfoBean repoInfoBean) {
+		this.repoInfoBean = repoInfoBean;
+	}
+
+	@Override
+	public void run() {
+
+		if (repoInfoBean != null) {
+			try {
+				createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
+				                 repoInfoBean.getUserName(), repoInfoBean.getPassword());
+				createGitFolderStructure(repoInfoBean.getTenantDomain(),
+				                         repoInfoBean.getCartridgeAlias(),
+				                         repoInfoBean.getDirArray());
+
+			} catch (Exception e) {
+				log.error(e);
+			}
+		}
+	}
+
+    //Creating the internal repo in the same thread as subscribe()
+    public void createInternalRepository () throws Exception {
+
+        if (repoInfoBean != null) {
+            try {
+                createRepository(repoInfoBean.getCartridgeAlias(), repoInfoBean.getTenantDomain(),
+                        repoInfoBean.getUserName(), repoInfoBean.getPassword());
+                
+				if (repoInfoBean.getDirArray() != null && repoInfoBean.getDirArray().length > 0) {
+					createGitFolderStructure(repoInfoBean.getTenantDomain(),
+					                         repoInfoBean.getCartridgeAlias(),
+					                         repoInfoBean.getDirArray());
+				}
+
+            } catch (Exception e) {
+                String errorMsg = "Creating an internal repository failed for tenant " + repoInfoBean.getTenantDomain();
+                log.error(errorMsg, e);
+                throw new Exception(errorMsg, e);
+            }
+        }
+    }
+
+	private Repository createRepository(String cartridgeName, String tenantDomain, String userName, String password)
+	                                                                                               throws Exception {
+
+		Repository repository = new Repository();
+		String repoName = tenantDomain + "/" + cartridgeName;
+
+		try {
+			
+			log.info("Creating internal repo ["+repoName+"] ");
+
+			RepositoryModel model = new RepositoryModel();
+			model.name = repoName;
+			model.accessRestriction = Constants.AccessRestrictionType.VIEW;
+
+			char[] passwordArr = password.toCharArray();
+
+			boolean isSuccess =
+			                    RpcUtils.createRepository(model,
+			                                              "https://localhost:8443/",
+			                                              userName, passwordArr);
+			if (!isSuccess) {
+				throw new Exception("Exception is occurred when creating an internal git repo. ");
+			}
+		} catch (Exception e) {
+			log.error(" Exception is occurred when creating an internal git repo. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		return repository;
+
+	}
+
+	private void createGitFolderStructure(String tenantDomain, String cartridgeName,
+	                                      String[] dirArray) throws Exception {
+		
+		if (log.isDebugEnabled()) {
+			log.debug("Creating git repo folder structure  ");
+		}		
+		
+		String parentDirName = "/tmp/" + UUID.randomUUID().toString();
+		CredentialsProvider credentialsProvider =
+		                                          new UsernamePasswordCredentialsProvider(
+		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
+		                                                                                  System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
+		// Clone
+		// --------------------------
+		FileRepository localRepo = null;
+		try {
+			localRepo = new FileRepository(new File(parentDirName + "/.git"));
+		} catch (IOException e) {
+			log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
+			throw e;
+		}
+
+		Git git = new Git(localRepo);
+
+		CloneCommand cloneCmd =
+		                        git.cloneRepository()
+		                           .setURI("https://localhost:8443/git/" + tenantDomain + "/" +
+		                                           cartridgeName + ".git")
+		                           .setDirectory(new File(parentDirName));
+
+		cloneCmd.setCredentialsProvider(credentialsProvider);
+		try {
+			log.debug("Clonning git repo");
+			cloneCmd.call();
+		} catch (Exception e1) {
+			log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
+			throw e1;
+		}
+		// ------------------------------------
+
+		// --- Adding directory structure --------
+
+		File parentDir = new File(parentDirName);
+		parentDir.mkdir();
+
+		for (String string : dirArray) {
+			String[] arr = string.split("=");
+			if (log.isDebugEnabled()) {
+				log.debug("Creating dir: " + arr[0]);
+			}
+			File parentFile = new File(parentDirName + "/" + arr[0]);
+			parentFile.mkdirs();
+
+			File filess = new File(parentFile, "README");
+			String content = "Content goes here";
+
+			filess.createNewFile();
+			FileWriter fw = new FileWriter(filess.getAbsoluteFile());
+			BufferedWriter bw = new BufferedWriter(fw);
+			bw.write(content);
+			bw.close();
+		}
+		// ----------------------------------------------------------
+
+		// ---- Git status ---------------
+		StatusCommand s = git.status();
+		Status status = null;
+		try {
+			log.debug("Getting git repo status");
+			status = s.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in git status check. Reason: " + e.getMessage());
+			throw e;
+		}
+		// --------------------------------
+
+		// ---------- Git add ---------------
+		AddCommand addCmd = git.add();
+		Iterator<String> it = status.getUntracked().iterator();
+
+		while (it.hasNext()) {
+			addCmd.addFilepattern(it.next());
+		}
+
+		try {
+			log.debug("Adding files to git repo");
+			addCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in adding files. Reason: " + e.getMessage());
+			throw e;
+		}
+		// -----------------------------------------
+
+		// ------- Git commit -----------------------
+
+		CommitCommand commitCmd = git.commit();
+		commitCmd.setMessage("Adding directories");
+
+		try {
+			log.debug("Committing git repo");
+			commitCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in committing . Reason: " + e.getMessage());
+			throw e;
+		}
+		// --------------------------------------------
+
+		// --------- Git push -----------------------
+		PushCommand pushCmd = git.push();
+		pushCmd.setCredentialsProvider(credentialsProvider);
+		try {
+			log.debug("Git repo push");
+			pushCmd.call();
+		} catch (Exception e) {
+			log.error("Exception occurred in Git push . Reason: " + e.getMessage());
+			throw e;
+		}
+
+		try {
+			deleteDirectory(new File(parentDirName));
+		} catch (Exception e) {
+			log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
+			throw e;
+		}
+
+		log.info(" Folder structure  is created ..... ");
+
+	}
+
+	private void handleException(String msg, Exception e) throws Exception {
+		log.error(msg, e);
+		throw new Exception(msg, e);
+	}
+
+	private void deleteDirectory(File file) throws IOException {
+
+		if (file.isDirectory()) {
+			// directory is empty, then delete it
+			if (file.list().length == 0) {
+				file.delete();
+
+			} else {
+				// list all the directory contents
+				String files[] = file.list();
+
+				for (String temp : files) {
+					// construct the file structure
+					File fileDelete = new File(file, temp);
+					// recursive delete
+					deleteDirectory(fileDelete);
+				}
+				// check the directory again, if empty then delete it
+				if (file.list().length == 0) {
+					file.delete();
+				}
+			}
+
+		} else {
+			// if file, then delete it
+			file.delete();
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryFactory.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryFactory.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryFactory.java
new file mode 100644
index 0000000..5f15a1a
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/RepositoryFactory.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.io.File;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.dao.Repository;
+import org.wso2.carbon.adc.mgt.service.ApplicationManagementService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * @author wso2
+ * 
+ */
+public class RepositoryFactory {
+
+	private static final Log log = LogFactory.getLog(ApplicationManagementService.class);
+
+	/*public synchronized Repository createRepository(String cartridgeName, String tenantDomain,
+	                                          String userName) throws Exception {
+
+		Repository repository = new Repository();
+		String repoName = tenantDomain + "/" + cartridgeName; // removed .git part
+		String repoUserName = userName + "@" + tenantDomain;
+
+		Process proc;
+		try {
+
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "manage-git-repo.sh " + "create " + repoUserName + " " +
+			                         tenantDomain + " " + cartridgeName + " " +
+			                         System.getProperty(CartridgeConstants.REPO_NOTIFICATION_URL) + " " +
+			                         System.getProperty(CartridgeConstants.GIT_HOST_NAME) +
+			                         " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script..... command :" + command);
+			proc.waitFor();
+			log.info(" Repo is created ..... for user: " + userName + ", tenantName: " +
+			         tenantDomain + " ");
+			repository.setRepoName("git@" + System.getProperty(CartridgeConstants.GIT_HOST_NAME) + ":" +repoName);
+		} catch (Exception e) {
+			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		return repository;
+
+	}*/
+
+	/*public synchronized void createGitFolderStructure(String tenantDomain, String cartridgeName,
+	                                            String[] dirArray) throws Exception {
+
+		log.info("In create Git folder structure...!");
+
+		StringBuffer dirBuffer = new StringBuffer();
+		for (String dir : dirArray) {
+			dirBuffer.append(dir).append(" ");
+		}
+
+		Process proc;
+		try {
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "git-folder-structure.sh " + tenantDomain + " " +
+			                         cartridgeName + " " + dirBuffer.toString() + " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script..... command : " + command);
+			proc.waitFor();
+
+		} catch (Exception e) {
+			log.error(" Exception is occurred when executing manage-git-repo script. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+		log.info(" Folder structure  is created ..... ");
+
+	}*/
+	
+	public synchronized void destroyRepository(String cartridgeName, String tenantDomain,
+	                                          String userName) throws Exception {
+
+		String repoUserName = userName + "@" + tenantDomain;
+
+		Process proc;
+		try {
+
+			String command =
+			                 CarbonUtils.getCarbonHome() + File.separator + "bin" + File.separator +
+			                         "manage-git-repo.sh " + "destroy " + repoUserName + " " +
+			                         tenantDomain + " " + cartridgeName + 
+			                         " /";
+			proc = Runtime.getRuntime().exec(command);
+			log.info("executing manage-git-repo script (destroy)..... command :" + command);
+			proc.waitFor();
+			log.info(" Repo is destroyed ..... for user: " + userName + ", tenantName: " +
+			         tenantDomain + " ");
+		} catch (Exception e) {
+			log.error(" Exception is occurred when destroying git repo. Reason :" +
+			          e.getMessage());
+			handleException(e.getMessage(), e);
+		}
+
+	}
+
+	private void handleException(String msg, Exception e) throws Exception {
+		log.error(msg, e);
+		throw new Exception(msg, e);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/StratosDBUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/StratosDBUtils.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/StratosDBUtils.java
new file mode 100644
index 0000000..34656c9
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/StratosDBUtils.java
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.utils;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tomcat.jdbc.pool.DataSource;
+import org.apache.tomcat.jdbc.pool.PoolProperties;
+
+public final class StratosDBUtils {
+
+	private static final Log log = LogFactory.getLog(StratosDBUtils.class);
+
+	private static volatile javax.sql.DataSource dataSource = null;
+
+	/**
+	 * Initializes the data source
+	 * 
+	 * @throws RuntimeException
+	 *             if an error occurs while loading DB configuration
+	 */
+	public static void initialize() throws Exception {
+		if (dataSource != null) {
+			return;
+		}
+
+		synchronized (StratosDBUtils.class) {
+			if (dataSource == null) {
+
+				String datasourceName = System.getProperty(CartridgeConstants.DB_DATASOURCE);
+
+				if (datasourceName != null && datasourceName.trim().length() > 0) {
+					if (log.isInfoEnabled()) {
+						log.info("Initializing data source: " + datasourceName);
+					}
+					try {
+						Context ctx = new InitialContext();
+						dataSource = (DataSource) ctx.lookup(datasourceName);
+						if (dataSource != null && log.isInfoEnabled()) {
+							log.info("Found data source: " + datasourceName + ", " + dataSource.getClass().getName());
+						}
+					} catch (NamingException e) {
+						throw new RuntimeException("Error while looking up the data source: " + datasourceName, e);
+					}
+				} else {
+					// FIXME Should we use system properties to get database
+					// details?
+					String dbUrl = System.getProperty(CartridgeConstants.DB_URL);
+					String driver = System.getProperty(CartridgeConstants.DB_DRIVER);
+					String username = System.getProperty(CartridgeConstants.DB_USERNAME);
+					String password = System.getProperty(CartridgeConstants.DB_PASSWORD);
+
+					if (dbUrl == null || driver == null || username == null || password == null) {
+						String msg = "Required DB configuration parameters are not specified.";
+						log.warn(msg);
+						throw new RuntimeException(msg);
+					}
+					
+					if (log.isInfoEnabled()) {
+						log.info("Initializing data source for JDBC URL: " + dbUrl);
+					}
+
+					PoolProperties p = new PoolProperties();
+					p.setUrl(dbUrl);
+					p.setDriverClassName(driver);
+					p.setUsername(username);
+					p.setPassword(password);
+					p.setJmxEnabled(true);
+					p.setTestWhileIdle(false);
+					p.setTestOnBorrow(true);
+					p.setValidationQuery("SELECT 1");
+					p.setTestOnReturn(false);
+					p.setValidationInterval(30000);
+					p.setTimeBetweenEvictionRunsMillis(30000);
+					p.setMaxActive(100);
+					p.setInitialSize(10);
+					p.setMaxWait(10000);
+					p.setRemoveAbandonedTimeout(60);
+					p.setMinEvictableIdleTimeMillis(30000);
+					p.setMinIdle(10);
+					p.setLogAbandoned(true);
+					p.setRemoveAbandoned(true);
+					p.setDefaultAutoCommit(false);
+					p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+							+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
+					DataSource tomcatDatasource = new DataSource();
+					tomcatDatasource.setPoolProperties(p);
+
+					dataSource = tomcatDatasource;
+				}
+
+			}
+		}
+	}
+
+	/**
+	 * Utility method to get a new database connection
+	 * 
+	 * @return Connection
+	 * @throws java.sql.SQLException
+	 *             if failed to get Connection
+	 */
+	public static Connection getConnection() throws SQLException {
+		if (dataSource != null) {
+			return dataSource.getConnection();
+		}
+		throw new SQLException("Datasource is not configured properly.");
+	}
+
+	/**
+	 * Utility method to close the connection streams.
+	 * 
+	 * @param connection
+	 *            Connection
+	 * @param preparedStatement
+	 *            PreparedStatement
+	 * @param resultSet
+	 *            ResultSet
+	 */
+	public static void closeAllConnections(Connection connection, PreparedStatement preparedStatement,
+			ResultSet resultSet) {
+		closeResultSet(resultSet);
+		closeStatement(preparedStatement);
+		closeConnection(connection);
+	}
+
+	public static void closeAllConnections(Connection connection, PreparedStatement... preparedStatements) {
+		for (PreparedStatement preparedStatement : preparedStatements) {
+			closeStatement(preparedStatement);
+		}
+		closeConnection(connection);
+	}
+
+	/**
+	 * Close Connection
+	 * 
+	 * @param dbConnection
+	 *            Connection
+	 */
+	public static void closeConnection(Connection dbConnection) {
+		if (dbConnection != null) {
+			try {
+				dbConnection.close();
+			} catch (SQLException e) {
+				log.warn(
+						"Database error. Could not close database connection. Continuing with " + "others. - "
+								+ e.getMessage(), e);
+			}
+		}
+	}
+
+	/**
+	 * Close ResultSet
+	 * 
+	 * @param resultSet
+	 *            ResultSet
+	 */
+	public static void closeResultSet(ResultSet resultSet) {
+		if (resultSet != null) {
+			try {
+				resultSet.close();
+			} catch (SQLException e) {
+				log.warn("Database error. Could not close ResultSet  - " + e.getMessage(), e);
+			}
+		}
+
+	}
+
+	/**
+	 * Close PreparedStatement
+	 * 
+	 * @param preparedStatement
+	 *            PreparedStatement
+	 */
+	public static void closeStatement(PreparedStatement preparedStatement) {
+		if (preparedStatement != null) {
+			try {
+				preparedStatement.close();
+			} catch (SQLException e) {
+				log.warn(
+						"Database error. Could not close PreparedStatement. Continuing with" + " others. - "
+								+ e.getMessage(), e);
+			}
+		}
+
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/SynchronizeRepositoryRequest.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/SynchronizeRepositoryRequest.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/SynchronizeRepositoryRequest.java
new file mode 100644
index 0000000..c83c77d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/utils/SynchronizeRepositoryRequest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.utils;
+
+import org.apache.axis2.clustering.ClusteringCommand;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.clustering.ClusteringMessage;
+import org.apache.axis2.clustering.management.GroupManagementCommand;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisConfigurator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.core.CarbonAxisConfigurator;
+import org.wso2.carbon.core.internal.CarbonCoreDataHolder;
+import org.wso2.carbon.core.multitenancy.TenantAxisConfigurator;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.deployment.GhostDeployerUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import java.util.UUID;
+
+/**
+ * ClusterMessage for sending a deployment repository synchronization request
+ */
+public class SynchronizeRepositoryRequest extends GroupManagementCommand {
+
+	/**
+     * 
+     */
+	private static final long serialVersionUID = 8717694086109561127L;
+
+	private transient static final Log log = LogFactory.getLog(SynchronizeRepositoryRequest.class);
+	private int tenantId;
+	private String tenantDomain;
+	private UUID messageId;
+
+	public SynchronizeRepositoryRequest() {
+	}
+
+	public SynchronizeRepositoryRequest(int tenantId, String tenantDomain, UUID messageId) {
+		this.tenantId = tenantId;
+		this.tenantDomain = tenantDomain;
+		this.messageId = messageId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public void execute(ConfigurationContext configContext) throws ClusteringFault {
+		log.info("Received  [" + this + "] ");
+		// Run only if the tenant is loaded
+		if (tenantId == MultitenantConstants.SUPER_TENANT_ID ||
+		    TenantAxisUtils.getTenantConfigurationContexts(configContext).get(tenantDomain) != null) {
+			updateDeploymentRepository(configContext);
+			doDeployment(configContext);
+		}
+	}
+
+	private void doDeployment(ConfigurationContext configContext) {
+		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
+		if (axisConfigurator instanceof CarbonAxisConfigurator) {
+			((CarbonAxisConfigurator) axisConfigurator).runDeployment();
+		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
+			((TenantAxisConfigurator) axisConfigurator).runDeployment();
+		}
+	}
+
+	private void updateDeploymentRepository(ConfigurationContext configContext) {
+
+		log.info(" Update Deployment Repo...");
+		/*
+		 * BundleContext bundleContext =
+		 * CarbonCoreDataHolder.getInstance().getBundleContext();
+		 * ServiceReference reference =
+		 * bundleContext.getServiceReference(DeploymentSynchronizer.class.getName
+		 * ());
+		 * if (reference != null) {
+		 * ServiceTracker serviceTracker =
+		 * new ServiceTracker(bundleContext,
+		 * DeploymentSynchronizer.class.getName(), null);
+		 * try {
+		 * serviceTracker.open();
+		 * for (Object obj : serviceTracker.getServices()) {
+		 * // if the update is for worker node with ghost ON, then we will
+		 * update the
+		 * // whole repo for now. See CARBON-13899
+		 * if (GhostDeployerUtils.isGhostOn() && CarbonUtils.isWorkerNode() &&
+		 * tenantId > 0) {
+		 * String repoPath = MultitenantUtils.getAxis2RepositoryPath(tenantId);
+		 * ((DeploymentSynchronizer) obj).update(repoPath, repoPath, 3);
+		 * } else {
+		 * ((DeploymentSynchronizer) obj).update(tenantId);
+		 * }
+		 * }
+		 * } catch (Exception e) {
+		 * log.error("Repository update failed for tenant " + tenantId, e);
+		 * setRepoUpdateFailed(configContext);
+		 * } finally {
+		 * serviceTracker.close();
+		 * }
+		 * }
+		 */
+	}
+
+	private void setRepoUpdateFailed(ConfigurationContext configContext) {
+		AxisConfigurator axisConfigurator = configContext.getAxisConfiguration().getConfigurator();
+		if (axisConfigurator instanceof CarbonAxisConfigurator) {
+			((CarbonAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
+		} else if (axisConfigurator instanceof TenantAxisConfigurator) {
+			((TenantAxisConfigurator) axisConfigurator).setRepoUpdateFailed();
+		}
+	}
+
+	public ClusteringCommand getResponse() {
+		return null;
+	}
+
+	@Override
+	public String toString() {
+		return "SynchronizeRepositoryRequest{" + "tenantId=" + tenantId + ", tenantDomain='" +
+		       tenantDomain + '\'' + ", messageId=" + messageId + '}';
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..923a2a0
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,86 @@
+<!-- ~ Copyright WSO2 Inc. (http://www.wso2.com) All Rights
+	Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, 
+	~ Version 2.0 (the "License"); you may not use this file except ~ in compliance 
+	with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, ~ software 
+	distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the 
+	License for the ~ specific language governing permissions and limitations 
+	~ under the License. -->
+<serviceGroup>
+	<service name="ApplicationManagementService" scope="transportsession">
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Admin service for ADC activities
+		</description>
+		<parameter name="ServiceClass">org.wso2.carbon.adc.mgt.service.ApplicationManagementService
+        </parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">true</parameter>
+		<parameter name="hiddenService" locked="true">true</parameter>
+		<parameter name="AuthorizationAction" locked="true">
+			/permission/admin/manage/modify/webapp    </parameter>
+		<parameter name="DoAuthentication" locked="true">true</parameter>
+	</service>
+
+	<service name="RepoNotificationService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Admin service for receiving git repo update notifications
+		</description>
+		<parameter name="ServiceClass">org.wso2.carbon.adc.mgt.service.RepoNotificationService
+		</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    </parameter>
+	</service>
+
+	<service name="RepositoryInformationService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Exposes information related to internally created
+			repositories
+        </description>
+		<parameter name="ServiceClass">org.wso2.carbon.adc.mgt.service.RepositoryInformationService
+		</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    	</parameter>
+	</service>
+
+	<service name="InstanceInformationManagementService" scope="transportsession">
+		<schema schemaNamespace="http://org.apache.axis2/xsd"
+			elementFormDefaultQualified="true" />
+		<transports>
+			<transport>https</transport>
+		</transports>
+		<description>
+			Exposes information related to internally created
+			repositories
+        </description>
+		<parameter name="ServiceClass">org.wso2.carbon.adc.mgt.service.InstanceInformationManagementService</parameter>
+		<parameter name="enableMTOM">true</parameter>
+		<parameter name="adminService" locked="true">false</parameter>
+		<parameter name="hiddenService" locked="true">false</parameter>
+		<parameter name="AuthorizationAction" locked="false">
+			/permission/admin/manage/modify/webapp
+    	</parameter>
+	</service>
+
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/policies.xsd
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/policies.xsd b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/policies.xsd
new file mode 100644
index 0000000..87f7b58
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/resources/policies.xsd
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<xs:schema attributeFormDefault="unqualified"
+	elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+	<xs:element name="policies">
+		<xs:annotation>
+			<xs:documentation>Use below section to specify auto-scaling policies
+				for cartridges.
+			</xs:documentation>
+		</xs:annotation>
+		<xs:complexType>
+			<xs:sequence>
+				<xs:element name="policy" maxOccurs="unbounded"
+					minOccurs="1">
+					<xs:annotation>
+						<xs:documentation>You can have 1..n policy elements.
+						</xs:documentation>
+					</xs:annotation>
+					<xs:complexType>
+						<xs:sequence>
+							<xs:element type="xs:string" name="description" />
+							<xs:element type="xs:integer" name="min_app_instances" />
+							<xs:element type="xs:integer" name="max_app_instances" />
+							<xs:element type="xs:integer" name="max_requests_per_second" />
+							<xs:element type="xs:decimal" name="alarming_upper_rate" />
+							<xs:element type="xs:decimal" name="alarming_lower_rate" />
+							<xs:element type="xs:decimal" name="scale_down_factor" />
+							<xs:element type="xs:integer" name="rounds_to_average" />
+						</xs:sequence>
+						<xs:attribute type="xs:string" name="name" use="required" />
+						<xs:attribute type="xs:boolean" name="isDefault" use="required" />
+					</xs:complexType>
+				</xs:element>
+			</xs:sequence>
+		</xs:complexType>
+	</xs:element>
+</xs:schema>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/scripts/append_zone_file.sh b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
new file mode 100755
index 0000000..45491df
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/scripts/append_zone_file.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+echo "subdomain $1 and ip $2 added to $3"
+appending_file=$3
+subdomain=$1
+ip=$2
+
+#appending the zone file
+echo $subdomain'\t'IN'\t'A'\t'$ip>> $appending_file
+
+#increasing the count
+for file in $appending_file;
+do
+  if [ -f $file ];
+  then
+    OLD=`egrep -ho "2010-9[0-9]*" $file`
+    NEW=$(($OLD + 1))
+    sed -i "s/$OLD/$NEW/g" $file
+    echo "fixed $file" 
+  fi
+done
+
+
+#reloading bind server
+/etc/init.d/bind9 reload

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/java/org/wso2/carbon/adc/mgt/test/PolicyHolderTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/java/org/wso2/carbon/adc/mgt/test/PolicyHolderTest.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/java/org/wso2/carbon/adc/mgt/test/PolicyHolderTest.java
new file mode 100644
index 0000000..c81fc80
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/java/org/wso2/carbon/adc/mgt/test/PolicyHolderTest.java
@@ -0,0 +1,63 @@
+package org.wso2.carbon.adc.mgt.test;
+
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import junit.framework.TestCase;
+
+import org.wso2.carbon.adc.mgt.utils.PolicyHolder;
+
+public class PolicyHolderTest extends TestCase {
+
+	private PolicyHolder getPolicyHolder(String policiesXMLFile) {
+		File policiesXmlSchema = new File("src/main/resources/policies.xsd");
+		String dir = "src/test/resources/";
+
+		Class<PolicyHolder> clazz = PolicyHolder.class;
+
+		Constructor<PolicyHolder> c;
+		try {
+			c = clazz.getDeclaredConstructor(File.class, File.class);
+			c.setAccessible(true);
+		} catch (NoSuchMethodException e) {
+			throw new RuntimeException(e);
+		} catch (SecurityException e) {
+			throw new RuntimeException(e);
+		}
+		PolicyHolder policyHolder;
+		try {
+			policyHolder = c.newInstance(policiesXmlSchema, new File(dir, policiesXMLFile));
+		} catch (InstantiationException e) {
+			throw new RuntimeException(e);
+		} catch (IllegalAccessException e) {
+			throw new RuntimeException(e);
+		} catch (IllegalArgumentException e) {
+			throw new RuntimeException(e);
+		} catch (InvocationTargetException e) {
+			throw new RuntimeException(e);
+		}
+		return policyHolder;
+	}
+
+	public void testDefaultPolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getDefaultPolicy());
+	}
+	
+	
+	public void testSinglePolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getPolicy("single"));
+		assertEquals("single", policyHolder.getPolicy("single").getName());
+	}
+	
+	public void testElasticPolicy() {
+		PolicyHolder policyHolder = getPolicyHolder("policies-1.xml");
+		assertNotNull(policyHolder);
+		assertNotNull(policyHolder.getPolicy("elastic"));
+		assertEquals("elastic", policyHolder.getPolicy("elastic").getName());
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/log4j.properties b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/log4j.properties
new file mode 100644
index 0000000..a131630
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/log4j.properties
@@ -0,0 +1,8 @@
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Target=System.out
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+#Loggers
+log4j.rootLogger=info, console
+log4j.logger.org.wso2.carbon.adc.mgt=trace
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/policies-1.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/policies-1.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/policies-1.xml
new file mode 100644
index 0000000..7dd37d5
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/test/resources/policies-1.xml
@@ -0,0 +1,22 @@
+<policies>
+	<policy name="single" isDefault="true">
+		<description>Single - Instances: Min 1, Max 1</description>
+		<min_app_instances>1</min_app_instances>
+		<max_app_instances>1</max_app_instances>
+		<max_requests_per_second>5</max_requests_per_second>
+		<alarming_upper_rate>0.7</alarming_upper_rate>
+		<alarming_lower_rate>0.2</alarming_lower_rate>
+		<scale_down_factor>0.25</scale_down_factor>
+		<rounds_to_average>2</rounds_to_average>
+	</policy>
+	<policy name="elastic" isDefault="false">
+		<description>Elastic - Instances: Min 1, Max 4</description>
+		<min_app_instances>1</min_app_instances>
+		<max_app_instances>4</max_app_instances>
+		<max_requests_per_second>5</max_requests_per_second>
+		<alarming_upper_rate>0.7</alarming_upper_rate>
+		<alarming_lower_rate>0.2</alarming_lower_rate>
+		<scale_down_factor>0.25</scale_down_factor>
+		<rounds_to_average>2</rounds_to_average>
+	</policy>
+</policies>
\ No newline at end of file


[39/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/UnsubscribeCommand.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/UnsubscribeCommand.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/UnsubscribeCommand.java
new file mode 100644
index 0000000..80e53f2
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/commands/UnsubscribeCommand.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.commands;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.CommandLineService;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class UnsubscribeCommand implements Command<StratosCommandContext> {
+
+	private static final Logger logger = LoggerFactory.getLogger(UnsubscribeCommand.class);
+	
+	private final Options options;;
+
+	public UnsubscribeCommand() {
+		options = constructOptions();
+	}
+	
+	/**
+	 * Construct Options.
+	 * 
+	 * @return Options expected from command-line.
+	 */
+	private Options constructOptions() {
+		final Options options = new Options();
+		Option forceOption = new Option(CliConstants.FORCE_OPTION, CliConstants.FORCE_LONG_OPTION, false,
+				"Never prompt for confirmation");
+		options.addOption(forceOption);
+		return options;
+	}
+
+	@Override
+	public String getName() {
+		return CliConstants.UNSUBSCRIBE_ACTION;
+	}
+
+	@Override
+	public String getDescription() {
+		return "Unsubscribe from a subscribed cartridge";
+	}
+
+	@Override
+	public String getArgumentSyntax() {
+		return "[Cartridge alias]";
+	}
+
+	@Override
+	public int execute(StratosCommandContext context, String[] args) throws CommandException {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Executing {} command...", getName());
+		}
+		if (args != null && args.length > 0) {
+			String[] remainingArgs = null;
+			String alias = null;
+			boolean force = false;
+			final CommandLineParser parser = new GnuParser();
+			CommandLine commandLine;
+			try {
+				commandLine = parser.parse(options, args);
+				remainingArgs = commandLine.getArgs();
+				if (remainingArgs != null && remainingArgs.length == 1) {
+					// Get alias
+					alias = remainingArgs[0];
+				} else {
+					if (logger.isDebugEnabled()) {
+						logger.debug("Unsubscribe: not enough arguments");
+					}
+					context.getStratosApplication().printUsage(getName());
+					return CliConstants.BAD_ARGS_CODE;
+				}
+
+				if (commandLine.hasOption(CliConstants.FORCE_OPTION)) {
+					if (logger.isTraceEnabled()) {
+						logger.trace("Force option is passed");
+					}
+					force = true;
+				}
+				if (logger.isDebugEnabled()) {
+					logger.debug("Unsubscribing {}, Force Option: {}", alias, force);
+				}
+				if (force || context.getApplication().getConfirmation("Are you sure you want to unsubscribe?")) {
+					System.out.format("Unsubscribing the cartridge %s%n", alias);
+					CommandLineService.getInstance().unsubscribe(alias);
+				}
+				return CliConstants.SUCCESSFUL_CODE;
+			} catch (ParseException e) {
+				if (logger.isErrorEnabled()) {
+					logger.error("Error parsing arguments", e);
+				}
+				System.out.println(e.getMessage());
+				return CliConstants.BAD_ARGS_CODE;
+			}
+		} else {
+			context.getStratosApplication().printUsage(getName());
+			return CliConstants.BAD_ARGS_CODE;
+		}
+	}
+
+	@Override
+	public Options getOptions() {
+		return options;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/completer/CommandCompleter.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/completer/CommandCompleter.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/completer/CommandCompleter.java
new file mode 100644
index 0000000..7344dd3
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/completer/CommandCompleter.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.completer;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import jline.console.completer.ArgumentCompleter;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.text.StrTokenizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wso2.carbon.adc.mgt.cli.Command;
+import org.wso2.carbon.adc.mgt.cli.StratosApplication;
+import org.wso2.carbon.adc.mgt.cli.StratosCommandContext;
+import org.wso2.carbon.adc.mgt.cli.utils.CliConstants;
+
+public class CommandCompleter implements Completer {
+
+	private static final Logger logger = LoggerFactory.getLogger(StratosApplication.class);
+
+	/**
+	 * Keep arguments for each command
+	 */
+	private final Map<String, Collection<String>> argumentMap;
+	
+	private final Completer helpCommandCompleter;
+
+	private final Completer defaultCommandCompleter;
+
+	public CommandCompleter(Map<String, Command<StratosCommandContext>> commands) {
+		if (logger.isDebugEnabled()) {
+			logger.debug("Creating auto complete for {} commands", commands.size());
+		}
+		argumentMap = new HashMap<String, Collection<String>>();
+		defaultCommandCompleter = new StringsCompleter(commands.keySet());
+		helpCommandCompleter = new ArgumentCompleter(new StringsCompleter(CliConstants.HELP_ACTION),
+				defaultCommandCompleter);
+		for (String action : commands.keySet()) {
+			Command<StratosCommandContext> command = commands.get(action);
+			Options commandOptions = command.getOptions();
+			if (commandOptions != null) {
+				if (logger.isDebugEnabled()) {
+					logger.debug("Creating argument completer for command: {}", action);
+				}
+				List<String> arguments = new ArrayList<String>();
+				Collection<?> allOptions = commandOptions.getOptions();
+				for (Object o : allOptions) {
+					Option option = (Option) o;
+					String longOpt = option.getLongOpt();
+					String opt = option.getOpt();
+					if (StringUtils.isNotBlank(longOpt)) {
+						arguments.add("--" + longOpt);
+					} else if (StringUtils.isNotBlank(opt)) {
+						arguments.add("-" + opt);
+					}
+				}
+
+				argumentMap.put(action, arguments);
+			}
+		}
+	}
+
+	@Override
+	public int complete(String buffer, int cursor, List<CharSequence> candidates) {
+		if (logger.isTraceEnabled()) {
+			logger.trace("Buffer: {}, cursor: {}", buffer, cursor);
+			logger.trace("Candidates {}", candidates);
+		}
+		if (StringUtils.isNotBlank(buffer)) {
+			// User is typing a command
+			StrTokenizer strTokenizer = new StrTokenizer(buffer);
+			String action = strTokenizer.next();
+			Collection<String> arguments = argumentMap.get(action);
+			if (arguments != null) {
+				if (logger.isTraceEnabled()) {
+					logger.trace("Arguments found for {}, Tokens: {}", action, strTokenizer.getTokenList());
+					logger.trace("Arguments for {}: {}", action, arguments);
+				}
+				List<String> args = new ArrayList<String>(arguments);
+				List<Completer> completers = new ArrayList<Completer>();
+				for (String token : strTokenizer.getTokenList()) {
+					boolean argContains = arguments.contains(token);
+					if (token.startsWith("-") && !argContains) {
+						continue;
+					}
+					if (argContains) {
+						if (logger.isTraceEnabled()) {
+							logger.trace("Removing argument {}", token);
+						}
+						args.remove(token);
+					}
+					completers.add(new StringsCompleter(token));
+				}
+				completers.add(new StringsCompleter(args));
+				Completer completer = new ArgumentCompleter(completers);
+				return completer.complete(buffer, cursor, candidates);
+			} else if (CliConstants.HELP_ACTION.equals(action)) {
+				// For help action, we need to display available commands as arguments
+				return helpCommandCompleter.complete(buffer, cursor, candidates);
+			}
+		}
+		if (logger.isTraceEnabled()) {
+			logger.trace("Using Default Completer...");
+		}
+		return defaultCommandCompleter.complete(buffer, cursor, candidates);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/exception/CommandException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/exception/CommandException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/exception/CommandException.java
new file mode 100644
index 0000000..691bbd1
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/exception/CommandException.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.exception;
+
+public class CommandException extends Exception {
+
+	private static final long serialVersionUID = 1L;
+
+	public CommandException() {
+	}
+
+	public CommandException(String message) {
+		super(message);
+	}
+
+	public CommandException(Throwable cause) {
+		super(cause);
+	}
+
+	public CommandException(String message, Throwable cause) {
+		super(message, cause);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliConstants.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliConstants.java
new file mode 100644
index 0000000..b2818f6
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliConstants.java
@@ -0,0 +1,111 @@
+package org.wso2.carbon.adc.mgt.cli.utils;
+
+/**
+ * Constants for CLI Tool
+ */
+public class CliConstants {
+
+	public static final String STRATOS_APPLICATION_NAME = "stratos";
+
+	public static final String STRATOS_URL_ENV_PROPERTY = "STRATOS_URL";
+
+	public static final String STRATOS_USERNAME_ENV_PROPERTY = "STRATOS_USERNAME";
+
+	public static final String STRATOS_PASSWORD_ENV_PROPERTY = "STRATOS_PASSWORD";
+
+	public static final String STRATOS_SHELL_PROMPT = "stratos> ";
+	
+	public static final int SUCCESSFUL_CODE = 0;
+	public static final int BAD_ARGS_CODE = 1;
+	public static final int ERROR_CODE = 2;
+
+
+	/**
+	 * The Directory for storing configuration
+	 */
+	public static final String STRATOS_DIR = ".stratos";
+	public static final String STRATOS_HISTORY_DIR = ".history";
+
+	public static final String HELP_ACTION = "help";
+
+	/**
+	 * Subscribe to a cartridge.
+	 */
+	public static final String SUBSCRIBE_ACTION = "subscribe";
+
+	public static final String UNSUBSCRIBE_ACTION = "unsubscribe";
+
+	/**
+	 * List the subscribed cartridges
+	 */
+	public static final String LIST_ACTION = "list";
+
+	/**
+	 * List the available cartridges
+	 */
+	public static final String CARTRIDGES_ACTION = "cartridges";
+
+	/**
+	 * Give information of a cartridge.
+	 */
+	public static final String INFO_ACTION = "info";
+
+	/**
+	 * Synchronize repository
+	 */
+	public static final String SYNC_ACTION = "sync";
+
+	/**
+	 * Domain mapping
+	 */
+	public static final String ADD_DOMAIN_MAPPING_ACTION = "add-domain-mapping";
+	/**
+	 * Remove Domain mapping
+	 */
+	public static final String REMOVE_DOMAIN_MAPPING_ACTION = "remove-domain-mapping";
+	
+	/**
+	 * List the available policies
+	 */
+	public static final String POLICIES_ACTION = "policies";
+
+	/**
+	 * Exit action
+	 */
+	public static final String EXIT_ACTION = "exit";
+
+	public static final String REPO_URL_OPTION = "r";
+	public static final String REPO_URL_LONG_OPTION = "repoURL";
+	
+	public static final String PRIVATE_REPO_OPTION = "i";
+	public static final String PRIVATE_REPO_LONG_OPTION = "privateRepo";
+
+	public static final String USERNAME_OPTION = "u";
+	public static final String USERNAME_LONG_OPTION = "username";
+
+	public static final String PASSWORD_OPTION = "p";
+	public static final String PASSWORD_LONG_OPTION = "password";
+
+	public static final String HELP_OPTION = "h";
+	public static final String HELP_LONG_OPTION = "help";
+	
+	public static final String POLICY_OPTION = "o";
+	public static final String POLICY_LONG_OPTION = "policy";
+	
+	public static final String CONNECT_OPTION = "c";
+	public static final String CONNECT_LONG_OPTION = "connect";
+	
+	public static final String DATA_ALIAS_OPTION = "d";
+	public static final String DATA_ALIAS_LONG_OPTION = "data-alias";
+	
+	public static final String FULL_OPTION = "f";
+	public static final String FULL_LONG_OPTION = "full";
+	
+	public static final String FORCE_OPTION = "f";
+	public static final String FORCE_LONG_OPTION = "force";
+	
+	public static final String TRACE_OPTION = "trace";
+	
+	public static final String DEBUG_OPTION = "debug";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliMessages.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliMessages.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CliMessages.java
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CommandLineUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CommandLineUtils.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CommandLineUtils.java
new file mode 100644
index 0000000..9ef34fe
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/CommandLineUtils.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.utils;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+public class CommandLineUtils {
+	
+	private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("Resources");
+
+	public static <T> void printTable(T[] data, RowMapper<T> mapper, String... headers) {
+		if (data == null) {
+			return;
+		}
+		// The maximum number of columns
+		// All data String[] length must be equal to this
+		int columns = headers.length;
+		int rows = data.length + 1;
+
+		String[][] table = new String[rows][columns];
+		table[0] = headers;
+
+		for (int i = 0; i < data.length; i++) {
+			T t = data[i];
+			table[i + 1] = mapper.getData(t);
+		}
+
+		// Find the maximum length of a string in each column
+		int[] lengths = new int[columns];
+		for (int i = 0; i < table.length; i++) {
+			for (int j = 0; j < table[i].length; j++) {
+				lengths[j] = Math.max(table[i][j].length(), lengths[j]);
+			}
+		}
+
+		// The border rows
+		String borders[] = new String[lengths.length];
+		// Generate a format string for each column
+		String[] formats = new String[lengths.length];
+		for (int i = 0; i < lengths.length; i++) {
+			StringBuilder stringBuilder = new StringBuilder();
+			stringBuilder.append("+");
+			for (int j = 0; j < lengths[i] + 2; j++) {
+				stringBuilder.append("-");
+			}
+			boolean finalColumn = (i + 1 == lengths.length);
+			if (finalColumn) {
+				stringBuilder.append("+\n");
+			}
+			borders[i] = stringBuilder.toString();
+			formats[i] = "| %1$-" + lengths[i] + "s " + (finalColumn ? "|\n" : "");
+		}
+
+		// Print the table
+		for (int i = 0; i < table.length; i++) {
+			for (int j = 0; j < table[i].length; j++) {
+				System.out.print(borders[j]);
+			}
+			for (int j = 0; j < table[i].length; j++) {
+				System.out.format(formats[j], table[i][j]);
+			}
+			if (i + 1 == table.length) {
+				for (int j = 0; j < table[i].length; j++) {
+					System.out.print(borders[j]);
+				}
+			}
+		}
+	}
+	
+	public static String getMessage(String key, Object... args) {
+		String message = BUNDLE.getString(key);
+		if (args != null && args.length > 0) {
+			message = MessageFormat.format(message, args);
+		}
+		return message;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/RowMapper.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/RowMapper.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/RowMapper.java
new file mode 100644
index 0000000..a181a3c
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/utils/RowMapper.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli.utils;
+
+public interface RowMapper<T> {
+	String[] getData(T t);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
new file mode 100644
index 0000000..fcec66f
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/Resources.properties
@@ -0,0 +1,25 @@
+
+
+cannot.list.available.cartridges=An error occurred when getting available cartridges.
+cannot.list.subscribed.cartridges=An error occurred when getting subscribed cartridges.
+cannot.get.cartridge.info=An error occurred when getting cartridge information.
+cannot.syncrepo=Synchronization failed
+cannot.subscribe=Subscribe failed
+cannot.unsubscribe=Unsubscribe failed
+cannot.mapdomain=Map Domain failed
+cannot.removedomain=Mapped Domain removal failed
+
+notsubscribed.error=You have not subscribed to {0}
+domainmapping.exists.error=The domain mapping {0} already exists for {1}
+
+cartridge.notregistered=Cartridge {0} is not registered
+cartridge.invalid.alias=The provided cartridge alias is not valid. The alias can contain only lowercase characters and numbers.
+cartridge.already.subscribed=You have already subscribed for cartridge type {0}
+cartridge.alias.duplicate=Duplicate cartridge alias {0}
+
+policy.error=Could not load policy.
+repository.required=An external repository required
+repository.credentials.required=Username and Password are required for the repository: {0}
+repository.transport.error=Error connecting to the repository: {0}
+repository.invalid.error=Invalid repository: {0}
+remote.error=Error connecting to back-end service.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
new file mode 100755
index 0000000..958eb9c
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/log4j.properties
@@ -0,0 +1,15 @@
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Target=System.out
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+log4j.appender.file=org.apache.log4j.RollingFileAppender
+log4j.appender.file.File=${user.home}/.stratos/.stratos-cli.log
+log4j.appender.file.MaxFileSize=10MB
+log4j.appender.file.MaxBackupIndex=100
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} [%t] %n%m%n
+
+#Loggers
+log4j.rootLogger=info, file
+log4j.logger.org.wso2.carbon.adc.mgt.cli=info
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks
new file mode 100644
index 0000000..7942c53
Binary files /dev/null and b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/resources/wso2carbon.jks differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/pom.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/pom.xml
new file mode 100644
index 0000000..7c22921
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/pom.xml
@@ -0,0 +1,87 @@
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<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.wso2.carbon</groupId>
+        <artifactId>adc-mgt</artifactId>
+        <version>2.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.adc.mgt.repository.synchronizer</artifactId>
+    <version>2.1.1</version>
+    <name>Repository Synchronizer</name>
+    <description>Repository Synchronizer</description>
+    <packaging>war</packaging>
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.5</source>
+                    <target>1.5</target>
+                </configuration>
+                <version>2.3.2</version>
+            </plugin>
+            <plugin>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>2.2</version>
+                <configuration>                     
+                    <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
+                    <warName>${project.artifactId}</warName>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-transports-http</artifactId>
+            <version>2.6.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
+            <version>2.6.2</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-httpclient</groupId>
+            <artifactId>commons-httpclient</artifactId>
+            <version>3.1</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.ws.rs</groupId>
+            <artifactId>jsr311-api</artifactId>
+            <version>1.1.1</version>
+        </dependency>
+        <dependency>
+        <groupId>net.sf.json-lib</groupId>
+        <artifactId>json-lib</artifactId>
+        <version>2.4</version>
+        <classifier>jdk15</classifier>
+    </dependency>
+            
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/wso2/carbon/adc/mgt/reposync/service/RepositorySynchronizer.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/wso2/carbon/adc/mgt/reposync/service/RepositorySynchronizer.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/wso2/carbon/adc/mgt/reposync/service/RepositorySynchronizer.java
new file mode 100644
index 0000000..7224253
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/java/org/wso2/carbon/adc/mgt/reposync/service/RepositorySynchronizer.java
@@ -0,0 +1,37 @@
+/**
+ * 
+ */
+package org.wso2.carbon.adc.mgt.reposync.service;
+
+import java.util.Map;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.MediaType;
+
+import net.sf.json.JSONObject;
+
+/**
+ * @author wso2
+ * 
+ */
+@Path("/reposyncservice/")
+public class RepositorySynchronizer {
+
+	@POST
+	@Path("/notify/")
+	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+	public void execute(@FormParam("payload") String payload) {
+		Map jsonObject = JSONObject.fromObject(payload);
+		System.out.println("Printing......");
+		Map repoMap = (Map) jsonObject.get("repository");
+		System.out.println("-------------");
+		System.out.println("Repo URL : " + repoMap.get("url"));
+		System.out.println("-------------");
+		System.out.println("-------------");
+		System.out.println("-------------");
+		System.out.println("---JSON customer : " + payload);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
new file mode 100644
index 0000000..7b0f718
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
+       xsi:schemaLocation="
+         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
+         http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
+
+    <jaxrs:server id="repoSynchronizer" address="/notify">
+        <jaxrs:serviceBeans>
+            <ref bean="serviceBean"/>
+        </jaxrs:serviceBeans>
+    </jaxrs:server>
+
+    <bean id="serviceBean" class="org.wso2.carbon.adc.mgt.reposync.service.RepositorySynchronizer"/>
+</beans>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..696d5cc
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
+         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
+
+    <display-name>JAX-WS/JAX-RS Webapp</display-name>
+
+    <servlet>
+        <servlet-name>JAXServlet</servlet-name>
+        <display-name>JAX-WS/JAX-RS Servlet</display-name>
+        <description>JAX-WS/JAX-RS Endpoint</description>
+        <servlet-class>
+            org.apache.cxf.transport.servlet.CXFServlet
+        </servlet-class>
+        <init-param>
+            <param-name>service-list-stylesheet</param-name>
+            <param-value>servicelist.css</param-value>
+        </init-param>
+        <load-on-startup>1</load-on-startup>
+    </servlet>
+
+    <servlet-mapping>
+        <servlet-name>JAXServlet</servlet-name>
+        <url-pattern>/services/*</url-pattern>
+    </servlet-mapping>
+
+    <session-config>
+        <session-timeout>60</session-timeout>
+    </session-config>
+
+</web-app>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
new file mode 100644
index 0000000..bbc4987
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.repository.synchronizer/2.1.1/src/main/webapp/servicelist.css
@@ -0,0 +1,117 @@
+@CHARSET "ISO-8859-1";
+
+/* http://meyerweb.com/eric/tools/css/reset/ 
+   v2.0 | 20110126
+   License: none (public domain)
+*/
+
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed, 
+figure, figcaption, footer, header, hgroup, 
+menu, nav, output, ruby, section, summary,
+time, mark, audio, video {
+	margin: 0;
+	padding: 0;
+	border: 0;
+	font-size: 100%;
+	font: inherit;
+	vertical-align: baseline;
+}
+/* HTML5 display-role reset for older browsers */
+article, aside, details, figcaption, figure, 
+footer, header, hgroup, menu, nav, section {
+	display: block;
+}
+
+html {
+	background: #efefef;
+}
+
+body {
+	line-height: 1;
+	width:960px;
+	margin:auto;
+	background:white;
+	padding:10px;
+	box-shadow:0px 0px 5px #CCC;
+	font-family:"Lucida Grande","Lucida Sans","Microsoft Sans Serif", "Lucida Sans Unicode","Verdana","Sans-serif","trebuchet ms" !important;
+	
+}
+ol, ul {
+	list-style: none;
+}
+blockquote, q {
+	quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+	content: '';
+	content: none;
+}
+table {
+	border-collapse: collapse;
+	border-spacing: 0;
+	width:960px;
+	border:solid 1px #ccc;
+}
+
+table a {
+	font-size:12px;
+	color:#1e90ff;
+	padding:7px;
+float:left;	
+;
+}
+
+.heading {
+	font-size: 18px;
+	margin-top: 20px;
+	float:left;
+	color:#0067B1;
+	margin-bottom:20px;
+	padding-top:20px;
+}
+
+.field {
+	font-weight: normal;
+	width:120px;
+	font-size:12px;
+	float:left;
+	padding:7px;
+	clear:left;
+}
+.value {
+	font-weight: bold;
+	font-size:12px;
+	float:left;
+	padding:7px;
+	clear:right;
+}
+.porttypename {
+	font-weight: bold;
+	font-size:14px;
+}
+UL {
+	margin-top: 0;
+}
+LI {
+	font-weight: normal;
+	font-size:12px;
+	margin-top:10px;
+}
+
+TD {
+	border:1px solid #ccc;
+	vertical-align: text-top;
+	padding: 5px;
+}
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/pom.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/pom.xml
new file mode 100644
index 0000000..fe5c33b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/pom.xml
@@ -0,0 +1,134 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
+	Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); 
+	~ you may not use this file except in compliance with the License. ~ You 
+	may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, software ~ 
+	distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the 
+	License for the specific language governing permissions and ~ limitations 
+	under the License. -->
+
+<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.wso2.carbon</groupId>
+		<artifactId>adc-mgt</artifactId>
+		<version>2.1.0</version>
+		<relativePath>../../pom.xml</relativePath>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.wso2.carbon.adc.mgt</artifactId>
+	<version>2.1.3</version>
+	<packaging>bundle</packaging>
+	<name>WSO2 Carbon - ADC BE</name>
+	<description>BE functionalities of ADC</description>
+	<url>http://wso2.org</url>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.registry.ws.client</artifactId>
+		</dependency>
+		<!--<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> 
+			</dependency> -->
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub</artifactId>
+			<version>4.1.3</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.topology.mgt</artifactId>
+			<version>2.1.1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.utils</artifactId>
+		</dependency>
+
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.cartridge.agent.stub</artifactId>
+			<version>4.1.1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>org.apache.tomcat.wso2</groupId>
+			<artifactId>jdbc-pool</artifactId>
+			<version>${version.tomcat}.wso2v1</version>
+		</dependency>
+
+		<dependency>
+			<groupId>com.gitblit</groupId>
+			<artifactId>gitblit</artifactId>
+			<version>1.2.0.wso2v1</version>
+		</dependency>
+		<dependency>
+			<groupId>com.google.code.gson</groupId>
+			<artifactId>gson</artifactId>
+			<version>2.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.jgit</groupId>
+            <artifactId>org.eclipse.jgit</artifactId>
+            <version>2.1.0.wso2v1</version>
+        </dependency>
+        <dependency>
+            <groupId>com.jcraft</groupId>
+            <artifactId>jsch</artifactId>
+            <version>0.1.49.wso2v1</version>
+        </dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<scope>test</scope>
+		</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>
+						<Bundle-Activator>
+							org.wso2.carbon.adc.mgt.internal.HostingManagementActivator
+                                                </Bundle-Activator>
+						<Private-Package>org.wso2.carbon.adc.mgt.internal.*</Private-Package>
+						<Export-Package>
+							org.wso2.carbon.adc.mgt.utils*,
+							org.wso2.carbon.adc.mgt.service.*,
+							org.wso2.carbon.adc.mgt.*
+                        			</Export-Package>
+						<Import-Package>
+							org.apache.axis2.*; version="1.6.1.wso2v6",
+							org.apache.axiom.*;
+							version="1.2.11.wso2v2",
+							org.apache.neethi.*;
+							version="2.0.4.wso2v4",
+							javax.xml.stream.*; version="1.0.1",
+							javax.wsdl.*; version="1.6.2",
+							org.osgi.framework.*,
+							*;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/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/cartridge-config.properties
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/cartridge-config.properties b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/cartridge-config.properties
new file mode 100644
index 0000000..b495014
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/cartridge-config.properties
@@ -0,0 +1,38 @@
+# Configuration properties
+
+sc.ip=s2_ip
+autoscalerService.url=https://cc.wso2.com:9444/services/CloudControllerService/
+autoscaler.time.out=190000
+cartridge.agent.epr=https://s2_ip:9447/services/CartridgeAgentService
+git.host.name=s2_hostname
+git.host.ip=s2_ip
+git.repo.notification.url=https://sc.wso2.com:9445/services/RepoNotificationService/
+identity.server.url=https://sc.wso2.com:9447/services/RepoNotificationService/
+
+adc.jdbc.url=jdbc:h2:repository/database/WSO2S2_DB
+adc.jdbc.username=wso2carbon
+adc.jdbc.password=wso2carbon
+adc.jdbc.driver=org.h2.Driver
+
+mb.server.ip=cc.wso2.com:5673
+
+feature.externalrepo.validation.enabled=true
+feature.internalrepo.enabled=false
+feature.multitenant.multiplesubscription.enabled=false
+
+internal.repo.username=admin
+internal.repo.password=admin
+
+append.script=SCRIPT_PATH/add_entry_zone_file.sh
+remove.script=SCRIPT_PATH/remove_entry_zone_file.sh
+bind.file.path=/etc/bind/db.STRATOS_DOMAIN
+elb.ip=s2_ip
+
+bam.ip=s2_ip
+bam.port=7714
+
+max.attempts=1000
+
+cartridge.key=KEYPATH
+
+repository.info.epr=https://s2_ip:9445/services/RepositoryInformationService

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
new file mode 100644
index 0000000..12bbf74
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/conf/tenant-resource-policy.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8"?>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CartridgeAgentClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CartridgeAgentClient.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CartridgeAgentClient.java
new file mode 100644
index 0000000..4834f29
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CartridgeAgentClient.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.client;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.stub.CartridgeAgentServiceStub;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+
+public class CartridgeAgentClient {
+
+	private static final Log log = LogFactory.getLog(CartridgeAgentClient.class);
+	CartridgeAgentServiceStub stub = null;
+	public CartridgeAgentClient(String epr) throws AxisFault {
+	  ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
+	  stub = new CartridgeAgentServiceStub(clientConfigContext, epr);
+    }
+	
+	public void unregister(String domain, String subDomain, String hostName) throws Exception {
+		log.info(" ** Unregistering -- ");
+		stub.unregister(domain, subDomain, hostName);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CloudControllerServiceClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CloudControllerServiceClient.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CloudControllerServiceClient.java
new file mode 100644
index 0000000..e6dfb4a
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/CloudControllerServiceClient.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.client;
+
+import java.rmi.RemoteException;
+
+import javax.activation.DataHandler;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.exception.UnregisteredCartridgeException;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceStub;
+import org.wso2.carbon.stratos.cloud.controller.stub.CloudControllerServiceUnregisteredCartridgeExceptionException;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.CartridgeInfo;
+import org.wso2.carbon.stratos.cloud.controller.util.xsd.Properties;
+
+public class CloudControllerServiceClient {
+
+	private CloudControllerServiceStub stub;
+
+	private static final Log log = LogFactory.getLog(CloudControllerServiceClient.class);
+
+	public CloudControllerServiceClient(String epr) throws AxisFault {
+
+		ConfigurationContext clientConfigContext = DataHolder.getClientConfigContext();
+		try {
+			stub = new CloudControllerServiceStub(clientConfigContext, epr);
+			stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
+
+		} catch (AxisFault axisFault) {
+			String msg = "Failed to initiate AutoscalerService client. " + axisFault.getMessage();
+			log.error(msg, axisFault);
+			throw new AxisFault(msg, axisFault);
+		}
+
+	}
+
+	public boolean register(String domainName, String subDomain, String cartridgeType,
+	                        DataHandler payload, String tenantRange, String hostName, Properties properties) throws RemoteException, CloudControllerServiceUnregisteredCartridgeExceptionException
+	                                                                                  {		
+		return stub.registerService(domainName, subDomain, tenantRange, cartridgeType, hostName,
+		                            properties, payload);
+
+	}
+
+	public String startInstance(String domain, String subDomain) throws Exception {
+		return stub.startInstance(domain, subDomain);
+	}
+
+	public boolean terminateAllInstances(String domain, String subDomain) throws Exception {
+		return stub.terminateAllInstances(domain, subDomain);
+	}
+
+	public String[] getRegisteredCartridges() throws Exception {
+		return stub.getRegisteredCartridges();
+	}
+
+	public boolean createKeyPair(String cartridge, String keyPairName, String publicKey)
+	                                                                                    throws Exception {
+		return stub.createKeyPairFromPublicKey(cartridge, keyPairName, publicKey);
+	}
+
+	public CartridgeInfo getCartridgeInfo(String cartridgeType) throws UnregisteredCartridgeException, Exception {
+		try {
+			return stub.getCartridgeInfo(cartridgeType);
+		} catch (RemoteException e) {
+			throw e;
+		} catch (CloudControllerServiceUnregisteredCartridgeExceptionException e) {
+			throw new UnregisteredCartridgeException("Not a registered cartridge " + cartridgeType, cartridgeType, e);
+		}
+	}
+	
+	public boolean unregisterService(String domain, String subDomain) throws Exception {
+	    return stub.unregisterService(domain, subDomain);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/RegistryClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/RegistryClient.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/RegistryClient.java
new file mode 100644
index 0000000..899e3ff
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/client/RegistryClient.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.client;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.UUID;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.commons.io.IOUtils;
+import org.wso2.carbon.registry.core.Association;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
+
+public class RegistryClient {
+
+	// url where the repository is running its services interface
+	private static String backendURL = "http://localhost:9763/services/";
+	private static ConfigurationContext configContext = null;
+
+	// configuration locations used to bootstrap axis2
+	private static String axis2Repo =
+	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2";
+	private static String axis2Conf =
+	                                  "/home/wso2/Desktop/HP-demo-packs-with-video/cartridge/wso2stratos-cartridge-1.0.0-SNAPSHOT/repository/conf/axis2/axis2_client.xml";
+	private static String serverURL = "https://localhost:9443/services/";
+
+	public RegistryClient() {
+		// TODO Auto-generated constructor stub
+	}
+
+	private static WSRegistryServiceClient initialize() throws Exception {
+		// set these properties, this is used for authentication over https to
+		// the registry
+		// if you have a newer version, you can update the keystore by copying
+		// it from
+		// the security directory of the repository
+		System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
+		System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
+
+		configContext =
+		                ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Repo,
+		                                                                                     axis2Conf);
+		return new WSRegistryServiceClient(serverURL, "admin", "admin", backendURL, configContext);
+	}
+
+	public static void addKey(String keyName, String content) throws Exception {
+		Registry registry = initialize();
+
+		// get the governance folder
+		Resource governanceFolder = registry.get("/_system/governance");
+		System.out.println("Folder description: " + governanceFolder.getDescription());
+		Resource r1 = registry.newResource();
+		String path = "/_system/governance/" + keyName;
+		r1.setContent(content);
+		registry.put(path, r1);
+
+		/*
+		 * List<Resource> paths = getServicePath(registry,
+		 * "/_system/governance/trunk/services");
+		 * 
+		 * for (Resource service : paths) { // we've got all the services here
+		 * 
+		 * Properties props = service.getProperties(); for (Object prop :
+		 * props.keySet()) { System.out.println(prop + " - " + props.get(prop));
+		 * }
+		 * 
+		 * Association[] associations =
+		 * registry.getAssociations(service.getPath(), "Documentation"); for
+		 * (Association association : associations) {
+		 * System.out.println(association.getAssociationType()); } }
+		 */
+	}
+
+	private static List<Resource> getServicePath(Registry registry, String servicesResource)
+	                                                                                        throws RegistryException {
+		List<Resource> result = new ArrayList<Resource>();
+		Resource resource = registry.get(servicesResource);
+
+		if (resource instanceof Collection) {
+			Object content = resource.getContent();
+			for (Object path : (Object[]) content) {
+				result.addAll(getServicePath(registry, (String) path));
+			}
+		} else if (resource instanceof Resource) {
+			result.add(resource);
+		}
+		return result;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/custom/domain/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/custom/domain/RegistryManager.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/custom/domain/RegistryManager.java
new file mode 100644
index 0000000..0caad62
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/custom/domain/RegistryManager.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.custom.domain;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.exception.ADCException;
+import org.wso2.carbon.adc.mgt.exception.DomainMappingExistsException;
+import org.wso2.carbon.adc.mgt.internal.DataHolder;
+import org.wso2.carbon.adc.mgt.utils.CartridgeConstants;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+
+public class RegistryManager {
+	private static Log log = LogFactory.getLog(RegistryManager.class);
+	private static Registry registry = DataHolder.getRegistry();
+
+	public RegistryManager() {
+		try {
+			if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO)) {
+				registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO,
+				                    registry.newCollection());
+			}
+		} catch (RegistryException e) {
+			String msg =
+			             "Error while accessing registry or initializing domain mapping registry path\n";
+			log.error(msg + e.getMessage());
+		}
+	}
+
+	/**
+    *
+    */
+    public void addDomainMappingToRegistry(String hostName, String actualHost)
+            throws ADCException, RegistryException, DomainMappingExistsException {
+        try {
+            registry.beginTransaction();
+            Resource hostResource = registry.newResource();
+            hostResource.addProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST, actualHost);
+            if (!registry.resourceExists(CartridgeConstants.DomainMappingInfo.HOSTINFO +
+                                                hostName)) {
+                registry.put(CartridgeConstants.DomainMappingInfo.HOSTINFO + hostName,
+                                    hostResource);
+            } else {
+                registry.rollbackTransaction();
+                String msg = "Requested domain is already taken!";
+                log.error(msg);
+                throw new DomainMappingExistsException(msg, hostName);
+            }
+            registry.commitTransaction();
+        } catch (RegistryException e) {
+            registry.rollbackTransaction();
+            throw e; 
+        }
+    }
+
+
+    /**
+        *
+        */
+   	public void removeDomainMappingFromRegistry(String actualHost) throws Exception {
+   		try {
+               registry.beginTransaction();
+                String hostResourcePath = CartridgeConstants.DomainMappingInfo.HOSTINFO;
+                if (registry.resourceExists(hostResourcePath)) {
+                    Resource hostResource = registry.get(hostResourcePath);
+                    Collection hostInfoCollection;
+                    if(hostResource instanceof Collection){
+                        hostInfoCollection = (Collection) hostResource;
+                    } else {
+                        throw new Exception("Resource is not a collection " + hostResourcePath );
+                    }
+                    String[] paths = hostInfoCollection.getChildren();
+                    for (String path: paths){
+                        Resource domainMapping = registry.get(path);
+                        String actualHostInRegistry = domainMapping.getProperty(CartridgeConstants.DomainMappingInfo.ACTUAL_HOST);
+                        if(actualHostInRegistry != null && actualHost.equalsIgnoreCase(actualHostInRegistry)){
+                            registry.delete(path);
+                        }
+                    }
+                }
+                registry.commitTransaction();
+   		} catch (RegistryException e) {
+   			registry.rollbackTransaction();
+   			log.error("Unable to remove the mapping", e);
+   			throw e;
+   		}
+   	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/CartridgeSubscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/CartridgeSubscription.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/CartridgeSubscription.java
new file mode 100644
index 0000000..5eaed90
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/CartridgeSubscription.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dao;
+
+import java.util.List;
+
+public class CartridgeSubscription {
+
+	private int subscriptionId;
+	private int tenantId;
+	private String cartridge;
+	private String provider;
+	private String hostName;
+	private String policy;
+	private List<PortMapping> portMappings;
+	private String clusterDomain;
+	private String clusterSubdomain;
+	private Repository repository;
+	private String state;
+	private String alias;
+	private String tenantDomain;
+	private DataCartridge dataCartridge;
+	private String baseDirectory;
+	private String mappedDomain;
+	private String mgtClusterDomain;
+	private String mgtClusterSubDomain;
+
+	public int getSubscriptionId() {
+		return subscriptionId;
+	}
+
+	public void setSubscriptionId(int subscriptionId) {
+		this.subscriptionId = subscriptionId;
+	}
+
+	public int getTenantId() {
+		return tenantId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public String getCartridge() {
+		return cartridge;
+	}
+
+	public void setCartridge(String cartridge) {
+		this.cartridge = cartridge;
+	}
+
+	public String getProvider() {
+		return provider;
+	}
+
+	public void setProvider(String provider) {
+		this.provider = provider;
+	}
+
+	public String getHostName() {
+		return hostName;
+	}
+
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+
+	public String getPolicy() {
+		return policy;
+	}
+
+	public void setPolicy(String policy) {
+		this.policy = policy;
+	}
+
+	public List<PortMapping> getPortMappings() {
+		return portMappings;
+	}
+
+	public void setPortMappings(List<PortMapping> portMappings) {
+		this.portMappings = portMappings;
+	}
+
+	public String getClusterDomain() {
+		return clusterDomain;
+	}
+
+	public void setClusterDomain(String clusterDomain) {
+		this.clusterDomain = clusterDomain;
+	}
+
+	public String getClusterSubdomain() {
+		return clusterSubdomain;
+	}
+
+	public void setClusterSubdomain(String clusterSubdomain) {
+		this.clusterSubdomain = clusterSubdomain;
+	}
+
+	public Repository getRepository() {
+		return repository;
+	}
+
+	public void setRepository(Repository repository) {
+		this.repository = repository;
+	}
+
+	public String getState() {
+		return state;
+	}
+
+	public void setState(String state) {
+		this.state = state;
+	}
+
+	public String getAlias() {
+		return alias;
+	}
+
+	public void setAlias(String alias) {
+		this.alias = alias;
+	}
+
+	public String getTenantDomain() {
+		return tenantDomain;
+	}
+
+	public void setTenantDomain(String tenantDomain) {
+		this.tenantDomain = tenantDomain;
+	}
+
+	public DataCartridge getDataCartridge() {
+		return dataCartridge;
+	}
+
+	public void setDataCartridge(DataCartridge dataCartridge) {
+		this.dataCartridge = dataCartridge;
+	}
+
+	public String getBaseDirectory() {
+		return baseDirectory;
+	}
+
+	public void setBaseDirectory(String baseDirectory) {
+		this.baseDirectory = baseDirectory;
+	}
+
+	public String getMappedDomain() {
+		return mappedDomain;
+	}
+
+	public void setMappedDomain(String mappedDomain) {
+		this.mappedDomain = mappedDomain;
+	}
+
+	public String getMgtClusterDomain() {
+		return mgtClusterDomain;
+	}
+
+	public void setMgtClusterDomain(String mgtClusterDomain) {
+		this.mgtClusterDomain = mgtClusterDomain;
+	}
+
+	public String getMgtClusterSubDomain() {
+		return mgtClusterSubDomain;
+	}
+
+	public void setMgtClusterSubDomain(String mgtClusterSubDomain) {
+		this.mgtClusterSubDomain = mgtClusterSubDomain;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/DataCartridge.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/DataCartridge.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/DataCartridge.java
new file mode 100644
index 0000000..3bc22b6
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/DataCartridge.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dao;
+
+public class DataCartridge {
+
+	private int id;
+	private String dataCartridgeType;
+	private String userName;
+	private String password;
+	public int getId() {
+    	return id;
+    }
+	public void setId(int id) {
+    	this.id = id;
+    }
+	public String getDataCartridgeType() {
+    	return dataCartridgeType;
+    }
+	public void setDataCartridgeType(String dataCartridgeType) {
+    	this.dataCartridgeType = dataCartridgeType;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String getPassword() {
+    	return password;
+    }
+	public void setPassword(String password) {
+    	this.password = password;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/PortMapping.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/PortMapping.java
new file mode 100644
index 0000000..70c9222
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/PortMapping.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dao;
+
+public class PortMapping {
+	private int id;
+	private String type;
+	private String primaryPort;
+	private String proxyPort;
+
+	public int getId() {
+		return id;
+	}
+
+	public void setId(int id) {
+		this.id = id;
+	}
+
+	public String getType() {
+		return type;
+	}
+
+	public void setType(String type) {
+		this.type = type;
+	}
+
+	public String getPrimaryPort() {
+		return primaryPort;
+	}
+
+	public void setPrimaryPort(String primaryPort) {
+		this.primaryPort = primaryPort;
+	}
+
+	public String getProxyPort() {
+		return proxyPort;
+	}
+
+	public void setProxyPort(String proxyPort) {
+		this.proxyPort = proxyPort;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/Repository.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/Repository.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/Repository.java
new file mode 100644
index 0000000..a5bf31d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/Repository.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dao;
+
+public class Repository {
+	private int repoId;
+	private String repoName;
+    private String repoUserName;
+    private String repoUserPassword;
+
+	public int getRepoId() {
+		return repoId;
+	}
+
+	public void setRepoId(int repoId) {
+		this.repoId = repoId;
+	}
+
+	public String getRepoName() {
+		return repoName;
+	}
+
+	public void setRepoName(String repoName) {
+		this.repoName = repoName;
+	}
+
+    public String getRepoUserName() {
+        return repoUserName;
+    }
+
+    public void setRepoUserName(String repoUserName) {
+        this.repoUserName=repoUserName;
+    }
+
+    public String getRepoUserPassword() {
+        return repoUserPassword;
+    }
+
+    public void setRepoUserPassword(String repoUserPassword) {
+        this.repoUserPassword=repoUserPassword;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/RepositoryCredentials.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/RepositoryCredentials.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/RepositoryCredentials.java
new file mode 100644
index 0000000..ca1af6b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dao/RepositoryCredentials.java
@@ -0,0 +1,27 @@
+package org.wso2.carbon.adc.mgt.dao;
+
+public class RepositoryCredentials {
+
+	private String url;
+	private String userName;
+	private String password;
+	public String getUrl() {
+    	return url;
+    }
+	public void setUrl(String url) {
+    	this.url = url;
+    }
+	public String getUserName() {
+    	return userName;
+    }
+	public void setUserName(String userName) {
+    	this.userName = userName;
+    }
+	public String getPassword() {
+    	return password;
+    }
+	public void setPassword(String password) {
+    	this.password = password;
+    }
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dns/DNSManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dns/DNSManager.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dns/DNSManager.java
new file mode 100644
index 0000000..56b340b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dns/DNSManager.java
@@ -0,0 +1,86 @@
+ /*
+  * Copyright WSO2, Inc. (http://wso2.com)
+  *
+  * Licensed under the Apache License, Version 2.0 (the "License");
+  * you may not use this file except in compliance with the License.
+  * You may obtain a copy of the License at
+  *
+  * http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+
+package org.wso2.carbon.adc.mgt.dns;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.utils.CartridgeConstants;
+
+/**
+ * This class is for handling dns entries.
+ */
+public class DNSManager {
+	private static final Log log = LogFactory.getLog(DNSManager.class);
+
+    /**
+   	 * This is get called when there is a need of adding new sub domain to
+   	 * exciting domain.
+   	 * It will append required text to bind9 zone file and reload bind9 server.
+   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
+   	 * without password
+   	 *
+   	 * @param subDomain
+   	 *            will be added in front of domain
+   	 */
+   	public void addNewSubDomain(String subDomain, String ip) {
+   		try {
+   			Runtime.getRuntime()
+   			       .exec(CartridgeConstants.SUDO_SH + " " +
+             // script script file that will be used to edit
+             // required files
+             System.getProperty(CartridgeConstants.APPEND_SCRIPT) + " " +
+             subDomain + " " +
+             // machineIp ip of the machine DNS bind service
+             // is running
+             ip + " " +
+             // bindFile the file which we edit to append
+             // the DNS entry
+             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
+   			log.info("New sub domain is added to zone file");
+   		} catch (Exception e) {
+   			log.error(e.getMessage());
+   			throw new RuntimeException(e);
+   		}
+   	}
+    /**
+   	 * This is get called when there is a need of remove a sub domain.
+   	 * It will remove required text from bind9 zone file and reload bind9 server.
+   	 * Note: make sure the user who run ADC has got rights to run sudo scripts
+   	 * without password
+   	 *
+   	 * @param subDomain
+   	 *            will be used to delete the entry related to this
+   	 */
+   	public void removeSubDomain(String subDomain) {
+   		try {
+   			Runtime.getRuntime()
+   			       .exec(CartridgeConstants.SUDO_SH + " " +
+             // script script file that will be used to edit
+             // required files
+             System.getProperty(CartridgeConstants.REMOVE_SCRIPT) + " " +
+             subDomain + " " +
+             // bindFile the file which we edit to remove
+             // the DNS entry
+             System.getProperty(CartridgeConstants.BIND_FILE_PATH));
+   			log.info("Sub domain is removed from zone file");
+   		} catch (Exception e) {
+   			log.error(e.getMessage());
+   			throw new RuntimeException(e);
+   		}
+   	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/AppRepo.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/AppRepo.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/AppRepo.java
new file mode 100644
index 0000000..2013969
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/dto/AppRepo.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.mgt.dto;
+
+public class AppRepo {
+
+	private int tenantId;
+	private String repoName;
+	private String cartridge;
+	private String appName;
+	private boolean isWebRoot;
+	private String tenantPubKey;
+	private String tenantCartridgePubKey;
+
+	public int getTenantId() {
+		return tenantId;
+	}
+
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}
+
+	public String getRepoName() {
+		return repoName;
+	}
+
+	public void setRepoName(String repoName) {
+		this.repoName = repoName;
+	}
+
+	public String getCartridge() {
+		return cartridge;
+	}
+
+	public void setCartridge(String cartridge) {
+		this.cartridge = cartridge;
+	}
+
+	public String getAppName() {
+		return appName;
+	}
+
+	public void setAppName(String appName) {
+		this.appName = appName;
+	}
+
+	public boolean isWebRoot() {
+		return isWebRoot;
+	}
+
+	public void setWebRoot(boolean isWebRoot) {
+		this.isWebRoot = isWebRoot;
+	}
+
+	public String getTenantPubKey() {
+		return tenantPubKey;
+	}
+
+	public void setTenantPubKey(String tenantPubKey) {
+		this.tenantPubKey = tenantPubKey;
+	}
+
+	public String getTenantCartridgePubKey() {
+		return tenantCartridgePubKey;
+	}
+
+	public void setTenantCartridgePubKey(String tenantCartridgePubKey) {
+		this.tenantCartridgePubKey = tenantCartridgePubKey;
+	}
+
+}


[11/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GoolgeAppsRegistrationClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GoolgeAppsRegistrationClient.java b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GoolgeAppsRegistrationClient.java
new file mode 100644
index 0000000..6cfe333
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GoolgeAppsRegistrationClient.java
@@ -0,0 +1,227 @@
+package org.wso2.carbon.gapp.registration.ui;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Calendar;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.neethi.Policy;
+import org.apache.rampart.RampartMessageData;
+import org.apache.rampart.policy.model.CryptoConfig;
+import org.apache.rampart.policy.model.RampartConfig;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.stratos.common.config.CloudServiceConfig;
+import org.wso2.carbon.stratos.common.config.CloudServiceConfigParser;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.packages.stub.PackageInfo;
+import org.wso2.carbon.stratos.common.packages.stub.PackageInfoServiceStub;
+import org.wso2.carbon.tenant.register.gapp.stub.GAppTenantRegistrationServiceStub;
+import org.wso2.carbon.tenant.register.gapp.stub.xsd.TenantInfoBean;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class GoolgeAppsRegistrationClient {
+
+    private static final Log log = LogFactory.getLog(GoolgeAppsRegistrationClient.class);
+    
+    
+    private static final String GAPP_PROPERTIES_FILE = "gapp.setup.properties";
+    private static Properties consumerKeys = new Properties();
+    
+    public GoolgeAppsRegistrationClient() {
+        
+    }
+       
+    public void registerTenantForGAppDomain(String backendServerURL, 
+    		                                ConfigurationContext configContext,
+    		                                String domain,
+    		                                String email, 
+    		                                String adminFirstName, 
+    		                                String adminLastName,
+    		                                String usagePlan) throws Exception {
+    	try {
+    	    Map<String, CloudServiceConfig> cloudServiceConfigs = CloudServiceConfigParser.
+                                                                                          loadCloudServicesConfiguration().
+                                                                                          getCloudServiceConfigs();
+            String managerHomepageURL =
+                                        cloudServiceConfigs.get(StratosConstants.CLOUD_MANAGER_SERVICE).
+                                                            getLink();
+        	String serviceURL = managerHomepageURL + "/services/GAppTenantRegistrationService";
+        	GAppTenantRegistrationServiceStub stub = new GAppTenantRegistrationServiceStub(configContext, serviceURL);
+            ServiceClient client = stub._getServiceClient();
+            // Engage rampart as we are going to sign requests to Relying Party Service
+            client.engageModule("rampart");
+            // Get a RampartConfig with default crypto information
+            Policy rampartConfig = getDefaultRampartConfig();
+            Policy signOnly = getSignOnlyPolicy();
+            Policy mergedPolicy = signOnly.merge(rampartConfig);
+            Options option = client.getOptions();
+            option.setProperty(RampartMessageData.KEY_RAMPART_POLICY, mergedPolicy);
+            option.setManageSession(true);
+       
+            String username = email.substring(0, email.indexOf("@"));
+            TenantInfoBean bean = new TenantInfoBean();
+            bean.setEmail(email);
+            bean.setFirstname(adminFirstName);
+            bean.setLastname(adminLastName);
+            bean.setTenantDomain(domain);
+            bean.setAdmin(username);
+            bean.setUsagePlan(usagePlan);
+            bean.setCreatedDate(Calendar.getInstance());
+            stub.registerGoogleAppsTenant(bean);
+        } catch (Exception e) {
+            String msg = "Failed to create domain because " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg);
+        }
+        
+    }
+
+    public JSONArray buildPackageInfoJSONArray(PackageInfo[] packages) throws Exception {
+        JSONArray packageInfo = new JSONArray();
+        try {
+            for (PackageInfo pak : packages) {
+                JSONObject obj = new JSONObject();
+                obj.put("name", pak.getName());
+                obj.put("users", pak.getUsersLimit());
+                packageInfo.put(obj);
+            }
+            return packageInfo;
+        } catch (JSONException e) {
+            String msg = "Failed to build JSON list " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg);
+        }
+    }
+    
+    public PackageInfo[] getPackageInfo(String backendServerURL,
+            ConfigurationContext configContext) throws Exception {
+    	String packageServiceEpr = backendServerURL + "PackageInfoService";
+    	PackageInfoServiceStub packageStub = null;
+    	PackageInfo[] packageInfo = new PackageInfo[0];
+        try {
+        	packageStub = new PackageInfoServiceStub(configContext, packageServiceEpr);
+            PackageInfo[] packages = packageStub.getPackageInfos();
+            int i = 0;
+            packageInfo = new PackageInfo[packages.length];
+            for (PackageInfo pack : packages ) {
+            	packageInfo[i] = new PackageInfo();
+                packageInfo[i].setName(pack.getName());
+                packageInfo[i].setUsersLimit(pack.getUsersLimit());
+                i++;
+            }
+            return packageInfo;
+        } catch (Exception e) {
+            String msg = "Failed to retrieve package list " + e.getMessage();
+            log.error(msg, e);
+            throw new Exception(msg);
+        }
+    } 
+     
+	private Policy getSignOnlyPolicy() {
+		URL url = null;
+		InputStream inStream;
+		try {
+			inStream = null;
+			if ((url = this.getClass().getClassLoader().getResource("signonly-policy.xml")) != null) {
+			    inStream = url.openStream();
+			} else {
+				throw new Exception("The file is not present in bundle");
+			}
+			Policy policy = org.apache.neethi.PolicyEngine.getPolicy(inStream);
+			return policy;
+		} catch (Exception e) {
+			e.printStackTrace();
+			throw new RuntimeException("Error while creating policy");
+		}
+	}
+
+    public boolean isRegisteredAsGoogleAppDomain(ConfigurationContext configContext,
+                                                 String domain) throws Exception {
+        
+        Map<String, CloudServiceConfig> cloudServiceConfigs = CloudServiceConfigParser.
+                                                                                      loadCloudServicesConfiguration().
+                                                                                      getCloudServiceConfigs();
+        String managerHomepageURL =
+            cloudServiceConfigs.get(StratosConstants.CLOUD_MANAGER_SERVICE).
+                                getLink();
+        String serviceURL = managerHomepageURL + "/services/GAppTenantRegistrationService";
+
+        GAppTenantRegistrationServiceStub stub = new GAppTenantRegistrationServiceStub(configContext, serviceURL);
+        ServiceClient client = stub._getServiceClient();
+        // Engage rampart as we are going to sign requests to Relying Party Service
+        client.engageModule("rampart");
+        // Get a RampartConfig with default crypto information
+        Policy rampartConfig = getDefaultRampartConfig();
+        Policy signOnly = getSignOnlyPolicy();
+        Policy mergedPolicy = signOnly.merge(rampartConfig);
+        Options option = client.getOptions();
+        option.setProperty(RampartMessageData.KEY_RAMPART_POLICY, mergedPolicy);
+        option.setManageSession(true);
+   
+        return stub.isRegisteredAsGoogleAppDomain(domain);
+    }
+    
+	public static String getGoogleAppSetupPropery(String name) throws Exception {
+        try {
+            if (consumerKeys.size() == 0) {
+                String carbonHome = CarbonUtils.getCarbonHome();
+                if (carbonHome != null) {
+                    File gappSetupProperties =
+                                               new File(CarbonUtils.getCarbonConfigDirPath(),
+                                                        GAPP_PROPERTIES_FILE);
+                    
+                    FileInputStream in = new FileInputStream(gappSetupProperties);
+                    consumerKeys.load(in);
+                }
+            }
+            return (String)consumerKeys.get(name);
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            throw new Exception(e.getMessage(), e);
+        }
+	}
+
+	private Policy getDefaultRampartConfig() {
+        //Extract the primary keystore information from server configuration
+        ServerConfiguration serverConfig = ServerConfiguration.getInstance();
+        String keyStore = serverConfig.getFirstProperty("Security.KeyStore.Location");
+        String keyStoreType = serverConfig.getFirstProperty("Security.KeyStore.Type");
+        String keyStorePassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
+        String privateKeyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
+        String privateKeyPassword = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");
+
+        //Populate Rampart Configuration
+        RampartConfig rampartConfig = new RampartConfig();
+        rampartConfig.setUser(privateKeyAlias);
+        rampartConfig.setPwCbClass("org.wso2.carbon.gapp.registration.ui.InMemoryPasswordcallbackHandler");
+
+        //Set the private key alias and private key password in the password callback handler
+        InMemoryPasswordcallbackHandler.addUser(privateKeyAlias, privateKeyPassword);
+
+        CryptoConfig sigCrypto = new CryptoConfig();
+        Properties props = new Properties();
+        sigCrypto.setProvider("org.apache.ws.security.components.crypto.Merlin");
+        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", keyStoreType);
+        props.setProperty("org.apache.ws.security.crypto.merlin.file", keyStore);
+        props.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", keyStorePassword);
+        sigCrypto.setProp(props);
+
+        rampartConfig.setSigCryptoConfig(sigCrypto);
+        Policy policy = new Policy();
+        policy.addAssertion(rampartConfig);
+
+        return policy;
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/InMemoryPasswordcallbackHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/InMemoryPasswordcallbackHandler.java b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/InMemoryPasswordcallbackHandler.java
new file mode 100644
index 0000000..082d816
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/InMemoryPasswordcallbackHandler.java
@@ -0,0 +1,39 @@
+package org.wso2.carbon.gapp.registration.ui;
+
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.ws.security.WSPasswordCallback;
+
+public class InMemoryPasswordcallbackHandler  implements CallbackHandler {
+
+	    private static Map<String, String> keystorePassword = new HashMap<String, String>();
+
+	    public void handle(Callback[] callbacks)
+	            throws IOException, UnsupportedCallbackException {
+
+	        for (int i = 0; i < callbacks.length; i++) {
+
+	            if (callbacks[i] instanceof WSPasswordCallback) {
+	                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+	                String id = pc.getIdentifier();
+	                if (keystorePassword.get(id) != null) {
+	                    pc.setPassword(keystorePassword.get(id));
+	                } else {
+	                    throw new UnsupportedCallbackException(callbacks[i], "no password found for " + id);
+	                }
+	            }
+
+	        }
+	    }
+
+	    public static void addUser(String username, String password) {
+	        keystorePassword.put(username, password);
+	    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..4436375
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,27 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <framework-configuration>
+        <bypass>
+            <authentication>
+                <link>/setup_ajaxprocessor.jsp</link>
+                <link>/done_ajaxprocessor.jsp</link>
+            </authentication>
+        </bypass>
+    </framework-configuration>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/org/wso2/carbon/gapp/registration/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/org/wso2/carbon/gapp/registration/ui/i18n/Resources.properties b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/org/wso2/carbon/gapp/registration/ui/i18n/Resources.properties
new file mode 100644
index 0000000..ec80581
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/org/wso2/carbon/gapp/registration/ui/i18n/Resources.properties
@@ -0,0 +1,8 @@
+select.usage.plan.for.tenant=Select a usage plan for tenant
+help=help
+admin.firstname=First Name
+admin.lastname=Last Name
+admin.address=Address
+admin.email=Email
+select.usage.plan.for.tenant=Select a usage plan for tenant
+help=help

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/signonly-policy.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/signonly-policy.xml b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/signonly-policy.xml
new file mode 100644
index 0000000..2b24b29
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/signonly-policy.xml
@@ -0,0 +1,102 @@
+<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SigOnly">
+        <wsp:ExactlyOne>
+            <wsp:All>
+                <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <wsp:Policy>
+                        <sp:InitiatorToken>
+                            <wsp:Policy>
+                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
+                                    <wsp:Policy>
+                                        <sp:RequireThumbprintReference />
+                                        <sp:WssX509V3Token10 />
+                                    </wsp:Policy>
+                                </sp:X509Token>
+                            </wsp:Policy>
+                        </sp:InitiatorToken>
+                        <sp:RecipientToken>
+                            <wsp:Policy>
+                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
+                                    <wsp:Policy>
+                                        <sp:RequireThumbprintReference />
+                                        <sp:WssX509V3Token10 />
+                                    </wsp:Policy>
+                                </sp:X509Token>
+                            </wsp:Policy>
+                        </sp:RecipientToken>
+                        <sp:AlgorithmSuite>
+                            <wsp:Policy>
+                                <sp:Basic256 />
+                            </wsp:Policy>
+                        </sp:AlgorithmSuite>
+                        <sp:Layout>
+                            <wsp:Policy>
+                                <sp:Strict />
+                            </wsp:Policy>
+                        </sp:Layout>
+                        <sp:IncludeTimestamp />
+                        <sp:OnlySignEntireHeadersAndBody />
+                    </wsp:Policy>
+                </sp:AsymmetricBinding>
+                <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <sp:Policy>
+                        <sp:MustSupportRefKeyIdentifier />
+                        <sp:MustSupportRefIssuerSerial />
+                    </sp:Policy>
+                </sp:Wss10>
+                <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <sp:Body />
+                </sp:SignedParts>
+            </wsp:All>
+        </wsp:ExactlyOne>
+    </wsp:Policy>
+<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SigOnly">
+        <wsp:ExactlyOne>
+            <wsp:All>
+                <sp:AsymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <wsp:Policy>
+                        <sp:InitiatorToken>
+                            <wsp:Policy>
+                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
+                                    <wsp:Policy>
+                                        <sp:RequireThumbprintReference />
+                                        <sp:WssX509V3Token10 />
+                                    </wsp:Policy>
+                                </sp:X509Token>
+                            </wsp:Policy>
+                        </sp:InitiatorToken>
+                        <sp:RecipientToken>
+                            <wsp:Policy>
+                                <sp:X509Token sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Never">
+                                    <wsp:Policy>
+                                        <sp:RequireThumbprintReference />
+                                        <sp:WssX509V3Token10 />
+                                    </wsp:Policy>
+                                </sp:X509Token>
+                            </wsp:Policy>
+                        </sp:RecipientToken>
+                        <sp:AlgorithmSuite>
+                            <wsp:Policy>
+                                <sp:Basic256 />
+                            </wsp:Policy>
+                        </sp:AlgorithmSuite>
+                        <sp:Layout>
+                            <wsp:Policy>
+                                <sp:Strict />
+                            </wsp:Policy>
+                        </sp:Layout>
+                        <sp:IncludeTimestamp />
+                        <sp:OnlySignEntireHeadersAndBody />
+                    </wsp:Policy>
+                </sp:AsymmetricBinding>
+                <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <sp:Policy>
+                        <sp:MustSupportRefKeyIdentifier />
+                        <sp:MustSupportRefIssuerSerial />
+                    </sp:Policy>
+                </sp:Wss10>
+                <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
+                    <sp:Body />
+                </sp:SignedParts>
+            </wsp:All>
+        </wsp:ExactlyOne>
+    </wsp:Policy>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/done_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/done_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/done_ajaxprocessor.jsp
new file mode 100644
index 0000000..0295fc7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/done_ajaxprocessor.jsp
@@ -0,0 +1,165 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@page import="org.wso2.carbon.gapp.registration.ui.GAppRegistrationUIConstants"%>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<html>
+<head>
+<%@page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@page import="org.wso2.carbon.CarbonConstants" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@page import="org.wso2.carbon.gapp.registration.ui.GoolgeAppsRegistrationClient" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+
+<%@page import="org.wso2.carbon.ui.util.CharacterEncoder"%><script type="text/javascript" src="../userstore/extensions/js/vui.js"></script>
+
+<%
+    String domain = (String)session.getAttribute("domain");
+    String callback = (String)session.getAttribute("callback"); 
+%>  
+<script type="text/javascript" src="../admin/js/main.js"></script>
+<link href="../admin/css/global.css" rel="stylesheet" type="text/css" media="all"/>
+<link href="../admin/css/main.css" rel="stylesheet" type="text/css" media="all"/>
+<link href="../tenant-register/css/tenant-register.css" rel="stylesheet" type="text/css" media="all"/>
+
+
+    <link href="../dialog/css/jqueryui/jqueryui-themeroller.css" rel="stylesheet" type="text/css" media="all"/>
+    <link href="../dialog/css/dialog.css" rel="stylesheet" type="text/css" media="all"/>
+    <link rel="icon" href="../admin/images/favicon.ico" type="image/x-icon"/>
+    <link rel="shortcut icon" href="../admin/images/favicon.ico" type="image/x-icon"/>
+
+    <script type="text/javascript" src="../admin/js/jquery.js"></script>
+    <script type="text/javascript" src="../admin/js/jquery.form.js"></script>
+    <script type="text/javascript" src="../dialog/js/jqueryui/jquery-ui.min.js"></script>
+    <script type="text/javascript" src="../dialog/js/dialog.js"></script>
+
+    <script type="text/javascript" src="../admin/js/main.js"></script>
+    <script type="text/javascript" src="../admin/js/WSRequest.js"></script>
+    <script type="text/javascript" src="../admin/js/cookies.js"></script>
+    <script src="../yui/build/yahoo-dom-event/yahoo-dom-event.js" type="text/javascript"></script>
+    <script src="../admin/js/widgets.js" type="text/javascript"></script> 
+<!--[if gte IE 8]>
+<link href="../dialog/css/dialog-ie8.css" rel="stylesheet" type="text/css" media="all"/>
+<![endif]-->
+<!--[if gte IE 7]>
+<link href="../dialog/css/dialog-ie8.css" rel="stylesheet" type="text/css" media="all"/>
+<![endif]-->
+<style type="text/css">
+  .header-links{
+      display:none !important;
+  }
+  body, span, td, div{
+    font-size:12px;
+  }
+</style>
+</head>
+<body>
+<div id="dcontainer"></div>
+<script type="text/javascript">
+    function forward() {
+        location.href = "<%=callback%>";
+    }
+</script>
+<%
+    Object isAllowed = session.getAttribute(GAppRegistrationUIConstants.ALLOWED);
+    boolean value = (Boolean)isAllowed;
+    if (!value) {
+		%>
+	<script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showInfoDialog("Illegal access atempt!");
+        });
+    </script>	
+		<%	
+		return;
+    }
+    
+    boolean isSuccess = true;
+	try {
+        String subscription = (String)request.getParameter("usage-plan-name");
+        String firstName = (String)request.getParameter("admin-firstname");
+        String lastName = (String)request.getParameter("admin-lastname");
+        String email = (String)request.getParameter("admin-email");
+        String[] users = new String[0];
+    	String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext =
+                    (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);       
+        GoolgeAppsRegistrationClient client = new GoolgeAppsRegistrationClient();
+        client.registerTenantForGAppDomain(backendServerURL, configContext, domain, email, firstName, lastName, subscription);
+    } catch (Exception e) {
+        isSuccess = false;
+    }
+    
+    if (isSuccess) {%>
+    <script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showInfoDialog("Stratos setup was successful! You are being redirected back to Google", forward, forward);
+        });
+        
+    </script>
+<%} else {%>
+    <script type="text/javascript">
+    jQuery(document).ready(function() {
+        CARBON.showErrorDialog("Stratos setup was unsuccessful! You are being redirected back to Google", forward, forward);
+    });
+    </script>  	
+<%}%>
+<table id="main-table" border="0" cellspacing="0">
+      <tr>
+          <td id="header"><jsp:include page="../admin/layout/header.jsp" />
+          </td>
+      </tr>
+      <tr>
+
+
+          <td id="middle-content">
+              <table id="content-table" border="0" cellspacing="0">
+
+                  <tr>
+                      <td id="body">
+				<fmt:bundle basename="org.wso2.carbon.gapp.registration.ui.i18n.Resources">
+				   
+				    <script type="text/javascript">
+				
+				       
+				    </script>
+				    <div id="middle">
+				        <div id="workArea">
+				        <%if (isSuccess) {%>
+				            <p>Setting up Stratos was successful. You are being redirected back to <%=callback%></p>
+				        <% } else { %>
+				        	<p>Setting up Stratos was unsuccessful. You are being redirected back to <%=callback%></p>
+				        <% } %>            
+				    </div>
+				    </div>				
+				</fmt:bundle>
+				  </td>
+                  </tr>
+              </table>
+          </td>
+      </tr>
+      <tr>
+          <td id="footer"<jsp:include page="../admin/layout/footer.jsp" /></td>
+      </tr>
+  </table>   
+</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/openidaccept_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/openidaccept_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/openidaccept_ajaxprocessor.jsp
new file mode 100644
index 0000000..aed6ece
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/openidaccept_ajaxprocessor.jsp
@@ -0,0 +1,93 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@page import="org.wso2.carbon.gapp.registration.ui.GoolgeAppsRegistrationClient"%>
+<%@page import="com.google.step2.Step2.AxSchema"%>
+<%@page import="org.wso2.carbon.identity.relyingparty.stub.dto.ClaimDTO"%>
+<%@page import="com.google.gdata.data.appsforyourdomain.provisioning.UserEntry"%>
+<%@page import="com.google.gdata.client.appsforyourdomain.UserService"%>
+<%@page import="java.net.URL"%>
+<%@page import="com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer"%>
+<%@page import="com.google.gdata.client.authn.oauth.GoogleOAuthParameters"%>
+<%@page import="org.wso2.carbon.utils.CarbonUtils"%>
+<%@page import="org.wso2.carbon.gapp.registration.ui.GAppRegistrationUIConstants"%>
+<%@page import="org.wso2.carbon.identity.relyingparty.ui.openid.OpenIDConsumer"%>
+<%@page import="org.wso2.carbon.identity.relyingparty.ui.client.RelyingPartyServiceClient"%>
+<%@page import="org.wso2.carbon.identity.relyingparty.ui.openid.OpenIDAuthenticationRequest"%>
+<%@ page import="org.wso2.carbon.identity.relyingparty.stub.dto.OpenIDDTO" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+  try {
+      
+      session.setAttribute(GAppRegistrationUIConstants.ALLOWED, new Boolean("false"));
+      
+      // is authenticated
+      String webContextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");
+      String adminConsoleURL = CarbonUIUtil.getAdminConsoleURL(webContextRoot);
+      String recievingURL = adminConsoleURL + "gappregistration/openidaccept_ajaxprocessor.jsp";
+      OpenIDDTO openID = OpenIDConsumer.getInstance().validateOpenIDAuthentication(request, recievingURL);
+      ClaimDTO[] claims = openID.getClaims();
+      String emailId = null;
+      for(ClaimDTO claim : claims) {
+          if(claim.getClaimUri().equals(AxSchema.EMAIL.getUri())) {
+              emailId = claim.getClaimValue();
+          }
+      }
+      
+      if (emailId != null) {
+		    //is authorized
+		    String serviceName = (String)session.getAttribute("service");
+		    
+		    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
+		    oauthParameters.setOAuthConsumerKey(
+		                                        GoolgeAppsRegistrationClient.
+		                                        getGoogleAppSetupPropery(serviceName + ".consumer.key"));
+		    oauthParameters.setOAuthConsumerSecret(
+		                                           GoolgeAppsRegistrationClient.
+		                                           getGoogleAppSetupPropery(serviceName + ".consumer.key.secret"));
+		    OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();       
+		    
+		    String username =  emailId.substring(0, emailId.indexOf("@"));
+		    String domain = (String)session.getAttribute("domain");
+		    
+		    
+		    URL feedUrl = new URL("https://apps-apis.google.com/a/feeds/" + domain + "/user/2.0/" + 
+		                                                                                 username + 
+		                                                                  "?xoauth_requestor_id=" + 
+		                                                                                 emailId);
+		
+		    UserService service = new UserService("ProvisiongApiClient");
+		    service.setOAuthCredentials(oauthParameters, signer);
+		    service.useSsl();
+		    UserEntry entry = service.getEntry(feedUrl, UserEntry.class);
+		    if (entry.getLogin().getAdmin()) {
+		        session.setAttribute(GAppRegistrationUIConstants.ALLOWED, new Boolean("true"));    
+		    } else {
+		        throw new Exception("You are not the admin of this google apps domain. To setup stratos you must be an Admin");
+		    }
+      } else {
+          throw new IllegalStateException("Invalid state");
+      }
+      
+      response.sendRedirect("setup_ajaxprocessor.jsp");
+  } catch (Exception e) {
+	  CarbonUIMessage.sendCarbonUIMessage("Failed to setup stratos. " + e.getMessage(), CarbonUIMessage.ERROR, request);
+	  response.sendRedirect("setup_ajaxprocessor.jsp");
+  }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/setup_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/setup_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/setup_ajaxprocessor.jsp
new file mode 100644
index 0000000..bf5a1f6
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/resources/web/gappregistration/setup_ajaxprocessor.jsp
@@ -0,0 +1,320 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@page import="com.google.gdata.data.appsforyourdomain.provisioning.UserEntry"%>
+<%@page import="com.google.gdata.client.appsforyourdomain.UserService"%>
+<%@page import="java.net.URL"%>
+<%@page import="com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer"%>
+<%@page import="com.google.gdata.client.authn.oauth.GoogleOAuthParameters"%>
+<html>
+<head>
+<%@page import="org.wso2.carbon.identity.relyingparty.ui.openid.OpenIDConsumer"%>
+<%@page import="org.wso2.carbon.identity.relyingparty.ui.openid.OpenIDAuthenticationRequest"%>
+<%@page import="org.wso2.carbon.gapp.registration.ui.GAppRegistrationUIConstants"%>
+<%@page import="org.wso2.carbon.stratos.common.packages.stub.PackageInfo"%>
+<%@page import="org.json.JSONArray"%>
+<%@page import="org.wso2.carbon.common.util.CommonUtil"%>
+<%@page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@page import="org.wso2.carbon.CarbonConstants" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@page import="org.wso2.carbon.gapp.registration.ui.GoolgeAppsRegistrationClient" %>
+<%@page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@page import="com.google.step2.Step2.AxSchema"%>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+
+<%
+    String domain = request.getParameter("domain");
+    String callback = request.getParameter("callback");
+    String service = request.getParameter("service");
+
+    PackageInfo[] packageInfo = new PackageInfo[0];
+
+    if (service != null && service.trim().length() > 0) {
+        session.setAttribute(GAppRegistrationUIConstants.ALLOWED, null);
+        session.setAttribute("service", service.trim());
+    } else {
+        service = (String) session.getAttribute("service");
+    }
+
+    if (domain != null && domain.trim().length() > 0) {
+        session.setAttribute(GAppRegistrationUIConstants.ALLOWED, null);
+        session.setAttribute("domain", domain.trim());
+    } else {
+        domain = (String) session.getAttribute("domain");
+    }
+
+    if (callback != null && callback.trim().length() > 0) {
+        session.setAttribute(GAppRegistrationUIConstants.ALLOWED, null);
+        session.setAttribute("callback", callback);
+    } else {
+        callback = (String) session.getAttribute("callback");
+    }
+%>
+<script type="text/javascript" src="../admin/js/main.js"></script>
+
+<link href="../dialog/css/dialog.css" rel="stylesheet" type="text/css" media="all"/>
+<link href="../admin/css/global.css" rel="stylesheet" type="text/css" media="all"/>
+<link href="../admin/css/main.css" rel="stylesheet" type="text/css" media="all"/>
+<link href="../tenant-register/css/tenant-register.css" rel="stylesheet" type="text/css" media="all"/>
+<!--[if gte IE 8]>
+<link href="../dialog/css/dialog-ie8.css" rel="stylesheet" type="text/css" media="all"/>
+<![endif]-->
+<!--[if gte IE 7]>
+<link href="../dialog/css/dialog-ie8.css" rel="stylesheet" type="text/css" media="all"/>
+<![endif]-->
+<style type="text/css">
+  .header-links{
+      display:none !important;
+  }
+  body, span, td, div{
+    font-size:12px;
+  }
+</style>
+
+ <link href="../dialog/css/jqueryui/jqueryui-themeroller.css" rel="stylesheet" type="text/css" media="all"/>
+    <link href="../dialog/css/dialog.css" rel="stylesheet" type="text/css" media="all"/>
+    <link rel="icon" href="../admin/images/favicon.ico" type="image/x-icon"/>
+    <link rel="shortcut icon" href="../admin/images/favicon.ico" type="image/x-icon"/>
+
+    <script type="text/javascript" src="../admin/js/jquery.js"></script>
+    <script type="text/javascript" src="../admin/js/jquery.form.js"></script>
+    <script type="text/javascript" src="../dialog/js/jqueryui/jquery-ui.min.js"></script>
+	<script type="text/javascript" src="../dialog/js/dialog.js"></script>
+	
+    <script type="text/javascript" src="../admin/js/main.js"></script>
+    <script type="text/javascript" src="../admin/js/WSRequest.js"></script>
+    <script type="text/javascript" src="../admin/js/cookies.js"></script>
+    <script src="../yui/build/yahoo-dom-event/yahoo-dom-event.js" type="text/javascript"></script>
+    <script src="../admin/js/widgets.js" type="text/javascript"></script> 
+    <script type="text/javascript">
+function validateGAppSetupInfo() {
+    var error = validateEmpty('admin-email');
+    if (error) {
+        CARBON.showWarningDialog("Email address cannot be empty.");
+        return false;
+    }
+    
+    var fld = document.getElementById('admin-email');
+    var value = fld.value;
+    if (value.indexOf("@") > -1 ) {
+    	var emaildomain = value.substring(value.indexOf("@")+1, value.length);
+    	if (emaildomain == "<%=domain%>") {
+			//do nothing
+    	} else {
+    		CARBON.showWarningDialog("Admin's email address must be in the same domain.");
+            return false;
+    	}
+    } else {
+    	CARBON.showWarningDialog("Invalid email address.");
+        return false;
+    }
+    
+    var error = validateEmpty('admin-firstname');
+    if (error) {
+        CARBON.showWarningDialog("First name cannot be empty.");
+        return false; 
+    }
+    var error = validateEmpty('admin-lastname');
+    if (error) {
+        CARBON.showWarningDialog("Last name cannot be empty.");
+        return false;
+    }
+    document.gappsetupForm.submit();
+};
+</script>
+</head>
+<body>
+<div id="dcontainer"></div>
+<script type="text/javascript">
+    function forward() {
+        location.href = "<%=callback%>";
+    }
+</script>
+<%
+    try {
+        Object isAllowed = session.getAttribute(GAppRegistrationUIConstants.ALLOWED);
+        if (isAllowed == null) {
+            //this is the first call 
+            ConfigurationContext configContext =
+                                                 (ConfigurationContext) config.getServletContext()
+                                                                              .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+            GoolgeAppsRegistrationClient client = new GoolgeAppsRegistrationClient();
+            
+            if (domain == null) {
+                throw new Exception("Cannot proceed since domain is invalid"); 
+            }
+            
+            boolean isRegistered =
+                                   client.isRegisteredAsGoogleAppDomain(configContext, domain);
+            if (isRegistered) {
+%>
+		     	<script type="text/javascript">
+			        jQuery(document).ready(function() {
+			            CARBON.showInfoDialog("Strato domain has been setup for the domain " + <%=domain%>, forward, forward);
+			        });
+                </script>	
+		     	<%
+			     	    return;
+			     	            }
+
+			     	            OpenIDAuthenticationRequest openIDAuthRequest =
+			     	                                                            new OpenIDAuthenticationRequest(
+			     	                                                                                            request,
+			     	                                                                                            response);
+			     	            openIDAuthRequest.setOpenIDUrl(domain.trim());
+			     	            String returnUrl =
+			     	                               OpenIDConsumer.getInstance().getAdminConsoleURL(request) +
+			     	                                       "gappregistration/openidaccept_ajaxprocessor.jsp";
+			     	            openIDAuthRequest.setReturnUrl(returnUrl);
+			     	            openIDAuthRequest.addRequiredClaims(AxSchema.EMAIL.getUri());
+			     	            openIDAuthRequest.setRequestClaimsFromIdP(true);
+			     	            String forwardTo =
+			     	                               OpenIDConsumer.getInstance()
+			     	                                             .doOpenIDAuthentication(openIDAuthRequest);
+			     	            response.sendRedirect(forwardTo);
+			     	        } else {
+			     	            boolean value = (Boolean) isAllowed;
+			     	            if (!value) {
+			     	                CarbonUIMessage carbonMessage =
+			     	                                                (CarbonUIMessage) session.getAttribute(CarbonUIMessage.ID);
+			     	%>
+		     	<script type="text/javascript">
+			        jQuery(document).ready(function() {
+			            CARBON.showErrorDialog("<%=carbonMessage.getMessage()%>", forward, forward);
+			        });
+                </script>	
+		     	<%
+			     	    return;
+			     	            }
+			     	        }
+
+			     	        String serverURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+			     	        ConfigurationContext configContext =
+			     	                                             (ConfigurationContext) config.getServletContext()
+			     	                                                                          .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+			     	        GoolgeAppsRegistrationClient client = new GoolgeAppsRegistrationClient();
+			     	        packageInfo = client.getPackageInfo(serverURL, configContext);
+			     	    } catch (Exception e) {
+			     	%>
+     	<script type="text/javascript">
+	        jQuery(document).ready(function() {
+	            CARBON.showErrorDialog("Unable to setup Stratos. <%=e.getMessage()%> ", forward, forward);
+	        });
+        </script>	
+     	<%
+	     	    return;
+	     	    }
+	     	%>
+
+<table id="main-table" border="0" cellspacing="0">
+	      <tr>
+	          <td id="header"><jsp:include page="../admin/layout/header.jsp" />
+	          </td>
+	      </tr>
+	      <tr>
+
+
+          <td id="middle-content">
+              <table id="content-table" border="0" cellspacing="0">
+
+                  <tr>
+                      <td id="body">
+                          
+       
+				<fmt:bundle basename="org.wso2.carbon.gapp.registration.ui.i18n.Resources">    
+				    <div id="middle">
+				        <h2>Setting up the Stratos Domain for your Google Apps Domain</h2>
+				        <div id="workArea">
+				            <form method="post" name="gappsetupForm" action="done_ajaxprocessor.jsp"> 
+				                <div class="toggle_container">
+							        <table class="normal-nopadding" cellspacing="0" >
+							            <tbody>
+							              <tr>
+				                                    <td><fmt:message key="admin.email"/><span
+				                                            class="required">*</span></td>
+				                                    <td><input type="text" name="admin-email"
+				                                                           id="admin-email" style="width:400px"/></td>
+				                            </tr>
+							                <tr>
+				                                    <td><fmt:message key="admin.firstname"/><span
+				                                            class="required">*</span></td>
+				                                    <td><input type="text" name="admin-firstname"
+				                                                           id="admin-firstname" style="width:400px"/></td>
+				                            </tr>
+				                            <tr>
+				                                    <td><fmt:message key="admin.lastname"/><span
+				                                            class="required">*</span></td>
+				                                    <td colspan="2"><input type="text" name="admin-lastname"
+				                                                           id="admin-lastname" style="width:400px"/></td>
+				                            </tr>
+							                <tr>
+							                    <td>
+							                       <fmt:message key="select.usage.plan.for.tenant"/><span class="required">*</span>
+							                    </td>
+							                    <td><p>
+							               <select name="usage-plan-name" id="usage-plan-name">               
+							               <%
+               							                   for (int i = 0; i < packageInfo.length; i++) {
+               							               %>
+							                   <%
+							                       if (i == 0) {
+							                   %>
+							                   <option value="<%=packageInfo[i].getName()%>" selected="selected"><%=packageInfo[i].getName()%></option>
+							                   <%
+							                       } else {
+							                   %>
+							                   <option value="<%=packageInfo[i].getName()%>"><%=packageInfo[i].getName()%></option>  
+							               <%
+  							                   }
+  							                       }
+  							               %>
+							               </select>
+							                   <a href=<%=CommonUtil.getStratosConfig().getUsagePlanURL()%>
+							                           target=<%=CommonUtil.getStratosConfig().getUsagePlanURL()%>>
+							                       <b>More info</b>
+							                   </a>
+							                   </p>
+							                   </td>
+							                 </tr>
+							                 <tr>
+							                 <td class="buttonRow" colspan="2"><input type="button" class="button" value="OK" onclick="validateGAppSetupInfo();"/></td>
+							               </tr>
+							            </tbody>
+							        </table>
+							      </div>
+				            </form>    
+				        </div>
+				    </div>
+				</fmt:bundle>
+                      </td>
+                  </tr>
+              </table>
+          </td>
+      </tr>
+      <tr>
+          <td id="footer"><jsp:include page="../admin/layout/footer.jsp" /></td>
+      </tr>
+  </table>
+  
+    
+</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..6ba9a06
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/pom.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<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/xsd/maven-4.0.0.xsd">
+    <parent>
+        <groupId>org.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.google.analytics.ui</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos-Google Analytics UI</name>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+           <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>
+                        <Private-Package>org.wso2.carbon.google.analytics.ui.internal
+                        </Private-Package>
+                        <Export-Package>
+                            org.wso2.carbon.google.analytics.ui.*; version=1.0.0,
+                        </Export-Package>
+                        <Import-Package>
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.xml.namespace; version="0.0.0",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                        <Carbon-Component>UIBundle</Carbon-Component>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/internal/GoogleAnalyticsUIServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/internal/GoogleAnalyticsUIServiceComponent.java b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/internal/GoogleAnalyticsUIServiceComponent.java
new file mode 100644
index 0000000..27ef59f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/internal/GoogleAnalyticsUIServiceComponent.java
@@ -0,0 +1,68 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.google.analytics.ui.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+
+import javax.servlet.ServletContext;
+
+/**
+ * @scr.component name="org.wso2.carbon.google.analyzer.ui" immediate="true"
+ * @scr.reference name="servlet.context.service"
+ * interface="javax.servlet.ServletContext"
+ * cardinality="1..1"
+ * policy="dynamic"
+ * bind="setServletContextService"
+ * unbind="unsetServletContextService"
+ */
+
+/**
+ * org.wso2.carbon.google.analytics.ui bundle has implemented for giving google-analytics support
+ * for stratos.
+ */
+
+public class GoogleAnalyticsUIServiceComponent {
+
+    private static final Log log = LogFactory.getLog(GoogleAnalyticsUIServiceComponent.class);
+
+    private static ServletContext servletCtx = null;
+
+    protected void activate(ComponentContext context) {
+        try {
+            log.debug("Google Analytics UI Component bundle is activated");
+        } catch (Exception e) {
+            log.debug("Failed to activate Google Analytics UI Component bundle");
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("Google Analytics UI Component bundle is deactivated");
+    }
+
+    protected void setServletContextService(ServletContext servletContext) {
+        this.servletCtx = servletContext;
+
+    }
+
+    protected void unsetServletContextService(ServletContext servletContext) {
+    }
+}
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/servlets/GoogleAnalyticsServlet.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/servlets/GoogleAnalyticsServlet.java b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/servlets/GoogleAnalyticsServlet.java
new file mode 100644
index 0000000..c3e6711
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/java/org/wso2/carbon/google/analytics/ui/servlets/GoogleAnalyticsServlet.java
@@ -0,0 +1,90 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.google.analytics.ui.servlets;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.URL;
+import java.net.URLConnection;
+
+/**
+ * GoogleAnalyticsServlet use for sending a request to a remote URL in where a js snippet which
+ * is  required to process google analytics is hosted.Then this servlet get back the content of
+ * that js snippet and set it as the response.Then by using a javascript,this servlet response will
+ * be embedded into another html/jsp page and make use of the js snippet content from that html/jsp
+ * page.
+ */
+public class GoogleAnalyticsServlet extends HttpServlet {
+    private static final Log log = LogFactory.getLog(GoogleAnalyticsServlet.class);
+    private static String GOOGLE_ANALYTICS_URL = "GoogleAnalyticsURL";
+    private static String googleAnalyticsURL = "googleAnalyticUrl";
+
+    public void init(ServletConfig servletConfig) throws ServletException {
+        super.init(servletConfig);
+
+    }
+
+    protected void doGet(HttpServletRequest request, HttpServletResponse response)
+            throws ServletException, IOException {
+        String url = null;
+        try {
+            //Read Google analytic url from stratos.xml
+            url = CommonUtil.loadStratosConfiguration().getGoogleAnalyticsURL();
+            if (url != null && !(url.equals(""))) {
+                //Create a new connection to above read google analytic url and read content of url.
+                URL googleAnalyticUrl = new URL(url);
+                URLConnection connection = googleAnalyticUrl.openConnection();
+                //Set the input stream of created URL connection to a reader
+                BufferedReader in = new BufferedReader(
+                        new InputStreamReader(
+                                connection.getInputStream()));
+                String inputLine;
+                //Set servlet response as 'text/javascript'
+                response.setContentType("text/javascript");
+                PrintWriter out = response.getWriter();
+                //Read the input stream which has fetched to buffered reader,line by line and then
+                //write those content into the servlet response.
+                while ((inputLine = in.readLine()) != null) {
+                    out.write(inputLine);
+                }
+                in.close();
+                out.flush();
+                out.close();
+            }
+        } catch (Exception e) {
+            String msg = "Failed to get content from the url." + url + e.getMessage();
+            log.error(msg, e);
+            response.setStatus(500);
+        }
+
+
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..bafedb9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,43 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <servlets>
+        <servlet id="googleAnalyticsServlet">
+            <servlet-name>googleAnalyticsServlet</servlet-name>
+            <url-pattern>/google-analytics</url-pattern>
+            <display-name>Google Analytics Servlet</display-name>
+            <servlet-class>org.wso2.carbon.google.analytics.ui.servlets.GoogleAnalyticsServlet
+            </servlet-class>
+        </servlet>
+    </servlets>
+    <framework-configuration>
+        <bypass>
+            <authentication>
+                <link>/google-analytics</link>
+            </authentication>
+            <tiles>
+                <link>/google-analytics</link>
+            </tiles>
+            <httpUrls>
+                <link>/google-analytics</link>
+            </httpUrls>
+        </bypass>
+    </framework-configuration>
+
+
+</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/googleAnalyticsProcessor.js
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/googleAnalyticsProcessor.js b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/googleAnalyticsProcessor.js
new file mode 100644
index 0000000..44803eb
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/googleAnalyticsProcessor.js
@@ -0,0 +1,35 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Following jquery function sends an AJAX request to the googleAnalyticsServlet and get back the
+ * response from the servlet and append it into html/jsp file 'body' section,once the html/jsp
+ * file is ready
+ */
+$('document').ready(function() {
+    $.ajax({
+               type: "GET",
+               url: "/google-analytics",
+               data: null,
+               success: function(response) {
+                   if (response != "googleAnalyticUrl") {
+                       $("body").append(response);
+                   }
+               }
+           });
+});


[32/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
new file mode 100644
index 0000000..05f3d8b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
@@ -0,0 +1,2557 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.jdbc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.billing.core.utilities.DataSourceHolder;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import javax.sql.DataSource;
+import java.sql.*;
+import java.sql.Date;
+import java.util.*;
+
+public class DataAccessObject {
+    public static final Log log = LogFactory.getLog(DataAccessObject.class);
+    public static final int INVALID = -1;
+    //following timezone will be changed according to the one defined in the billing-config.xml
+    //It is done in the MonthlyScheduleHelper
+    public static String TIMEZONE="GMT-8:00";
+
+    DataSource dataSource;
+
+    public DataAccessObject(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    public DataAccessObject() {
+        this.dataSource = DataSourceHolder.getDataSource();
+    }
+    // transaction handling
+
+    public void beginTransaction() throws BillingException {
+        if (Transaction.getNestedDepth() != 0) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not started, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+            Transaction.incNestedDepth();
+            return;
+        }
+
+        Connection conn;
+        try {
+            conn = dataSource.getConnection();
+            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
+                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+            }
+            conn.setAutoCommit(false);
+            Transaction.incNestedDepth();
+        } catch (SQLException e) {
+            String msg = "Failed to start new billing transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        Transaction.setConnection(conn);
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        Transaction.setRollbacked(true);
+        if (Transaction.getNestedDepth() != 1) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not rollbacked, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+
+            Transaction.decNestedDepth();
+            return;
+        }
+
+        Connection conn = Transaction.getConnection();
+        try {
+            conn.rollback();
+
+        } catch (SQLException e) {
+            String msg = "Failed to rollback transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            endTransaction();
+            Transaction.decNestedDepth();
+        }
+    }
+
+    public void commitTransaction() throws BillingException {
+        if (Transaction.getNestedDepth() != 1) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not commited, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+            Transaction.decNestedDepth();
+            return;
+        }
+
+        if (Transaction.isRollbacked()) {
+            String msg = "The transaction is already rollbacked, you can not commit a transaction "
+                    + "already rollbacked, nested depth: " + Transaction.getNestedDepth() + ".";
+            log.debug(msg);
+            Transaction.decNestedDepth();
+            throw new BillingException(msg);
+        }
+
+        Connection conn = Transaction.getConnection();
+        try {
+            conn.commit();
+
+        } catch (SQLException e) {
+            String msg = "Failed to commit transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            endTransaction();
+            Transaction.decNestedDepth();
+        }
+    }
+
+    private void endTransaction() throws BillingException {
+
+        if (Transaction.isStarted()) {
+            Connection conn = Transaction.getConnection();
+            try {
+                conn.close();
+                //log.info("Database connection closed: ");
+            } catch (SQLException e) {
+                String msg = "Failed to close transaction. " + e.getMessage();
+                log.error(msg, e);
+                throw new BillingException(msg, e);
+
+            } finally {
+                Transaction.setStarted(false);
+                Transaction.setConnection(null);
+            }
+        }
+    }
+
+    public int getItemIdWithName(String itemName) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int id = INVALID;
+        try {
+            String sql = "SELECT BC_ID FROM BC_ITEM WHERE BC_NAME=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                id = result.getInt("BC_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to check the existence of the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            
+        }
+
+        return id;
+    }
+
+    public int getItemId(String itemName, int parentId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int id = INVALID;
+        try {
+            String sql = "SELECT BC_ID FROM BC_ITEM WHERE BC_NAME=? AND BC_PARENT_ITEM_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+            ps.setInt(2, parentId);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                id = result.getInt("BC_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to check the existence of the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+
+        return id;
+    }
+
+    public List<Item> getItemsWithName(String itemName) throws BillingException {
+        /*Connection conn = null;
+        try {
+              conn = DataSourceHolder.getDataSource().getConnection();
+                } catch (SQLException e) {
+                    String msg = "Failed to establish data connection";
+                    log.error(msg, e);
+                }
+        */
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Item> items = new ArrayList<Item>();
+
+        try {
+            String sql = "SELECT BC_ID, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM WHERE BC_NAME=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = new Item();
+                item.setName(itemName);
+                int id = result.getInt("BC_ID");
+                item.setId(id);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    Item parentItem;
+                    if (id == parentId) {
+                        parentItem = item;
+                    } else {
+                        parentItem = getItem(parentId);
+                    }
+                    item.setParent(parentItem);
+                }
+                items.add(item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            /*try{
+                if(conn !=null){
+                    conn.close();
+                }
+            }
+            catch (SQLException e){
+                String msg = "Error while closing connection";
+                log.error(msg, e);
+            }*/
+        }
+
+        return items;
+    }
+
+    public int addInvoice(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceId = INVALID;
+
+        try {
+            String sql = "INSERT INTO BC_INVOICE (BC_TENANT_ID, BC_DATE, BC_START_DATE, "
+                    + "BC_END_DATE, BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, "
+                    + "BC_TOTAL_COST) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoice.getCustomer().getId());
+            ps.setTimestamp(2, new Timestamp(invoice.getDate().getTime()));
+            ps.setTimestamp(3, new Timestamp(invoice.getStartDate().getTime()));
+            ps.setTimestamp(4, new Timestamp(invoice.getEndDate().getTime()));
+            ps.setString(5, invoice.getBoughtForward().serializeToString());
+            ps.setString(6, invoice.getCarriedForward().serializeToString());
+            ps.setString(7, invoice.getTotalPayment().serializeToString());
+            ps.setString(8, invoice.getTotalCost().serializeToString());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceId = result.getInt(1);
+                invoice.setId(invoiceId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice for customer, "
+                    + invoice.getCustomer().getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceId;
+    }
+
+    public int addItem(Item item) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int itemId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_ITEM (BC_NAME, BC_COST, BC_DESCRIPTION, " +
+                    "BC_PARENT_ITEM_ID) " +
+                    "VALUES (?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setString(1, item.getName());
+
+
+            Cash cost = item.getCost();
+            if (cost == null) {
+                ps.setString(2, null);
+            } else {
+                ps.setString(2, cost.serializeToString());
+            }
+            ps.setString(3, item.getDescription());
+            if (item.getParent() == null) {
+                ps.setNull(4, Types.INTEGER);
+            } else {
+                ps.setInt(4, item.getParent().getId());
+            }
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                itemId = result.getInt(1);
+                item.setId(itemId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the item, " +
+                    item.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return itemId;
+    }
+
+    // return the existence of the customer
+
+    public void fillCustomerData(int customerId, Customer customer) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            customer.setId(customerId);
+            customer.setName(tenant.getDomain());
+            customer.setStartedDate(tenant.getCreatedDate());
+            customer.setEmail(tenant.getEmail());
+            //customer.setAddress(); //we dont have the address
+        }catch (Exception e){
+            String msg = "Failed to fill the data for customer: " +
+                    customer.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    public List<Customer> getAllCustomers() throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            Tenant[] tenants = tenantManager.getAllTenants();
+            if(tenants!=null && tenants.length>0){
+                for(Tenant tenant : tenants){
+                    Customer customer = new Customer();
+                    customer.setId(tenant.getId());
+                    customer.setName(tenant.getDomain());
+                    customer.setStartedDate(tenant.getCreatedDate());
+                    customer.setEmail(tenant.getEmail());
+                    //customer.setAddress(); //no address yet
+                    customers.add(customer);
+                }
+            }
+        } catch (Exception e){
+            String msg = "Failed to get all the customers.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public List<Item> getAllItems() throws BillingException {
+        Map<Integer, Item> items = new HashMap<Integer, Item>();
+        Map<Item, Integer> itemParents = new HashMap<Item, Integer>();
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_ID, BC_NAME, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM";
+            ps = conn.prepareStatement(sql);
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = new Item();
+                int id = result.getInt("BC_ID");
+                item.setId(id);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    itemParents.put(item, parentId);
+                }
+                items.put(id, item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get all the items.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+
+        // before return resolve all the ids for items who have parents
+        for (Map.Entry<Item, Integer> entry : itemParents.entrySet()) {
+            Item item = entry.getKey();
+            int parentId = entry.getValue();
+            Item parentItem = items.get(parentId);
+            item.setParent(parentItem);
+        }
+        List<Item> returnVal = new ArrayList<Item>();
+        returnVal.addAll(items.values());
+        return returnVal;
+    }
+
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if(tenant!=null){
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        }catch(Exception e){
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public Customer getCustomer(int customerId) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        Customer customer = null;
+
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            if(tenant!=null){
+                customer = new Customer();
+                customer.setId(customerId);
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+            }
+        } catch (Exception e){
+            String msg = "Failed to get customer for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customer;
+    }
+
+    public Item getItem(int itemId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        /*try {
+            conn = DataSourceHolder.getDataSource().getConnection();
+        } catch (SQLException e) {
+            String msg = "Failed to establish data connection";
+            log.error(msg, e);
+        }*/
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_NAME, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, itemId);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                Item item = new Item();
+                item.setId(itemId);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                item.setName(result.getString("BC_NAME"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    Item parentItem;
+                    if (itemId == parentId) {
+                        parentItem = item;
+                    } else {
+                        parentItem = getItem(parentId);
+                    }
+                    item.setParent(parentItem);
+                }
+                return item;
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the item with item id: " + itemId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            /*try{
+                if(conn !=null){
+                    conn.close();
+                }
+            }
+            catch (SQLException e){
+                String msg = "Error while closing connection";
+                log.error(msg, e);
+            }*/
+        }
+
+        return null;
+    }
+
+    public void updateSubscription(Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        try {
+            String sql = "UPDATE BC_SUBSCRIPTION SET BC_IS_ACTIVE=?, " +
+                    "BC_ACTIVE_SINCE=? , BC_ACTIVE_UNTIL=?, BC_ITEM_ID=?, BC_TENANT_ID=? " +
+                    "WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+
+            // updating the subscription
+            ps.setInt(1, subscription.isActive() ? 1 : 0);
+            long activeSinceTime = 0;
+            if (subscription.getActiveSince() != null) {
+                activeSinceTime = subscription.getActiveSince().getTime();
+            }
+            ps.setTimestamp(2, new Timestamp(activeSinceTime));
+            long activeUntilTime = 0;
+            if (subscription.getActiveUntil() != null) {
+                activeUntilTime = subscription.getActiveUntil().getTime();
+            }
+            ps.setTimestamp(3, new Timestamp(activeUntilTime));
+            ps.setInt(4, subscription.getItem().getId());
+            ps.setInt(5, subscription.getCustomer().getId());
+            ps.setInt(6, subscription.getId());
+
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Error in updating the subscription: " + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            }
+            catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    public int addSubscription(Subscription subscription, String filter) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int subscriptionId = -1;
+        try {
+            String sql = "INSERT INTO BC_SUBSCRIPTION (BC_FILTER, BC_IS_ACTIVE, " +
+                    "BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, BC_TENANT_ID) " +
+                    "VALUES (?, ?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the subscription
+            ps.setString(1, filter);
+            ps.setInt(2, subscription.isActive() ? 1 : 0);
+            long activeSinceTime = 0;
+            if (subscription.getActiveSince() != null) {
+                activeSinceTime = subscription.getActiveSince().getTime();
+            }else{
+                activeSinceTime = System.currentTimeMillis();
+                subscription.setActiveSince(new Date(activeSinceTime));
+            }
+            ps.setTimestamp(3, new Timestamp(activeSinceTime));
+            long activeUntilTime = 0;
+
+            if (subscription.getActiveUntil() != null) {
+                activeUntilTime = subscription.getActiveUntil().getTime();
+            }
+            else{
+                //When adding to database each user will activate until 2 years 
+                //from the registration date
+                Calendar activeUntilDate = Calendar.getInstance();
+                activeUntilDate.setTimeInMillis(subscription.getActiveSince().getTime());
+                activeUntilDate.add(Calendar.YEAR,2);
+                activeUntilTime = activeUntilDate.getTimeInMillis();
+            }
+
+            ps.setTimestamp(4, new Timestamp(activeUntilTime));
+            ps.setInt(5, getItemIdWithName(filter));
+
+            //setting the customer id: we dont have the customer id in the customer object
+            //which comes with the subscription object. Therefore we have to get it.
+            if(subscription.getCustomer().getId()==0){
+                int customerId = CustomerUtils.getCustomerId(subscription.getCustomer().getName());
+                if(customerId==0){
+                    throw new BillingException("No customer found with domain: " +
+                            subscription.getCustomer().getName());
+                }
+                ps.setInt(6, customerId);
+            }else{
+                ps.setInt(6, subscription.getCustomer().getId());
+            }
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                subscriptionId = result.getInt(1);
+                subscription.setId(subscriptionId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the subscription.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptionId;
+    }
+
+    public void deleteBillingData(int tenantId) throws Exception {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement deleteSubItemPs = null;
+        PreparedStatement deleteInvoiceSubsPs = null;
+        PreparedStatement deletePaymentSubsPs = null;
+        PreparedStatement deletePaymentPs = null;
+        PreparedStatement deleteInvoicePs = null;
+        PreparedStatement deleteSubscriptionPs = null;
+        try {
+            conn.setAutoCommit(false);
+            String deleteSubItemRecordsSql = "DELETE FROM BC_INVOICE_SUBSCRIPTION_ITEM WHERE BC_INVOICE_SUBSCRIPTION_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?));";
+            deleteSubItemPs = conn.prepareStatement(deleteSubItemRecordsSql);
+            deleteSubItemPs.setInt(1, tenantId);
+            deleteSubItemPs.executeUpdate();
+
+            String deleteInvoiceSubsRecordsSql = "DELETE FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID IN " +
+                                                 "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?) OR " +
+                                                 "BC_SUBSCRIPTION_ID IN (SELECT BC_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?)";
+            deleteInvoiceSubsPs = conn.prepareStatement(deleteInvoiceSubsRecordsSql);
+            deleteInvoiceSubsPs.setInt(1, tenantId);
+            deleteInvoiceSubsPs.setInt(2, tenantId);
+            deleteInvoiceSubsPs.executeUpdate();
+
+            String deletePaymentSubsRecordsSql = "DELETE FROM BC_PAYMENT_SUBSCRIPTION WHERE BC_PAYMENT_ID IN " +
+                                                 "(SELECT BC_ID FROM BC_PAYMENT WHERE BC_TENANT_ID = ?) OR " +
+                                                 "BC_SUBSCRIPTION_ID IN (SELECT BC_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?)";
+            deletePaymentSubsPs = conn.prepareStatement(deletePaymentSubsRecordsSql);
+            deletePaymentSubsPs.setInt(1, tenantId);
+            deletePaymentSubsPs.setInt(2, tenantId);
+            deletePaymentSubsPs.executeUpdate();
+
+            String deletePaymentRecordsSql = "DELETE FROM BC_PAYMENT WHERE BC_INVOICE_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?)";
+            deletePaymentPs = conn.prepareStatement(deletePaymentRecordsSql);
+            deletePaymentPs.setInt(1, tenantId);
+            deletePaymentPs.executeUpdate();
+
+            String deleteInvoiceRecordsSql = "DELETE FROM BC_INVOICE WHERE BC_TENANT_ID = ?";
+            deleteInvoicePs = conn.prepareStatement(deleteInvoiceRecordsSql);
+            deleteInvoicePs.setInt(1, tenantId);
+            deleteInvoicePs.executeUpdate();
+
+            String deleteSubscriptionRecordsSql = "DELETE FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?";
+            deleteSubscriptionPs = conn.prepareStatement(deleteSubscriptionRecordsSql);
+            deleteSubscriptionPs.setInt(1, tenantId);
+            deleteSubscriptionPs.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Failed to delete billing information for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (deleteSubItemPs != null) {
+                    deleteSubItemPs.close();
+                }
+                if (deleteInvoiceSubsPs != null) {
+                    deleteInvoiceSubsPs.close();
+                }
+                if (deletePaymentSubsPs != null) {
+                    deletePaymentSubsPs.close();
+                }
+                if (deletePaymentPs != null) {
+                    deletePaymentPs.close();
+                }
+                if (deleteInvoicePs != null) {
+                    deleteInvoicePs.close();
+                }
+                if (deleteSubscriptionPs != null) {
+                    deleteSubscriptionPs.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    /**
+     * Get all the active subscriptions for a particular filter.
+     * Customers and Items are just dummy objects that only have a valid id.
+     *
+     * @param filter the name of the filter (This is not used.Will be removed from
+     *               the signature in the future trunk).
+     * @return the array of the subscriptions.
+     * @throws BillingException throws if there is an error.
+     */
+    public List<Subscription> getFilteredActiveSubscriptions(String filter) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        Date lastInvoiceDate = getLastInvoiceDate();
+        try {
+            String sql = "";
+            //if the last invoice date is null, that means there has been no bill generation yet.
+            //so we have to consider all the subscriptions
+            if(lastInvoiceDate==null){
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_FILTER, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION";
+                ps = conn.prepareStatement(sql);
+            }else{
+                //this means there has been a previous bill generation. Now we only consider
+                //1. Active subscriptions
+                //2. Inactive subscriptions which ended after the last invoice date
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_FILTER, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE (BC_IS_ACTIVE=?) OR " +
+                        "(BC_IS_ACTIVE=? AND BC_ACTIVE_UNTIL>=?)";
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1,1);
+                ps.setInt(2,0);
+                ps.setTimestamp(3, new Timestamp(lastInvoiceDate.getTime()));
+            }
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActive(result.getInt("BC_IS_ACTIVE")==1);
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+                subscription.setActiveSince(new Date(
+                        result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+
+                // filling with dummy customer
+                Customer customer = new Customer();
+                customer.setId(customerId);
+                subscription.setCustomer(customer);
+                //subscription.setActive(true);
+                subscriptions.add(subscription);
+                // we will fill the payment details too
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscriptions.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    public Invoice getLastInvoice(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Invoice invoice = null;
+        try {
+            String sql = "SELECT BC_ID, BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_COST, BC_TOTAL_PAYMENTS "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=? AND BC_DATE=(SELECT MAX(BC_DATE) "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=?) ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            ps.setInt(2, customer.getId());
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setCustomer(customer);
+                invoice.setDate(result.getTimestamp("BC_DATE"));
+                invoice.setStartDate(result.getTimestamp("BC_START_DATE"));
+                invoice.setEndDate(result.getTimestamp("BC_END_DATE"));
+                String boughtForwardStr = result.getString("BC_BOUGHT_FORWARD");
+                invoice.setBoughtForward(new Cash(boughtForwardStr));
+                String carriedForwardStr = result.getString("BC_CARRIED_FORWARD");
+                invoice.setCarriedForward(new Cash(carriedForwardStr));
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                invoice.setTotalCost(new Cash(totalCostStr));
+                String totalPaymentsStr = result.getString("BC_TOTAL_PAYMENTS");
+                invoice.setTotalPayment(new Cash(totalPaymentsStr));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice for customer: " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoice;
+    }
+
+    public List<Invoice> getAllInvoices(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        List<Invoice> invoices = new ArrayList<Invoice>();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_ID, BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_COST, BC_TOTAL_PAYMENTS "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=? ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Invoice invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setCustomer(customer);
+                invoice.setDate(result.getTimestamp("BC_DATE"));
+                invoice.setStartDate(result.getTimestamp("BC_START_DATE"));
+                invoice.setEndDate(result.getTimestamp("BC_END_DATE"));
+                String boughtForwardStr = result.getString("BC_BOUGHT_FORWARD");
+                invoice.setBoughtForward(new Cash(boughtForwardStr));
+                String carriedForwardStr = result.getString("BC_CARRIED_FORWARD");
+                invoice.setCarriedForward(new Cash(carriedForwardStr));
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                invoice.setTotalCost(new Cash(totalCostStr));
+                String totalPaymentsStr = result.getString("BC_TOTAL_PAYMENTS");
+                invoice.setTotalPayment(new Cash(totalPaymentsStr));
+
+                invoices.add(invoice);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get invoices for customer: " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoices;
+    }
+
+    public void fillUnbilledPayments(Subscription subscription,
+                                     Map<Integer, Payment> payments,
+                                     Invoice invoice) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet results = null;
+        java.sql.Timestamp startDate= new Timestamp(invoice.getStartDate().getTime());
+        java.sql.Timestamp endDate= new Timestamp(invoice.getEndDate().getTime());
+        try {
+            /*String sql = "SELECT P.BC_ID, P.BC_DATE, P.BC_AMOUNT, P.BC_DESCRIPTION " +
+                    " FROM BC_PAYMENT P, BC_PAYMENT_SUBSCRIPTION PS " +
+                    "WHERE PS.BC_SUBSCRIPTION_ID=? AND PS.BC_PAYMENT_ID=P.BC_ID " +
+                    "AND P.BC_INVOICE_ID IS NULL";
+            */
+            String sql = "SELECT P.BC_ID, P.BC_DATE, P.BC_AMOUNT, P.BC_DESCRIPTION " +
+                    " FROM BC_PAYMENT P, BC_PAYMENT_SUBSCRIPTION PS " +
+                    "WHERE PS.BC_SUBSCRIPTION_ID=? AND PS.BC_PAYMENT_ID=P.BC_ID " +
+                    "AND P.BC_DATE>=? AND P.BC_DATE<?";
+
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, subscription.getId());
+            Calendar cal = Calendar.getInstance();
+            cal.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
+            ps.setTimestamp(2, startDate, cal);
+            ps.setTimestamp(3, endDate, cal);
+            results = ps.executeQuery();
+            while (results.next()) {
+                Payment payment;
+                int paymentId = results.getInt("BC_ID");
+                if (payments.get(paymentId) != null) {
+                    payment = payments.get(paymentId);
+                } else {
+                    payment = new Payment();
+                    payment.setId(paymentId);
+                    payment.setDate(results.getTimestamp("BC_DATE"));
+                    payment.setDescription(results.getString("BC_DESCRIPTION"));
+                    String amount = results.getString("BC_AMOUNT");
+                    if (amount == null) {
+                        amount = "0";
+                    }
+                    Cash paymentCash = new Cash(amount);
+                    payment.setAmount(paymentCash);
+                    payments.put(paymentId, payment);
+                }
+                payment.addSubscription(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to fill the payment for subscription: "
+                    + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (results != null) {
+                    results.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    public void associatePaymentWithInvoice(Payment payment,
+                                            Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        try {
+            String sql = "UPDATE BC_PAYMENT SET BC_INVOICE_ID=? WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+
+            // inserting the data values
+            ps.setInt(1, invoice.getId());
+            ps.setInt(2, payment.getId());
+
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Error in associating invoice: " + invoice.getId() +
+                    " with payment: " + payment.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+        }
+    }
+
+    public int addInvoiceSubscription(Invoice invoice,
+                                      Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceSubscriptionId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_INVOICE_SUBSCRIPTION (BC_INVOICE_ID, BC_SUBSCRIPTION_ID) "
+                    + "VALUES (?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoice.getId());
+            ps.setInt(2, subscription.getId());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceSubscriptionId = result.getInt(1);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice subscription, invoice id: " +
+                    invoice.getId() + ", subscription id: " + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceSubscriptionId;
+    }
+
+    public int addInvoiceSubscriptionItem(Item item,
+                                          int invoiceSubscriptionId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceSubscriptionItemId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_INVOICE_SUBSCRIPTION_ITEM (BC_INVOICE_SUBSCRIPTION_ID, " +
+                    "BC_ITEM_ID, BC_COST, BC_DESCRIPTION) VALUES (?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoiceSubscriptionId);
+            ps.setInt(2, item.getId());
+            if(item.getCost()!=null){
+                ps.setString(3, item.getCost().serializeToString());
+            }else{
+                ps.setString(3, new Cash("$0").serializeToString());
+            }
+            ps.setString(4, item.getDescription());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceSubscriptionItemId = result.getInt(1);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice subscription item, item id: " +
+                    item.getId() + ", invoice subscription id: " + invoiceSubscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceSubscriptionItemId;
+    }
+
+
+    public int addPayment(Payment payment) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int paymentId = INVALID;
+        int invoiceId = INVALID;
+        int customerId = INVALID;
+        if (payment.getInvoice() != null) {
+            invoiceId = payment.getInvoice().getId();
+        }
+        if(invoiceId!=INVALID){
+            customerId = getCustomerIdFromInvoiceId(invoiceId);
+        }
+        try {
+            String sql = "INSERT INTO BC_PAYMENT (BC_DATE, BC_AMOUNT, " +
+                    "BC_DESCRIPTION, BC_INVOICE_ID, BC_TENANT_ID) " +
+                    "VALUES (?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data
+            long paymentTime = System.currentTimeMillis();
+            //there was a problem of time shown as 00:00:00 when getting the date sent
+            //from frontend. Therefore, to get rid of it, I am creating the timestamp
+            //by getting the current time. This may be a few seconds different from the
+            //time sent from frontend
+            /*if (payment.getDate() != null) {
+                paymentTime = payment.getDate().getTime();
+            }*/
+            ps.setTimestamp(1, new Timestamp(paymentTime));
+            ps.setString(2, payment.getAmount().serializeToString());
+            ps.setString(3, payment.getDescription());
+            if (invoiceId == INVALID) {
+                ps.setNull(4, Types.INTEGER);
+            } else {
+                ps.setInt(4, invoiceId);
+            }
+            if(customerId == INVALID){
+                ps.setNull(5, Types.INTEGER);
+            }else{
+                ps.setInt(5, customerId);
+            }
+
+            ps.executeUpdate();
+
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                paymentId = result.getInt(1);
+                payment.setId(paymentId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the payment, payment id: " + paymentId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        // adn then insert the subscriptions
+        addPaymentSubscriptionsEntry(payment);
+        return paymentId;
+    }
+
+    public void addPaymentSubscriptionsEntry(Payment payment) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        List<Subscription> subscriptions = payment.getSubscriptions();
+        if (subscriptions == null) {
+            return;
+        }
+        try {
+            for (Subscription subscription : subscriptions) {
+                String sql = "INSERT INTO BC_PAYMENT_SUBSCRIPTION ( " +
+                        "BC_PAYMENT_ID, BC_SUBSCRIPTION_ID) " +
+                        "VALUES (?, ?)";
+                ps = conn.prepareStatement(sql);
+
+                // inserting the data
+                ps.setInt(1, payment.getId());
+                ps.setInt(2, subscription.getId());
+
+                ps.executeUpdate();
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the payment subscriptions, " +
+                    "payment id: " + payment.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+        }
+    }
+
+    public int addRegistrationPayment(Payment payment, String usagePlan) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int paymentId = INVALID;
+        String tenantDomain = payment.getDescription().split(" ")[0];
+        try {
+            int tenantId = Util.getRealmService().getTenantManager().getTenantId(tenantDomain);
+            String sql = "INSERT INTO BC_REGISTRATION_PAYMENT (BC_DATE, BC_AMOUNT, " +
+                         "BC_DESCRIPTION, BC_USAGE_PLAN, BC_TENANT_ID) " +
+                         "VALUES (?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data
+            long paymentTime = System.currentTimeMillis();
+            ps.setTimestamp(1, new Timestamp(paymentTime));
+            ps.setString(2, payment.getAmount().serializeToString());
+            ps.setString(3, payment.getDescription().split(" ")[1]);
+            ps.setString(4, usagePlan);
+            ps.setInt(5, tenantId);
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                paymentId = result.getInt(1);
+                payment.setId(paymentId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the registration payment record, id: " + paymentId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } catch (UserStoreException e) {
+            String msg = "Failed to get tenant id of registration payment for: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return paymentId;
+    }
+
+    public List<Subscription> getFilteredActiveSubscriptionsForCustomer(String filter, Customer customer)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        Date lastInvoiceDate = getLastInvoiceDate();
+        try {
+            String sql="";
+            if(lastInvoiceDate==null){
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE " +
+                    "BC_TENANT_ID=? ORDER BY BC_ACTIVE_UNTIL DESC"; //not sure whether this
+                                                                                           //ORDER BY is necessary
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1, customer.getId());
+            }else{
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID=? AND " +
+                        "((BC_IS_ACTIVE=? ) OR (BC_IS_ACTIVE=? AND BC_ACTIVE_UNTIL>=?)) ORDER BY BC_ACTIVE_UNTIL DESC";
+
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1, customer.getId());
+                ps.setInt(2, 1);             //active=true
+                ps.setInt(3, 0);             //active=false
+                ps.setTimestamp(4, new Timestamp(lastInvoiceDate.getTime()));
+            }
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActive(result.getInt("BC_IS_ACTIVE")==1);
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                subscription.setCustomer(customer);
+                //subscription.setActive(true);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscriptions for " +
+                    "customer = " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    /**
+     * this doesn't load the subscriptions
+     *
+     * @param customer
+     * @return
+     * @throws BillingException
+     */
+    public List<Invoice> getInvoices(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Invoice> invoices = new ArrayList<Invoice>();
+        try {
+            String sql = "SELECT BC_ID, BC_DATE, BC_START_DATE, BC_END_DATE, BC_BOUGHT_FORWARD, "
+                    + "BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, BC_TOTAL_COST FROM BC_INVOICE "
+                    + "WHERE BC_TENANT_ID=? ORDER BY BC_DATE DESC";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Invoice invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+                invoice.setStartDate(new Date(result.getTimestamp("BC_START_DATE").getTime()));
+                invoice.setEndDate(new Date(result.getTimestamp("BC_END_DATE").getTime()));
+                invoice.setCustomer(customer);
+
+                String bfStr = result.getString("BC_BOUGHT_FORWARD");
+                if (bfStr == null) {
+                    bfStr = "$0";
+                }
+                invoice.setBoughtForward(new Cash(bfStr));
+
+                String cfStr = result.getString("BC_CARRIED_FORWARD");
+                if (cfStr == null) {
+                    cfStr = "$0";
+                }
+                invoice.setCarriedForward(new Cash(cfStr));
+
+                String totalPayStr = result.getString("BC_TOTAL_PAYMENTS");
+                if (totalPayStr == null) {
+                    totalPayStr = "$0";
+                }
+                invoice.setTotalPayment(new Cash(totalPayStr));
+
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                if (totalCostStr == null) {
+                    totalCostStr = "$0";
+                }
+                invoice.setTotalCost(new Cash(totalCostStr));
+                invoices.add(invoice);
+            }
+        } catch (SQLException e) {
+            String msg =
+                    "Failed to get the invoice for: " + "customer = " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg =
+                        RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                                ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoices;
+    }
+
+    /**
+     * this load the subscriptions and payments associated
+     *
+     * @param invoiceId
+     * @return
+     * @throws BillingException
+     */
+    public Invoice getInvoice(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Invoice invoice = null;
+        try {
+            String sql = "SELECT BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, BC_TOTAL_COST "
+                    + "FROM BC_INVOICE WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                invoice = new Invoice();
+
+                invoice.setEndDate(new Date(result.getTimestamp("BC_END_DATE").getTime()));
+                invoice.setId(invoiceId);
+                invoice.setStartDate(new Date(result.getTimestamp("BC_START_DATE").getTime()));
+                invoice.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+
+                String bfStr = result.getString("BC_BOUGHT_FORWARD");
+                if (bfStr == null) {
+                    bfStr = "$0";
+                }
+                invoice.setBoughtForward(new Cash(bfStr));
+
+                String cfStr = result.getString("BC_CARRIED_FORWARD");
+                if (cfStr == null) {
+                    cfStr = "$0";
+                }
+                invoice.setCarriedForward(new Cash(cfStr));
+
+                String totalPayStr = result.getString("BC_TOTAL_PAYMENTS");
+                if (totalPayStr == null) {
+                    totalPayStr = "$0";
+                }
+                invoice.setTotalPayment(new Cash(totalPayStr));
+
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                if (totalCostStr == null) {
+                    totalCostStr = "$0";
+                }
+                invoice.setTotalCost(new Cash(totalCostStr));
+
+                int customerId = result.getInt("BC_TENANT_ID");
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                invoice.setCustomer(customer);
+
+                fillInvoiceSubscriptions(invoice);
+                fillInvoicePayments(invoice);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice for: " + "invoice id = " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                        ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoice;
+    }
+
+    private void fillInvoicePayments(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int customerId = INVALID;
+        //int invoiceId = invoice.getId();
+        if(invoice.getCustomer()==null){
+            return;
+        }else{
+            customerId = invoice.getCustomer().getId();
+        }
+        java.sql.Timestamp startDate = new Timestamp(invoice.getStartDate().getTime());
+        java.sql.Timestamp endDate = new Timestamp(invoice.getEndDate().getTime());
+        List<Payment> payments = new ArrayList<Payment>();
+
+        try {
+            /*String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION "
+                    + "FROM BC_PAYMENT WHERE BC_INVOICE_ID=?";
+            */
+            String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION "
+                    + "FROM BC_PAYMENT WHERE BC_TENANT_ID=? AND BC_DATE>=? AND BC_DATE<?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customerId);
+            Calendar cal = Calendar.getInstance();
+            cal.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
+            ps.setTimestamp(2, startDate, cal);
+            ps.setTimestamp(3, endDate, cal);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Payment payment = new Payment();
+                payment.setId(result.getInt("BC_ID"));
+                String cashPayment = result.getString("BC_AMOUNT");
+                payment.setAmount(new Cash(cashPayment));
+                payment.setDate(result.getTimestamp("BC_DATE"));
+                payment.setDescription(result.getString("BC_DESCRIPTION"));
+
+                payments.add(payment);
+            }
+        } catch (SQLException e) {
+            String msg =
+                    "Failed to get the invoice payments for: " + "invoice id = " + invoice.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        invoice.setPayments(payments);
+    }
+
+    private void fillInvoiceSubscriptions(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceId = invoice.getId();
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+
+        try {
+            String sql = "SELECT BC_ID, BC_SUBSCRIPTION_ID "
+                    + "FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                int invoiceSubscriptionId = result.getInt("BC_ID");
+                int subscriptionId = result.getInt("BC_SUBSCRIPTION_ID");
+                Subscription subscription = getSubscription(subscriptionId);
+                subscription.setInvoiceSubscriptionId(invoiceSubscriptionId);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice subscriptions for: " + "invoice id = "
+                    + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                        ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        invoice.setSubscriptions(subscriptions);
+    }
+
+    public Subscription getSubscription(int subscriptionId)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Subscription subscription = null;
+        try {
+            String sql = "SELECT BC_ID, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID, BC_IS_ACTIVE, BC_FILTER FROM BC_SUBSCRIPTION WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, subscriptionId);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                subscription = new Subscription();
+                subscription.setId(subscriptionId);
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+                // filling with dummy item
+                Item item = getItem(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                subscription.setCustomer(customer);
+                int isActive = result.getInt("BC_IS_ACTIVE");
+                subscription.setActive(isActive == 1);
+                //subscription plan name
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscription for id: " + subscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscription;
+    }
+
+        public Subscription getActiveSubscriptionOfCustomer(int customerId)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Subscription subscription = null;
+        try {
+            String sql = "SELECT BC_ID, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID, BC_IS_ACTIVE, BC_FILTER FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID=? AND BC_IS_ACTIVE=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customerId);
+            ps.setInt(2,1);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                // filling with dummy item
+                Item item = getItem(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                subscription.setCustomer(customer);
+                int isActive = result.getInt("BC_IS_ACTIVE");
+                subscription.setActive(isActive == 1);
+                //subscription plan name
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscription for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscription;
+    }
+
+    public List<Item> getBilledItems(Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+
+        int invoiceSubscriptionId = subscription.getInvoiceSubscriptionId();
+        if (invoiceSubscriptionId == INVALID) {
+            String msg = "Not a invoiced subscription, subscription id: "
+                    + subscription.getId() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+
+        List<Item> items = new ArrayList<Item>();
+        try {
+            String sql = "SELECT BC_ITEM_ID, BC_COST, BC_DESCRIPTION " +
+                    "FROM BC_INVOICE_SUBSCRIPTION_ITEM WHERE BC_INVOICE_SUBSCRIPTION_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceSubscriptionId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = getItem(result.getInt("BC_ITEM_ID"));
+                String cost = result.getString("BC_COST");
+                String description = result.getString("BC_DESCRIPTION");
+                if (cost != null) {
+                    item.setCost(new Cash(cost));
+                }
+                if(description!=null && !"".equals(description)){
+                    item.setDescription(description);
+                }
+                items.add(item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoiced subscription items for " +
+                    "invoice subscription id: " + invoiceSubscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return items;
+    }
+
+    public List<Subscription> getInvoiceSubscriptions(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+
+        try {
+            String sql = "SELECT S.BC_ID, S.BC_FILTER, S.BC_IS_ACTIVE, S.BC_ACTIVE_SINCE, S.BC_ACTIVE_UNTIL, S.BC_ITEM_ID, S.BC_TENANT_ID FROM " +
+                        "BC_SUBSCRIPTION S, BC_INVOICE_SUBSCRIPTION BIS " +
+                        "WHERE S.BC_ID=BIS.BC_SUBSCRIPTION_ID AND BIS.BC_INVOICE_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+                subscription.setActiveSince(new Date(
+                        result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+                boolean isActive = result.getBoolean("BC_IS_ACTIVE");
+
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+
+                // filling with dummy customer
+                Customer customer = new Customer();
+                customer.setId(customerId);
+                subscription.setCustomer(customer);
+                subscription.setActive(isActive);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice subscriptions for invoice: " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    private int getCustomerIdFromInvoiceId(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int customerId = INVALID;
+
+        try {
+            String sql = "SELECT BC_TENANT_ID FROM BC_INVOICE WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                customerId = result.getInt("BC_TENANT_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the customer Id for invoice: " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return customerId;
+    }
+
+    public Payment getLastPayment(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Payment payment = null;
+        try {
+            String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION FROM BC_PAYMENT WHERE BC_TENANT_ID=?" +
+                        " AND BC_DATE=(SELECT MAX(BC_DATE) FROM BC_PAYMENT WHERE BC_TENANT_ID=?) ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            ps.setInt(2, customer.getId());
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                payment = new Payment();
+                payment.setAmount(new Cash(result.getString("BC_AMOUNT")));
+                payment.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+                payment.setDescription(result.getString("BC_DESCRIPTION"));
+            }
+        } catch (SQLException e)

<TRUNCATED>

[14/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl.xsl
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl.xsl b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl.xsl
new file mode 100644
index 0000000..bdfd057
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl.xsl
@@ -0,0 +1,702 @@
+<?xml version="1.0"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
+                xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+                xmlns:wsoap="http://schemas.xmlsoap.org/wsdl/soap/"
+                xmlns:xs="http://www.w3.org/2001/XMLSchema"
+                exclude-result-prefixes="wsdl xs wsoap">
+    <!--
+         Created by: Jonathan Marsh <jo...@wso2.com>
+         23 October 2006
+         7 November 2006 - JM: code review and cleanup + linked binding operations, added support for xs:import, wsdl:import
+     -->
+    <xsl:import href="annotated-xsd.xsl"/>
+
+    <xsl:output method="html" indent="yes" encoding="UTF-8"/>
+
+    <!--
+         Many schemas refer to the built-in schema types.  In order to navigate to those types, one needs
+         to know where to load the schema for schemas, hopefully a local version with this stylesheet
+         applied so the user can continue to navigate.
+     -->
+    <xsl:param name="xsd-schema-location" select="'/service-mgt/styles/XMLSchema.xsd'"/>
+
+    <!-- QName resolving functions require the targetNamespace, so stuff it in a global variable. -->
+    <xsl:variable name="targetNamespace" select="wsdl:definitions/@targetNamespace"/>
+    <xsl:variable name="schemaTargetNamespace"
+                  select="wsdl:definitions/wsdl:types/xs:schema/@targetNamespace"/>
+
+    <!-- Mozilla doesn't support the namespace axis, which makes simulating namespace declarations
+     problematic.  At least we can try alternate reconstruction methods if we know the functionality
+     isn't there.  -->
+    <xsl:variable name="supports-namespace-axis" select="count(/*/namespace::*) &gt; 0"/>
+
+    <!-- ===  Main  ========================================
+         Main template for the wsdl document
+     -->
+    <xsl:template match="/">
+        <html>
+            <head>
+                <title>WSDL 1.1 for
+                    <xsl:value-of select="wsdl:definitions/@targetNamespace"/>
+                </title>
+                <style type="text/css">
+                    <xsl:call-template name="css"/>
+                    <![CDATA[
+.annotation-area {width:19em}
+.schema-block {background-color:#EEE;}
+.schema {padding-left:7em; text-indent:-5em}
+.schema-top-level {padding-left: 8em; text-indent:-5em}
+.wsdl-top-level {padding-left: 6em; text-indent:-5em}
+.wsdl-second-level {padding-left: 7em; text-indent:-5em}
+.wsdl-message {padding-left: 6em; text-indent:-5em}
+
+.definitions {padding-left:5em; margin-bottom:1em; text-indent:-5em}
+.operation   {background-color:rgb(215,206,221); text-align:right; border: 1px dashed black; padding:.5em} 
+.message     {background-color:rgb(240,206,206); text-align:right; border: 1px dashed black; padding:.5em} 
+.portType    {background-color:rgb(185,218,192); text-align:right; border: 1px dashed black; padding:.5em} 
+.binding     {background-color:rgb(218,208,185); text-align:right; border: 1px dashed black; padding:.5em} 
+.service     {background-color:rgb(240,197,166); text-align:right; border: 1px dashed black; padding:.5em} 
+]]>
+                </style>
+            </head>
+            <body>
+                <xsl:apply-templates select="wsdl:definitions"/>
+                <p/>
+                <hr/>
+                <table cellpadding="0" cellspacing="0" id="index">
+                    <xsl:if test="wsdl:definitions/wsdl:types/xs:schema">
+                        <xsl:for-each select="wsdl:definitions/wsdl:types">
+                            <xsl:call-template name="generate-xsd-index"/>
+                        </xsl:for-each>
+                    </xsl:if>
+                    <xsl:call-template name="generate-wsdl-index"/>
+                </table>
+            </body>
+        </html>
+    </xsl:template>
+    <!-- ===  Elements  ========================================
+         The following templates format elements of various flavors
+         (xs:schema, children of xs:schema, grandchildren etc. of schema, and extension elements
+     -->
+    <xsl:template match="wsdl:definitions">
+        <table cellpadding="0" cellspacing="0">
+            <tr>
+                <td class="annotation-area">
+                    <div class="sidebar">
+                        <xsl:call-template name="index-reference"/>
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <div class="definitions">
+                        <xsl:call-template name="element-start"/>
+                    </div>
+                </td>
+            </tr>
+            <xsl:apply-templates/>
+            <tr>
+                <td colspan="2" class="annotation-area"/>
+                <td class="source-area">
+                    <div class="definitions">
+                        <xsl:call-template name="element-end"/>
+                    </div>
+                </td>
+            </tr>
+        </table>
+    </xsl:template>
+    <xsl:template match="wsdl:definitions/wsdl:*">
+        <xsl:variable name="identifier">
+            <xsl:if test="@name">
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="local-name()"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="@name"/>
+            </xsl:if>
+        </xsl:variable>
+        <tr>
+            <xsl:choose>
+                <xsl:when
+                        test="not(self::wsdl:documentation or self::wsdl:import or self::wsdl:include)">
+                    <td class="annotation-area">
+                        <div class="sidebar {local-name()} sidebar-title">
+                            <xsl:if test="$identifier">
+                                <xsl:attribute name="id">
+                                    <xsl:value-of select="$identifier"/>
+                                </xsl:attribute>
+                            </xsl:if>
+                            <span class="sidebar-title-highlight">
+                                <xsl:value-of select="@name"/>
+                            </span>
+                            <xsl:text></xsl:text>
+                            <xsl:value-of select="local-name()"/>
+                            <xsl:call-template name="wsdl-referenced-by"/>
+                        </div>
+                    </td>
+                    <td>
+                        <div class="arrow">&#160;</div>
+                    </td>
+                </xsl:when>
+                <xsl:otherwise>
+                    <td colspan="2" class="annotation-area"/>
+                </xsl:otherwise>
+            </xsl:choose>
+            <td class="source-area">
+                <div>
+                    <xsl:choose>
+                        <xsl:when test="self::wsdl:message">
+                            <xsl:attribute name="class">wsdl-message</xsl:attribute>
+                        </xsl:when>
+                        <xsl:otherwise>
+                            <xsl:attribute name="class">wsdl-top-level</xsl:attribute>
+                        </xsl:otherwise>
+                    </xsl:choose>
+                    <xsl:call-template name="element-start"/>
+                </div>
+                <div class="wsdl-top-level">
+                    <xsl:apply-templates/>
+                </div>
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:definitions/wsdl:portType">
+        <tr>
+            <td class="annotation-area">
+                <div class="sidebar portType sidebar-title">
+                    <a name="_portType_{@name}"></a>
+                    <span class="sidebar-title-highlight">
+                        <xsl:value-of select="@name"/>
+                    </span>
+                    <xsl:text></xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                    <xsl:call-template name="wsdl-referenced-by"/>
+                    <xsl:call-template name="interface-defines"/>
+                </div>
+            </td>
+            <td>
+                <div class="arrow">&#160;</div>
+            </td>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-start"/>
+                    <xsl:apply-templates select="wsdl:documentation"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates select="node()[not(self::wsdl:documentation)]"/>
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:portType/wsdl:operation">
+        <tr>
+            <td class="annotation-area">
+                <div class="sidebar operation sidebar-title">
+                    <a name="_operation_{@name}"></a>
+                    <span class="sidebar-title-highlight">
+                        <xsl:value-of select="@name"/>
+                    </span>
+                    <xsl:text></xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                    <xsl:call-template name="wsdl-referenced-by"/>
+                </div>
+            </td>
+            <td>
+                <div class="arrow">&#160;</div>
+            </td>
+            <td class="source-area">
+                <div class="wsdl-second-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+                <div class="wsdl-second-level">
+                    <xsl:apply-templates/>
+                </div>
+                <div class="wsdl-second-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:definitions/wsdl:types">
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates/>
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:schema">
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-start"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates/>
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:*">
+        <xsl:apply-imports/>
+    </xsl:template>
+    <xsl:template match="wsdl:* | wsoap:*">
+        <div class="indent">
+            <div>
+                <xsl:call-template name="element-start"/>
+            </div>
+            <xsl:apply-templates/>
+            <div>
+                <xsl:call-template name="element-end"/>
+            </div>
+        </div>
+    </xsl:template>
+
+    <!-- ===  Attributes  =========================================
+         The following templates format attributes of various flavors
+     -->
+    <xsl:template match="wsdl:*/@id">
+        <a name="{@id}"/>
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:binding/wsdl:operation/@name" priority="1">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-wsdl-reference"/>
+                <xsl:text>#_operation_</xsl:text>
+                <xsl:value-of select="."/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:*/@name">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:part/@element">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_</xsl:text>
+                <xsl:value-of select="name()"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template
+            match="wsdl:input/@message | wsdl:output/@message | wsdl:port/@binding | wsdl:binding/@type">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-wsdl-reference"/>
+                <xsl:text>#_</xsl:text>
+                <xsl:choose>
+                    <xsl:when test="name() = 'type'">portType</xsl:when>
+                    <xsl:otherwise>
+                        <xsl:value-of select="name()"/>
+                    </xsl:otherwise>
+                </xsl:choose>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:*/@id">
+        <a name="{@id}"/>
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:*/@* | wsoap:*/@*" priority="0">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+
+    <!-- ===  Comments  ========================================
+         The following template formats comment nodes
+     -->
+    <xsl:template match="wsdl:definitions/comment()">
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="schema-top-level source-area">
+                <div class="markup-comment">
+                    <xsl:text>&lt;!--</xsl:text>
+                    <xsl:value-of select="."/>
+                    <xsl:text>--&gt;</xsl:text>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:portType/comment()">
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="wsdl-second-level source-area">
+                <div class="markup-comment">
+                    <xsl:text>&lt;!--</xsl:text>
+                    <xsl:value-of select="."/>
+                    <xsl:text>--&gt;</xsl:text>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+
+    <!-- ===  Library templates  ========================================
+         Library of useful named templates
+     -->
+    <xsl:template name="insert-wsdl-reference">
+        <xsl:if test="parent::wsdl:operation">
+            <a href="#_operation_{../@name}">
+                <xsl:value-of select="../@name"/>
+            </a>
+            <xsl:text>operation of the</xsl:text>
+        </xsl:if>
+        <xsl:for-each select="ancestor-or-self::*[last() - 1]">
+            <a href="#_{local-name(.)}_{@name}">
+                <xsl:value-of select="@name"/>
+            </a>
+            <xsl:text></xsl:text>
+            <xsl:value-of select="local-name(.)"/>
+        </xsl:for-each>
+    </xsl:template>
+    <xsl:template name="wsdl-referenced-by">
+        <xsl:variable name="target" select="@name"/>
+        <xsl:if test="parent::wsdl:definitions">
+            <div class="sidebar-text">
+                <xsl:variable name="extended-by" select="//wsdl:*[substring-after(@element | @message | @binding
+					| @type,':') = $target]"/>
+                <xsl:if test="count($extended-by) > 0">
+                    <div class="referenced-list">Referenced by:</div>
+                    <ul>
+                        <xsl:for-each select="$extended-by">
+                            <xsl:sort select="@element | @message | @binding | @type"/>
+                            <li class="referenced-item">
+                                <xsl:call-template name="insert-wsdl-reference"/>
+                            </li>
+                        </xsl:for-each>
+                    </ul>
+                </xsl:if>
+            </div>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="interface-defines">
+        <xsl:variable name="target" select="@name"/>
+        <div class="sidebar-text">
+            <xsl:if test="wsdl:operation">
+                <div class="referenced-list">Defines operations:</div>
+                <ul>
+                    <xsl:for-each select="wsdl:operation">
+                        <xsl:sort select="@name"/>
+                        <li class="referenced-item">
+                            <a href="#_operation_{@name}">
+                                <xsl:value-of select="@name"/>
+                            </a>
+                        </li>
+                    </xsl:for-each>
+                </ul>
+            </xsl:if>
+        </div>
+    </xsl:template>
+    <xsl:template name="additional-references">
+        <xsl:param name="target"/>
+        <xsl:variable name="referenced-by"
+                      select="/wsdl:definitions/wsdl:message/wsdl:part[substring-after(@element,':') = $target]"/>
+        <xsl:if test="count($referenced-by) > 0">
+            <div class="referenced-list">Referenced from WSDL by:</div>
+            <ul>
+                <xsl:for-each select="$referenced-by">
+                    <xsl:sort select="@element"/>
+                    <li class="referenced-item">
+                        <xsl:call-template name="insert-wsdl-reference"/>
+                    </li>
+                </xsl:for-each>
+            </ul>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="external-wsdl-reference">
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <xsl:if test="not(../namespace::*[. = $targetNamespace and name(.) =
+					substring-before(current(),':')])">
+                    <xsl:variable name="prefix" select="substring-before(.,':')"/>
+                    <xsl:variable name="uri" select="../namespace::*[name(.) = $prefix]"/>
+                    <xsl:value-of
+                            select="/wsdl:definitions/wsdl:import[@namespace=$uri]/@location"/>
+                </xsl:if>
+            </xsl:when>
+            <xsl:otherwise>
+                <xsl:choose>
+                    <xsl:when
+                            test="substring-before(current(),':')= 'xs' or substring-before(current(),':')= 'xsd'">
+                        <xsl:value-of select="$xsd-schema-location"/>
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <!-- the link is broken - Bad Mozilla -->
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="external-schema-reference">
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <xsl:if test="not(../namespace::*[. = $schemaTargetNamespace and name(.) =
+					substring-before(current(),':')])">
+                    <xsl:variable name="prefix" select="substring-before(.,':')"/>
+                    <xsl:variable name="uri" select="../namespace::*[name(.) = $prefix]"/>
+                    <xsl:choose>
+                        <xsl:when test="$uri = 'http://www.w3.org/2001/XMLSchema'">
+                            <xsl:value-of select="$xsd-schema-location"/>
+                        </xsl:when>
+                        <xsl:otherwise>
+                            <xsl:value-of
+                                    select="/wsdl:definitions/wsdl:types/xs:schema/xs:import[@namespace=$uri]/@schemaLocation"/>
+                        </xsl:otherwise>
+                    </xsl:choose>
+                </xsl:if>
+            </xsl:when>
+            <xsl:otherwise>
+                <xsl:choose>
+                    <xsl:when
+                            test="substring-before(current(),':')= 'xs' or substring-before(current(),':')= 'xsd'">
+                        <xsl:value-of select="$xsd-schema-location"/>
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <!-- the link is broken - Bad Mozilla -->
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="generate-wsdl-index">
+        <xsl:if test="wsdl:definitions/wsdl:message">
+            <tr>
+                <td id="message-list" class="annotation-area">
+                    <div class="message sidebar sidebar-title-highlight">Index of messages</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:definitions/wsdl:message">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:definitions/wsdl:portType">
+            <tr>
+                <td id="portType-list" class="annotation-area">
+                    <div class="portType sidebar sidebar-title-highlight">Index of portTypes</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:definitions/wsdl:portType">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:definitions/wsdl:portType/wsdl:operation">
+            <tr>
+                <td id="operation-list" class="annotation-area">
+                    <div class="operation sidebar sidebar-title-highlight">Index of operations</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:definitions/wsdl:portType/wsdl:operation">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:definitions/wsdl:binding">
+            <tr>
+                <td id="binding-list" class="annotation-area">
+                    <div class="binding sidebar sidebar-title-highlight">Index of bindings</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:definitions/wsdl:binding">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:definitions/wsdl:service">
+            <tr>
+                <td id="service-list" class="annotation-area">
+                    <div class="service sidebar sidebar-title-highlight">Index of services</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:definitions/wsdl:service">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="index-reference">
+        <div class="note sidebar-text">See the
+            <a href="#index">index</a>
+            of
+            <xsl:variable name="ss1">
+                <xsl:if test="wsdl:types/xs:schema/xs:complexType">
+                    <a href="#complexType-list">complexTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss2">
+                <xsl:copy-of select="$ss1"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:simpleType">
+                    <xsl:if test="$ss1!=''">,</xsl:if>
+                    <a href="#simpleType-list">simpleTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss3">
+                <xsl:copy-of select="$ss2"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:element">
+                    <xsl:if test="$ss2!=''">,</xsl:if>
+                    <a href="#global-element-list">global elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss4">
+                <xsl:copy-of select="$ss3"/>
+                <xsl:if test="wsdl:types/xs:schema/*//xs:element[@name]">
+                    <xsl:if test="$ss3!=''">,</xsl:if>
+                    <a href="#local-element-list">local elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss5">
+                <xsl:copy-of select="$ss4"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:attribute">
+                    <xsl:if test="$ss4!=''">,</xsl:if>
+                    <a href="#global-attribute-list">global attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss6">
+                <xsl:copy-of select="$ss5"/>
+                <xsl:if test="wsdl:types/xs:schema/*//xs:attribute[@name]">
+                    <xsl:if test="$ss5!=''">,</xsl:if>
+                    <a href="#local-attribute-list">local attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss7">
+                <xsl:copy-of select="$ss6"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:group">
+                    <xsl:if test="$ss6!=''">,</xsl:if>
+                    <a href="#model-group-list">model groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss8">
+                <xsl:copy-of select="$ss7"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:attributeGroup">
+                    <xsl:if test="$ss7!=''">,</xsl:if>
+                    <a href="#attributeGroup-list">attribute groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss9">
+                <xsl:copy-of select="$ss8"/>
+                <xsl:if test="wsdl:message">
+                    <xsl:if test="$ss8!=''">,</xsl:if>
+                    <a href="#message-list">messages</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss10">
+                <xsl:copy-of select="$ss9"/>
+                <xsl:if test="wsdl:portType">
+                    <xsl:if test="$ss9!=''">,</xsl:if>
+                    <a href="#portType-list">portTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss11">
+                <xsl:copy-of select="$ss10"/>
+                <xsl:if test="wsdl:portType/wsdl:operation">
+                    <xsl:if test="$ss10!=''">,</xsl:if>
+                    <a href="#operation-list">operations</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss12">
+                <xsl:copy-of select="$ss11"/>
+                <xsl:if test="wsdl:binding">
+                    <xsl:if test="$ss11!=''">,</xsl:if>
+                    <a href="#binding-list">bindings</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss13">
+                <xsl:copy-of select="$ss12"/>
+                <xsl:if test="wsdl:service">
+                    <xsl:if test="$ss12!=''">,</xsl:if>
+                    <a href="#service-list">services</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:copy-of select="$ss13"/>
+            <xsl:text>defined in this wsdl</xsl:text>
+        </div>
+    </xsl:template>
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl2.xsl
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl2.xsl b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl2.xsl
new file mode 100644
index 0000000..cdb07fd
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-wsdl2.xsl
@@ -0,0 +1,721 @@
+<?xml version="1.0"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
+                xmlns:wsdl="http://www.w3.org/ns/wsdl"
+                xmlns:wsoap="http://www.w3.org/ns/wsdl/soap"
+                xmlns:whttp="http://www.w3.org/ns/wsdl/http"
+                xmlns:wrpc="http://www.w3.org/ns/wsdl/rpc"
+                xmlns:xs="http://www.w3.org/2001/XMLSchema"
+                exclude-result-prefixes="wsdl xs wsoap">
+    <!--
+         Created by: Jonathan Marsh <jo...@wso2.com>
+         8 November 2006
+     -->
+    <xsl:import href="annotated-xsd.xsl"/>
+
+    <xsl:output method="html" indent="yes" encoding="UTF-8"/>
+
+    <!--
+         Many schemas refer to the built-in schema types.  In order to navigate to those types, one needs
+         to know where to load the schema for schemas, hopefully a local version with this stylesheet
+         applied so the user can continue to navigate.
+     -->
+    <xsl:param name="xsd-schema-location" select="'/service-mgt/styles/XMLSchema.xsd'"/>
+
+    <!-- QName resolving functions require the targetNamespace, so stuff it in a global variable. -->
+    <xsl:variable name="targetNamespace" select="wsdl:description/@targetNamespace"/>
+    <xsl:variable name="schemaTargetNamespace"
+                  select="wsdl:description/wsdl:types/xs:schema/@targetNamespace"/>
+
+    <!-- Mozilla doesn't support the namespace axis, which makes simulating namespace declarations
+     problematic.  At least we can try alternate reconstruction methods if we know the functionality
+     isn't there.  -->
+    <xsl:variable name="supports-namespace-axis" select="count(/*/namespace::*) &gt; 0"/>
+
+    <!-- ===  Main  ========================================
+         Main template for the wsdl document
+     -->
+    <xsl:template match="/">
+        <html>
+            <head>
+                <title>WSDL 2.0 for
+                    <xsl:value-of select="wsdl:description/@targetNamespace"/>
+                </title>
+                <style type="text/css">
+                    <xsl:call-template name="css"/>
+                    <![CDATA[
+.annotation-area {width:19em}
+.schema-block {background-color:#EEE;}
+.schema {padding-left:7em; text-indent:-5em}
+.schema-top-level {padding-left: 8em; text-indent:-5em}
+.wsdl-top-level {padding-left: 6em; text-indent:-5em}
+.wsdl-second-level {padding-left: 7em; text-indent:-5em}
+.wsdl-message {padding-left: 6em; text-indent:-5em}
+
+.description {padding-left:5em; margin-bottom:1em; text-indent:-5em}
+.operation   {background-color:rgb(215,206,221); text-align:right; border: 1px dashed black; padding:.5em} 
+.fault       {background-color:rgb(240,206,206); text-align:right; border: 1px dashed black; padding:.5em} 
+.interface   {background-color:rgb(185,218,192); text-align:right; border: 1px dashed black; padding:.5em} 
+.binding     {background-color:rgb(218,208,185); text-align:right; border: 1px dashed black; padding:.5em} 
+.service     {background-color:rgb(240,197,166); text-align:right; border: 1px dashed black; padding:.5em} 
+]]>
+                </style>
+            </head>
+            <body>
+                <xsl:apply-templates select="wsdl:description"/>
+                <p/>
+                <hr/>
+                <table cellpadding="0" cellspacing="0" id="index">
+                    <xsl:if test="wsdl:description/wsdl:types/xs:schema">
+                        <xsl:for-each select="wsdl:description/wsdl:types">
+                            <xsl:call-template name="generate-xsd-index"/>
+                        </xsl:for-each>
+                    </xsl:if>
+                    <xsl:call-template name="generate-wsdl-index"/>
+                </table>
+            </body>
+        </html>
+    </xsl:template>
+    <!-- ===  Elements  ========================================
+         The following templates format elements of various flavors
+         (wsdl:description, children of wsdl:description, grandchildren etc. of wsdl:description,
+         and extension elements
+     -->
+    <xsl:template match="wsdl:description">
+        <table cellpadding="0" cellspacing="0">
+            <tr>
+                <td class="annotation-area">
+                    <div class="sidebar">
+                        <xsl:call-template name="index-reference"/>
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <div class="description">
+                        <xsl:call-template name="element-start"/>
+                    </div>
+                </td>
+            </tr>
+            <xsl:apply-templates/>
+            <tr>
+                <td colspan="2" class="annotation-area"/>
+                <td class="source-area">
+                    <div class="description">
+                        <xsl:call-template name="element-end"/>
+                    </div>
+                </td>
+            </tr>
+        </table>
+    </xsl:template>
+    <xsl:template match="wsdl:description/wsdl:*">
+        <xsl:variable name="identifier">
+            <xsl:if test="@name">
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="local-name()"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="@name"/>
+            </xsl:if>
+        </xsl:variable>
+        <tr>
+            <xsl:choose>
+                <xsl:when
+                        test="not(self::wsdl:documentation or self::wsdl:import or self::wsdl:include)">
+                    <td class="annotation-area">
+                        <div class="sidebar {local-name()} sidebar-title">
+                            <xsl:if test="$identifier">
+                                <xsl:attribute name="id">
+                                    <xsl:value-of select="$identifier"/>
+                                </xsl:attribute>
+                            </xsl:if>
+                            <span class="sidebar-title-highlight">
+                                <xsl:value-of select="@name"/>
+                            </span>
+                            <xsl:text></xsl:text>
+                            <xsl:value-of select="local-name()"/>
+                            <xsl:call-template name="wsdl-referenced-by"/>
+                        </div>
+                    </td>
+                    <td>
+                        <div class="arrow">&#160;</div>
+                    </td>
+                </xsl:when>
+                <xsl:otherwise>
+                    <td colspan="2" class="annotation-area"/>
+                </xsl:otherwise>
+            </xsl:choose>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+                <div class="wsdl-top-level">
+                    <xsl:apply-templates/>
+                </div>
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:description/wsdl:interface">
+        <tr>
+            <td class="annotation-area">
+                <div class="sidebar interface sidebar-title">
+                    <a name="_interface_{@name}"></a>
+                    <span class="sidebar-title-highlight">
+                        <xsl:value-of select="@name"/>
+                    </span>
+                    <xsl:text></xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                    <xsl:call-template name="wsdl-referenced-by"/>
+                    <xsl:call-template name="interface-defines"/>
+                </div>
+            </td>
+            <td>
+                <div class="arrow">&#160;</div>
+            </td>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-start"/>
+                    <xsl:apply-templates select="wsdl:documentation"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates select="node()[not(self::wsdl:documentation)]"/>
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:interface/wsdl:operation | wsdl:interface/wsdl:fault">
+        <tr>
+            <td class="annotation-area">
+                <div class="sidebar {local-name()} sidebar-title">
+                    <a name="_{local-name()}_{@name}"></a>
+                    <span class="sidebar-title-highlight">
+                        <xsl:value-of select="@name"/>
+                    </span>
+                    <xsl:text></xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                    <xsl:call-template name="wsdl-referenced-by"/>
+                </div>
+            </td>
+            <td>
+                <div class="arrow">&#160;</div>
+            </td>
+            <td class="source-area">
+                <div class="wsdl-second-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+                <div class="wsdl-second-level">
+                    <xsl:apply-templates/>
+                </div>
+                <div class="wsdl-second-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:description/wsdl:types">
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates/>
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="wsdl-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:schema | xs:import">
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-start"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates/>
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:*">
+        <xsl:apply-imports/>
+    </xsl:template>
+    <xsl:template match="wsdl:* | wsoap:* | whttp:*">
+        <div class="indent">
+            <div>
+                <xsl:call-template name="element-start"/>
+            </div>
+            <xsl:apply-templates/>
+            <div>
+                <xsl:call-template name="element-end"/>
+            </div>
+        </div>
+    </xsl:template>
+
+    <!-- ===  Attributes  =========================================
+         The following templates format attributes of various flavors
+     -->
+    <xsl:template match="wsdl:binding/wsdl:operation/@name | wsdl:binding/wsdl:fault/@name"
+                  priority="1">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-wsdl-reference"/>
+                <xsl:text>#_</xsl:text>
+                <xsl:value-of select="local-name(parent::*)"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="."/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:*/@name">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template
+            match="wsdl:input/@element[not(contains(.,'#'))] | wsdl:output/@element[not(contains(.,'#'))] | wsdl:fault/@element[not(contains(.,'#'))]">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_</xsl:text>
+                <xsl:value-of select="name()"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:infault/@ref | wsdl:outfault/@ref |wsdl:fault/@ref">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_fault_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:operation/@ref">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_operation_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:service/@interface | wsdl:interface/@extends">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_interface_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:endpoint/@binding">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-schema-reference"/>
+                <xsl:text>#_binding_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="wsdl:*/@* | wsoap:*/@* | whttp:*/@*" priority="0">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="native-attribute" select="true()"/>
+        </xsl:call-template>
+    </xsl:template>
+
+    <!-- ===  Comments  ========================================
+         The following template formats comment nodes
+     -->
+    <xsl:template match="wsdl:description/comment()">
+        <tr>
+            <td colspan="2" class="annotation-area"/>
+            <td class="source-area">
+                <div class="schema-top-level markup-comment">
+                    <xsl:text>&lt;!--</xsl:text>
+                    <xsl:value-of select="."/>
+                    <xsl:text>--&gt;</xsl:text>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="wsdl:interface/comment()">
+        <div class="markup-comment double-indent">
+            <xsl:text>&lt;!--</xsl:text>
+            <xsl:value-of select="."/>
+            <xsl:text>--&gt;</xsl:text>
+        </div>
+    </xsl:template>
+
+    <!-- ===  Library templates  ========================================
+         Library of useful named templates
+     -->
+    <xsl:template name="insert-wsdl-reference">
+        <xsl:if test="parent::wsdl:operation">
+            <a href="#_operation_{../@name}">
+                <xsl:value-of select="../@name"/>
+            </a>
+            <xsl:text>operation of the</xsl:text>
+        </xsl:if>
+        <xsl:for-each select="ancestor-or-self::*[last() - 1]">
+            <a href="#_{local-name(.)}_{@name}">
+                <xsl:value-of select="@name"/>
+            </a>
+            <xsl:text></xsl:text>
+            <xsl:value-of select="local-name(.)"/>
+        </xsl:for-each>
+    </xsl:template>
+    <xsl:template name="wsdl-referenced-by">
+        <xsl:variable name="target" select="@name"/>
+        <xsl:if test="parent::wsdl:description">
+            <div class="sidebar-text">
+                <xsl:variable name="extended-by" select="//wsdl:*[substring-after(@element | @binding
+					| @interface,':') = $target]"/>
+                <xsl:if test="count($extended-by) > 0">
+                    <div class="referenced-list">Referenced by:</div>
+                    <ul>
+                        <xsl:for-each select="$extended-by">
+                            <xsl:sort select="@element | @binding | @interface"/>
+                            <li class="referenced-item">
+                                <xsl:call-template name="insert-wsdl-reference"/>
+                            </li>
+                        </xsl:for-each>
+                    </ul>
+                </xsl:if>
+            </div>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="interface-defines">
+        <xsl:variable name="target" select="@name"/>
+        <div class="sidebar-text">
+            <xsl:if test="wsdl:fault">
+                <div class="referenced-list">Defines faults:</div>
+                <ul>
+                    <xsl:for-each select="wsdl:fault">
+                        <xsl:sort select="@name"/>
+                        <li class="referenced-item">
+                            <a href="#_fault_{@name}">
+                                <xsl:value-of select="@name"/>
+                            </a>
+                        </li>
+                    </xsl:for-each>
+                </ul>
+            </xsl:if>
+            <xsl:if test="wsdl:operation">
+                <div class="referenced-list">Defines operations:</div>
+                <ul>
+                    <xsl:for-each select="wsdl:operation">
+                        <xsl:sort select="@name"/>
+                        <li class="referenced-item">
+                            <a href="#_operation_{@name}">
+                                <xsl:value-of select="@name"/>
+                            </a>
+                        </li>
+                    </xsl:for-each>
+                </ul>
+            </xsl:if>
+        </div>
+    </xsl:template>
+    <xsl:template name="additional-references">
+        <xsl:param name="target"/>
+        <xsl:variable name="referenced-by"
+                      select="/wsdl:description/wsdl:interface/wsdl:operation/wsdl:*[substring-after(@element,':') = $target]"/>
+        <xsl:if test="count($referenced-by) > 0">
+            <div class="referenced-list">Referenced from WSDL by:</div>
+            <ul>
+                <xsl:for-each select="$referenced-by">
+                    <xsl:sort select="@element"/>
+                    <li class="referenced-item">
+                        <xsl:call-template name="insert-wsdl-reference"/>
+                    </li>
+                </xsl:for-each>
+            </ul>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="external-wsdl-reference">
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <xsl:if test="not(../namespace::*[. = $targetNamespace and name(.) =
+					substring-before(current(),':')])">
+                    <xsl:variable name="prefix" select="substring-before(.,':')"/>
+                    <xsl:variable name="uri" select="../namespace::*[name(.) = $prefix]"/>
+                    <xsl:value-of
+                            select="/wsdl:description/wsdl:import[@namespace=$uri]/@location"/>
+                </xsl:if>
+            </xsl:when>
+            <xsl:otherwise>
+                <xsl:choose>
+                    <xsl:when
+                            test="substring-before(current(),':')= 'xs' or substring-before(current(),':')= 'xsd'">
+                        <xsl:value-of select="$xsd-schema-location"/>
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <!-- the link is broken - Bad Mozilla -->
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="external-schema-reference">
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <xsl:if test="not(../namespace::*[. = $schemaTargetNamespace and name(.) =
+					substring-before(current(),':')])">
+                    <xsl:variable name="prefix" select="substring-before(.,':')"/>
+                    <xsl:variable name="uri" select="../namespace::*[name(.) = $prefix]"/>
+                    <xsl:choose>
+                        <xsl:when test="$uri = 'http://www.w3.org/2001/XMLSchema'">
+                            <xsl:value-of select="$xsd-schema-location"/>
+                        </xsl:when>
+                        <xsl:otherwise>
+                            <xsl:value-of
+                                    select="/wsdl:description/wsdl:types/xs:import[@namespace=$uri]/@schemaLocation"/>
+                        </xsl:otherwise>
+                    </xsl:choose>
+                </xsl:if>
+            </xsl:when>
+            <xsl:otherwise>
+                <xsl:choose>
+                    <xsl:when
+                            test="substring-before(current(),':')= 'xs' or substring-before(current(),':')= 'xsd'">
+                        <xsl:value-of select="$xsd-schema-location"/>
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <!-- the link is broken - Bad Mozilla -->
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="generate-wsdl-index">
+        <xsl:if test="wsdl:description/wsdl:interface">
+            <tr>
+                <td id="interface-list" class="annotation-area">
+                    <div class="interface sidebar sidebar-title-highlight">Index of interfaces</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:description/wsdl:interface">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:description/wsdl:interface/wsdl:fault">
+            <tr>
+                <td id="fault-list" class="annotation-area">
+                    <div class="fault sidebar sidebar-title-highlight">Index of faults</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:description/wsdl:interface/wsdl:fault">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:description/wsdl:interface/wsdl:operation">
+            <tr>
+                <td id="operation-list" class="annotation-area">
+                    <div class="operation sidebar sidebar-title-highlight">Index of operations</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:description/wsdl:interface/wsdl:operation">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:description/wsdl:binding">
+            <tr>
+                <td id="binding-list" class="annotation-area">
+                    <div class="binding sidebar sidebar-title-highlight">Index of bindings</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:description/wsdl:binding">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="wsdl:description/wsdl:service">
+            <tr>
+                <td id="service-list" class="annotation-area">
+                    <div class="service sidebar sidebar-title-highlight">Index of services</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="wsdl:description/wsdl:service">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="index-reference">
+        <div class="note sidebar-text">See the
+            <a href="#index">index</a>
+            of
+            <xsl:variable name="ss1">
+                <xsl:if test="wsdl:types/xs:schema/xs:complexType">
+                    <a href="#complexType-list">complexTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss2">
+                <xsl:copy-of select="$ss1"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:simpleType">
+                    <xsl:if test="$ss1!=''">,</xsl:if>
+                    <a href="#simpleType-list">simpleTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss3">
+                <xsl:copy-of select="$ss2"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:element">
+                    <xsl:if test="$ss2!=''">,</xsl:if>
+                    <a href="#global-element-list">global elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss4">
+                <xsl:copy-of select="$ss3"/>
+                <xsl:if test="wsdl:types/xs:schema/*//xs:element[@name]">
+                    <xsl:if test="$ss3!=''">,</xsl:if>
+                    <a href="#local-element-list">local elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss5">
+                <xsl:copy-of select="$ss4"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:attribute">
+                    <xsl:if test="$ss4!=''">,</xsl:if>
+                    <a href="#global-attribute-list">global attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss6">
+                <xsl:copy-of select="$ss5"/>
+                <xsl:if test="wsdl:types/xs:schema/*//xs:attribute[@name]">
+                    <xsl:if test="$ss5!=''">,</xsl:if>
+                    <a href="#local-attribute-list">local attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss7">
+                <xsl:copy-of select="$ss6"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:group">
+                    <xsl:if test="$ss6!=''">,</xsl:if>
+                    <a href="#model-group-list">model groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss8">
+                <xsl:copy-of select="$ss7"/>
+                <xsl:if test="wsdl:types/xs:schema/xs:attributeGroup">
+                    <xsl:if test="$ss7!=''">,</xsl:if>
+                    <a href="#attributeGroup-list">attribute groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss9">
+                <xsl:copy-of select="$ss8"/>
+                <xsl:if test="wsdl:interface">
+                    <xsl:if test="$ss8!=''">,</xsl:if>
+                    <a href="#interface-list">interfaces</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss10">
+                <xsl:copy-of select="$ss9"/>
+                <xsl:if test="wsdl:interface/wsdl:fault">
+                    <xsl:if test="$ss9!=''">,</xsl:if>
+                    <a href="#fault-list">faults</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss11">
+                <xsl:copy-of select="$ss10"/>
+                <xsl:if test="wsdl:interface/wsdl:operation">
+                    <xsl:if test="$ss10!=''">,</xsl:if>
+                    <a href="#operation-list">operations</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss12">
+                <xsl:copy-of select="$ss11"/>
+                <xsl:if test="wsdl:binding">
+                    <xsl:if test="$ss11!=''">,</xsl:if>
+                    <a href="#binding-list">bindings</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss13">
+                <xsl:copy-of select="$ss12"/>
+                <xsl:if test="wsdl:service">
+                    <xsl:if test="$ss12!=''">,</xsl:if>
+                    <a href="#service-list">services</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:copy-of select="$ss13"/>
+            <xsl:text>defined in this wsdl</xsl:text>
+        </div>
+    </xsl:template>
+</xsl:stylesheet>


[07/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
new file mode 100644
index 0000000..3640bc2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredCartridgeException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class UnregisteredCartridgeException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public UnregisteredCartridgeException(String msg) {
+        super(msg);
+    }
+    
+    public UnregisteredCartridgeException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
new file mode 100644
index 0000000..2060553
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/exception/UnregisteredServiceException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.exception;
+
+public class UnregisteredServiceException extends Exception {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public UnregisteredServiceException(String msg) {
+        super(msg);
+    }
+    
+    public UnregisteredServiceException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
new file mode 100644
index 0000000..c1f5686
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hector/CassandraDataRetriever.java
@@ -0,0 +1,181 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.hector;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+
+import me.prettyprint.cassandra.model.BasicColumnDefinition;
+import me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;
+import me.prettyprint.cassandra.model.CqlQuery;
+import me.prettyprint.cassandra.model.CqlRows;
+import me.prettyprint.cassandra.serializers.StringSerializer;
+import me.prettyprint.cassandra.service.CassandraHostConfigurator;
+import me.prettyprint.cassandra.service.ThriftCfDef;
+import me.prettyprint.hector.api.Cluster;
+import me.prettyprint.hector.api.Keyspace;
+import me.prettyprint.hector.api.beans.HColumn;
+import me.prettyprint.hector.api.beans.Row;
+import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
+import me.prettyprint.hector.api.ddl.ColumnIndexType;
+import me.prettyprint.hector.api.ddl.ComparatorType;
+import me.prettyprint.hector.api.ddl.KeyspaceDefinition;
+import me.prettyprint.hector.api.factory.HFactory;
+import me.prettyprint.hector.api.query.QueryResult;
+
+public class CassandraDataRetriever {
+
+    private static final Log log = LogFactory.getLog(CassandraDataRetriever.class);
+    private static FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+    private final static StringSerializer se = StringSerializer.get();
+    private static Cluster cluster;
+    private static Keyspace keyspace;
+    private static boolean isInit;
+    
+    public static void init() {
+
+        if(isInit){
+            return;
+        }
+        getCassandraKeyspace();
+        indexCounterColumn("payload_status");
+        isInit = true;
+    }
+    
+    public static void connect() {
+        
+        if(keyspace == null){
+            handleException("Cannot find the key space.");
+        }
+        
+        String colFamily = CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY;
+        
+        CqlQuery<String,String,String> cqlQuery = new CqlQuery<String,String,String>(keyspace, se, se, se);
+        cqlQuery.setQuery("select payload_nodeId from "+colFamily+" where payload_status='RUNNING'");
+//        cqlQuery.setQuery("select * from "+colFamily+" where payload_domain='nirmal'");
+        QueryResult<CqlRows<String,String,String>> result = cqlQuery.execute();
+        
+        if (result != null && result.get() != null) {
+            List<Row<String, String, String>> list = result.get().getList();
+            for (Row<?, ?, ?> row : list) {
+                System.out.println(".");
+                List<?> columns = row.getColumnSlice().getColumns();
+                for (Iterator<?> iterator = columns.iterator(); iterator.hasNext();) {
+                    HColumn<?, ?> column = (HColumn<?, ?>) iterator.next();
+                    System.out.print(column.getName() + ":" + column.getValue()
+                            + "\t");
+                }
+                System.out.println("");
+            }
+        }
+        
+//        ColumnQuery<String, String, String> columnQuery =
+//                HFactory.createStringColumnQuery(keyspace);
+//        KeyIterator<String> keyIterator = new KeyIterator<String>(keyspace, colFamily, StringSerializer.get());
+//        for ( String key : keyIterator ) {
+//            
+//            columnQuery.setColumnFamily(colFamily).setKey(key).setName("payload_nodeId");
+//            QueryResult<HColumn<String, String>> result = columnQuery.execute();
+//            HColumn<String, String> hColumn = result.get();
+//            System.out.println("Column: " + hColumn.getName() + " Value : " + hColumn.getValue() + "\n");
+//        }
+        
+//        //Read Data
+//        for (String key : keyList) {
+//            System.out.println("\nretrieving Key " + rowKey + "From Column Family " + columnFamily + "\n");
+//            for (String columnName : columnList.split(":")) {
+//                //sout data
+//            }
+//        }
+        
+        
+    }
+    
+    private static void indexCounterColumn(String idxColumnName) {
+
+        KeyspaceDefinition keyspaceDefinition = cluster.describeKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE);
+
+        List<ColumnFamilyDefinition> cdfs = keyspaceDefinition.getCfDefs();
+        ColumnFamilyDefinition cfd = null;
+        for (ColumnFamilyDefinition c : cdfs) {
+            if (c.getName().equals(CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY)) {
+                System.out.println(c.getName());
+                cfd = c;
+                break;
+            }
+        }
+
+        BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition(cfd);
+
+        BasicColumnDefinition bcdf = new BasicColumnDefinition();
+        bcdf.setName(StringSerializer.get().toByteBuffer(idxColumnName));
+        bcdf.setIndexName(idxColumnName + "index");
+        bcdf.setIndexType(ColumnIndexType.KEYS);
+        bcdf.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
+
+        columnFamilyDefinition.addColumnDefinition(bcdf);
+        cluster.updateColumnFamily(new ThriftCfDef(columnFamilyDefinition));
+
+    } 
+    
+    private static void getCassandraKeyspace() {
+        if (cluster == null) {
+            Map<String, String> credentials = new HashMap<String, String>();
+            credentials.put("username", dataHolder.getCassandraUser());
+            credentials.put("password", dataHolder.getCassandraPassword());
+
+            cluster =
+                      retrieveCassandraCluster(CloudControllerConstants.DEFAULT_CASSANDRA_CLUSTER_NAME,
+                                               dataHolder.getCassandraConnUrl(), credentials);
+
+            keyspace =
+                       HFactory.createKeyspace(CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE,
+                                               cluster);
+        }
+        
+    }
+    
+    private static Cluster retrieveCassandraCluster(String clusterName, String connectionUrl,
+        Map<String, String> credentials) {
+
+        CassandraHostConfigurator hostConfigurator = new CassandraHostConfigurator(connectionUrl);
+        hostConfigurator.setRetryDownedHosts(false);
+        Cluster cluster = HFactory.createCluster(clusterName, hostConfigurator, credentials);
+        return cluster;
+    }
+
+    private static void handleException(String msg) {
+
+        log.error(msg);
+        throw new CloudControllerException(msg);
+    }
+    
+//    private void handleException(String msg, Exception e) {
+//
+//        log.error(msg, e);
+//        throw new AutoscalerServiceException(msg, e);
+//    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
new file mode 100644
index 0000000..64efe7a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/hive/HiveQueryExecutor.java
@@ -0,0 +1,167 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.hive;
+
+import java.rmi.RemoteException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.transport.http.HttpTransportProperties;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceHiveExecutionException;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResult;
+import org.wso2.carbon.analytics.hive.stub.HiveExecutionServiceStub.QueryResultRow;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.runtime.FasterLookUpDataHolder;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.utils.CarbonUtils;
+
+public class HiveQueryExecutor {
+    private static final Log log = LogFactory.getLog(HiveQueryExecutor.class);
+    private HiveExecutionServiceStub hiveService;
+    private String payloadPrefix = CloudControllerConstants.PAYLOAD_PREFIX;
+    private String hiveTable = "cloudController";
+    private FasterLookUpDataHolder dataHolder = FasterLookUpDataHolder.getInstance();
+    
+    public HiveQueryExecutor() {
+
+        ServerConfiguration serverConfig =  CarbonUtils.getServerConfiguration();
+        String bamServerUrl = serverConfig.getFirstProperty("BamServerURL");
+        String serviceName = "HiveExecutionService";
+        HttpTransportProperties.Authenticator authenticator;
+        
+        try {
+            hiveService = new HiveExecutionServiceStub(bamServerUrl+"/services/"+serviceName);
+            
+            // admin service authentication
+            authenticator = new HttpTransportProperties.Authenticator();
+            authenticator.setUsername(dataHolder.getBamUsername());
+            authenticator.setPassword(dataHolder.getBamPassword());
+            authenticator.setPreemptiveAuthentication(true);
+            
+            ServiceClient client = hiveService._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, authenticator);
+            option.setTimeOutInMilliSeconds(120000);
+
+        } catch (AxisFault e) {
+            String msg = "Cannot get a connection to "+serviceName;
+            handleException(msg, e);
+        }
+    }
+    
+    public QueryResult[] execute(String query){
+        try {
+            return hiveService.executeHiveScript(query);
+        } catch (RemoteException e) {
+            handleException("Query : '"+query+"' - "+e.getMessage(), e);
+        } catch (HiveExecutionServiceHiveExecutionException e) {
+            handleException("Query : '"+query+"' - "+e.getMessage(), e);
+        }
+        
+        return new QueryResult[0];
+    }
+    
+    public void createHiveTable(){
+        String query = 
+                "CREATE EXTERNAL TABLE IF NOT EXISTS "+hiveTable+" (id STRING, " +
+                payloadPrefix+CloudControllerConstants.NODE_ID_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.DOMAIN_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.IAAS_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.PUB_IP_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.STATUS_COL+" STRING," +
+                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL+" STRING" +
+                ") STORED BY 'org.apache.hadoop.hive.cassandra.CassandraStorageHandler' " +
+                "WITH SERDEPROPERTIES ( \"cassandra.host\" = \""+dataHolder.getCassandraConnUrl().split(":")[0]+"\"," +
+                "\"cassandra.port\" = \""+dataHolder.getCassandraConnUrl().split(":")[1]+
+                "\",\"cassandra.ks.name\" = \""+CloudControllerConstants.DEFAULT_CASSANDRA_KEY_SPACE+"\"," +
+                "\"cassandra.ks.username\" = \""+dataHolder.getCassandraUser()+
+                "\", \"cassandra.ks.password\" = \""+dataHolder.getCassandraPassword()+"\"," +
+                "\"cassandra.cf.name\" = \""+CloudControllerConstants.CLOUD_CONTROLLER_COL_FAMILY+"\"," +
+                "\"cassandra.columns.mapping\" = \"" +
+                payloadPrefix+CloudControllerConstants.NODE_ID_COL+"," +
+                payloadPrefix+CloudControllerConstants.CARTRIDGE_TYPE_COL+"," +
+                payloadPrefix+CloudControllerConstants.DOMAIN_COL+"," +
+                payloadPrefix+CloudControllerConstants.HOST_NAME_COL+"," +
+                payloadPrefix+CloudControllerConstants.HYPERVISOR_COL+"," +
+                payloadPrefix+CloudControllerConstants.IAAS_COL+"," +
+                payloadPrefix+CloudControllerConstants.IMAGE_ID_COL+"," +
+                payloadPrefix+CloudControllerConstants.LOGIN_PORT_COL+"," +
+                payloadPrefix+CloudControllerConstants.PRIV_IP_COL+"," +
+                payloadPrefix+CloudControllerConstants.PUB_IP_COL+"," +
+                payloadPrefix+CloudControllerConstants.STATUS_COL+"," +
+                payloadPrefix+CloudControllerConstants.SUB_DOMAIN_COL +
+                "\");";
+        
+        execute(query);
+    }
+    
+    public List<String> getRunningNodeIds() {
+        List<String> nodeIds = new ArrayList<String>();
+        String query =
+//                       "select " + payloadPrefix + AutoscalerConstant.NODE_ID_COL + " from " +
+//                               hiveTable + " where payload_status='RUNNING' OR payload_status='PENDING' ;";
+
+//        "select id1 from (select distinct payload_nodeId from cloud1  where payload_status='RUNNING' OR payload_status='PENDING') table1
+//LEFT OUTER JOIN
+//(select distinct payload_nodeId as nodeId from cloud1  where payload_status='TERMINATED') table2
+//ON(table2.nodeId = table1.payload_nodeId)
+//where table2.nodeId is null;";
+                "select table1.id1 from (select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
+                " as id1 from "+ hiveTable +" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+
+                "='RUNNING' OR "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='PENDING') table1 " +
+                "LEFT OUTER JOIN " +"(select distinct "+payloadPrefix+CloudControllerConstants.NODE_ID_COL+
+                " as id2 from "+hiveTable+" where "+payloadPrefix+CloudControllerConstants.STATUS_COL+"='TERMINATED') table2 " +
+                "ON(table1.id1 = table2.id2) where table2.id2 is null;";
+        
+        QueryResult[] result = execute(query);
+
+        for (QueryResult queryResult : result) {
+            if(queryResult == null || queryResult.getResultRows() == null){
+                continue;
+            }
+            for (QueryResultRow row : queryResult.getResultRows()) {
+                if (row != null && row.getColumnValues() != null && row.getColumnValues().length != 0) {
+                    nodeIds.add(row.getColumnValues()[0]);
+                }
+            }
+        }
+        
+        return nodeIds;
+
+    }
+    
+    private void handleException(String msg, Exception e){
+        log.error(msg, e);
+        throw new CloudControllerException(msg, e);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
new file mode 100644
index 0000000..8c3b78a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/AWSEC2Iaas.java
@@ -0,0 +1,275 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.iaases;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.aws.ec2.AWSEC2AsyncClient;
+import org.jclouds.aws.ec2.AWSEC2Client;
+import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
+import org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;
+import org.jclouds.aws.ec2.functions.ImportOrReturnExistingKeypair;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.ec2.domain.KeyPair;
+import org.jclouds.ec2.domain.PublicIpInstanceIdPair;
+import org.jclouds.rest.RestContext;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
+import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class AWSEC2Iaas extends Iaas{
+    
+    private static final Log log = LogFactory.getLog(AWSEC2Iaas.class);
+    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
+    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
+            log.fatal(msg);
+            throw new CloudControllerException(msg);
+        }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(iaas.getImage());
+
+        if (iaas.getProperty("instanceType") != null) {
+            // set instance type eg: m1.large
+            templateBuilder.hardwareId(iaas.getProperty("instanceType"));
+        }
+
+		// build the Template
+		Template template = templateBuilder.build();
+
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode?
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+        
+        // this is required in order to avoid creation of additional security groups by jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
+
+        // set EC2 specific options
+		if (iaas.getProperty("subnetId") != null) {
+			template.getOptions().as(AWSEC2TemplateOptions.class).subnetId(iaas.getProperty("subnetId"));
+		}
+
+        if (iaas.getProperty("availabilityZone") != null) {
+            template.getOptions().as(AWSEC2TemplateOptions.class)
+                    .placementGroup(iaas.getProperty("availabilityZone"));
+        }
+
+        if (iaas.getProperty("securityGroups") != null) {
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .securityGroups(iaas.getProperty("securityGroups")
+                                        .split(CloudControllerConstants.ENTRY_SEPARATOR));
+
+        }
+
+        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
+                                                                File.separator +
+                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
+        }
+
+        if (iaas.getProperty("keyPair") != null) {
+            template.getOptions().as(AWSEC2TemplateOptions.class)
+                    .keyPair(iaas.getProperty("keyPair"));
+        }
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
+                    .userData(iaasInfo.getPayload());
+        }
+
+    }
+
+    @Override
+    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+
+        String ec2Msg = " ec2. Region: "+region+" - Key Pair Name: ";
+        
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext = context.unwrap(RestContext.class);
+        AWSEC2Client ec2Client = restContext.getApi();
+        
+        ImportOrReturnExistingKeypair importer = new ImportOrReturnExistingKeypair(ec2Client);
+        
+        RegionNameAndPublicKeyMaterial regionNameAndKey = new RegionNameAndPublicKeyMaterial(region, keyPairName, publicKey);
+        KeyPair keyPair = importer.apply(regionNameAndKey);
+        
+        if (keyPair != null) {
+
+            iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
+                    .keyPair(keyPair.getKeyName());
+
+            log.info(SUCCESSFUL_LOG_LINE + ec2Msg + keyPair.getKeyName());
+            return true;
+        }
+        
+        log.error(FAILED_LOG_LINE+ec2Msg);
+        
+        return false;
+    }
+
+    @Override
+	public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+		@SuppressWarnings("unchecked")
+		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
+		                                                           context.unwrap(RestContext.class);
+		AWSEC2Client ec2Client = restContext.getApi();
+		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+
+		String ip = null;
+		
+		// first try to find an unassigned IP.
+		ArrayList<PublicIpInstanceIdPair> unassignedIps =
+		                                                  Lists.newArrayList(Iterables.filter(ec2Client.getElasticIPAddressServices()
+		                                                                                               .describeAddressesInRegion(region,
+		                                                                                                                          new String[0]),
+		                                                                                      new Predicate<PublicIpInstanceIdPair>() {
+
+			                                                                                      @Override
+			                                                                                      public boolean apply(PublicIpInstanceIdPair arg0) {
+				                                                                                      return arg0.getInstanceId() == null;
+			                                                                                      }
+
+		                                                                                      }));
+		
+		
+		if (!unassignedIps.isEmpty()) {
+			// try to prevent multiple parallel launches from choosing the same
+			// ip.
+			Collections.shuffle(unassignedIps);
+			ip = Iterables.getLast(unassignedIps).getPublicIp();
+		}
+		
+		// if no unassigned IP is available, we'll try to allocate an IP.
+		if (ip == null || ip.isEmpty()) {
+			try {
+				ip = ec2Client.getElasticIPAddressServices().allocateAddressInRegion(region);
+				log.info("Assigned ip [" + ip +"]");
+
+			} catch (Exception e) {
+				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+		}
+
+		String id = node.getProviderId();
+
+		// wait till the fixed IP address gets assigned - this is needed before we associate a
+		// public IP
+
+		while (node.getPrivateAddresses() == null) {
+			CloudControllerUtil.sleep(1000);
+		}
+
+		int retries = 0;
+		while (retries < 12 && !associatePublicIp(ec2Client, region, ip, id)) {
+
+			// wait for 5s
+			CloudControllerUtil.sleep(5000);
+			retries++;
+		}
+
+		// FIXME make this debug
+		log.info("Successfully associated an IP address " + ip + " for node with id: " +
+		         node.getId());
+
+		return ip;
+
+	}
+
+	/**
+     * @param ec2Client
+     * @param region
+     * @param ip
+     * @param id
+     */
+	private boolean associatePublicIp(AWSEC2Client ec2Client, String region, String ip, String id) {
+		try {
+			ec2Client.getElasticIPAddressServices().associateAddressInRegion(region, ip, id);
+			log.info("Successfully associated public IP ");
+			return true;
+		} catch (Exception e) {
+			log.error("Exception in associating public IP " + e.getMessage());
+			return false;
+		}
+	}
+
+	@Override
+    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip) {
+	    
+		ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+		@SuppressWarnings("unchecked")
+		RestContext<AWSEC2Client, AWSEC2AsyncClient> restContext =
+		                                                           context.unwrap(RestContext.class);
+		AWSEC2Client ec2Client = restContext.getApi();
+		String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+
+		ec2Client.getElasticIPAddressServices().disassociateAddressInRegion(region, ip);
+		ec2Client.getElasticIPAddressServices().releaseAddressInRegion(region, ip);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
new file mode 100644
index 0000000..f763144
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/OpenstackNovaIaas.java
@@ -0,0 +1,269 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.iaases;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.openstack.nova.v2_0.NovaAsyncClient;
+import org.jclouds.openstack.nova.v2_0.NovaClient;
+import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
+import org.jclouds.openstack.nova.v2_0.domain.FloatingIP;
+import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
+import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPClient;
+import org.jclouds.openstack.nova.v2_0.extensions.KeyPairClient;
+import org.jclouds.rest.InsufficientResourcesException;
+import org.jclouds.rest.RestContext;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
+import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerConstants;
+import org.wso2.carbon.stratos.cloud.controller.util.CloudControllerUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import com.google.common.base.Predicate;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class OpenstackNovaIaas extends Iaas{
+    
+    private static final Log log = LogFactory.getLog(OpenstackNovaIaas.class);
+    private static final String SUCCESSFUL_LOG_LINE = "A key-pair is created successfully in ";
+    private static final String FAILED_LOG_LINE = "Key-pair is unable to create in ";
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            throw new CloudControllerException("Compute service is null for IaaS provider: " +
+                                                 iaas.getName());
+        }
+
+        // // if domain to template map is null
+        // if (entity.getDomainToTemplateMap() == null) {
+        // // we initialize it
+        // entity.setDomainToTemplateMap(new HashMap<String, Template>());
+        // }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+        templateBuilder.imageId(iaas.getImage());
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once!
+        // for (org.wso2.carbon.cartridge.autoscaler.service.util.ServiceContext temp :
+        // serviceContexts) {
+
+        String instanceType;
+
+        // set instance type
+        if (((instanceType = iaas.getProperty("instanceType")) != null)) {
+
+            templateBuilder.hardwareId(instanceType);
+        }
+
+        Template template = templateBuilder.build();
+        
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode?
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+		// this is required in order to avoid creation of additional security groups by Jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(new int[]{});
+
+        if (iaas.getProperty("securityGroups") != null) {
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .securityGroupNames(iaas.getProperty("securityGroups")
+                                            .split(CloudControllerConstants.ENTRY_SEPARATOR));
+        }
+
+        if (iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER) != null) {
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .userData(ComputeServiceBuilderUtil.getUserData(CarbonUtils.getCarbonHome() +
+                                                                File.separator +
+                                                                iaas.getProperty(CloudControllerConstants.PAYLOAD_FOLDER)));
+        }
+
+        if (iaas.getProperty("keyPair") != null) {
+            template.getOptions().as(NovaTemplateOptions.class)
+                    .keyPairName(iaas.getProperty("keyPair"));
+        }
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+        
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class).userData(iaasInfo.getPayload());
+        }
+
+    }
+
+    @Override
+    public synchronized boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+
+        String openstackNovaMsg = " Openstack-nova. Region: " + region + " - Name: ";
+
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        KeyPairClient api = restContext.getApi().getKeyPairExtensionForZone(region).get();
+        
+        KeyPair keyPair = api.createKeyPairWithPublicKey(keyPairName, publicKey);
+
+        if (keyPair != null) {
+            
+            iaasInfo.getTemplate().getOptions().as(NovaTemplateOptions.class)
+            .keyPairName(keyPair.getName());
+            
+            log.info(SUCCESSFUL_LOG_LINE + openstackNovaMsg + keyPair.getName());
+            return true;
+        }
+
+        log.error(FAILED_LOG_LINE + openstackNovaMsg);
+        return false;
+
+    }
+
+    @Override
+    public synchronized String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+        ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        NovaClient novaClient = restContext.getApi();
+        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+        
+        FloatingIPClient floatingIp = novaClient.getFloatingIPExtensionForZone(region).get();
+        
+        String ip=null;
+        // first try to find an unassigned IP.
+        ArrayList<FloatingIP> unassignedIps =
+        		Lists.newArrayList(Iterables.filter(floatingIp.listFloatingIPs(),
+        		                                    new Predicate<FloatingIP>() {
+        			
+        			@Override
+        			public boolean apply(FloatingIP arg0) {
+        				//FIXME is this the correct filter?
+        				return arg0.getFixedIp() == null;
+        			}
+        			
+        		}));
+        
+		if (!unassignedIps.isEmpty()) {
+			// try to prevent multiple parallel launches from choosing the same
+			// ip.
+			Collections.shuffle(unassignedIps);
+			ip = Iterables.getLast(unassignedIps).getIp();
+		}
+        
+        // if no unassigned IP is available, we'll try to allocate an IP.
+		if (ip == null || ip.isEmpty()) {
+
+			try {
+				ip = floatingIp.allocate().getIp();
+
+			} catch (InsufficientResourcesException e) {
+				String msg = "Failed to allocate an IP address. All IP addresses are in use.";
+				log.error(msg, e);
+				throw new CloudControllerException(msg, e);
+			}
+		}
+
+        // wait till the fixed IP address gets assigned - this is needed before we associate a public IP
+        
+        while(node.getPrivateAddresses() == null){
+        	CloudControllerUtil.sleep(1000);
+        }
+
+        int retries =0;
+        while(retries < 5 && !associateIp(floatingIp, ip, node.getProviderId()) ){
+        	
+        	// wait for 5s
+        	CloudControllerUtil.sleep(5000);
+        	retries++;
+        }
+        
+        NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip)).build();
+      
+        log.info("Successfully associated an IP address "+ip+" for node with id: "+node.getId());
+        
+        return ip;
+    }
+    
+    @Override
+    public synchronized void releaseAddress(IaasProvider iaasInfo, String ip){
+    	
+    	ComputeServiceContext context = iaasInfo.getComputeService().getContext();
+        @SuppressWarnings("unchecked")
+        RestContext<NovaClient, NovaAsyncClient> restContext = context.unwrap(RestContext.class);
+        
+        NovaClient novaClient = restContext.getApi();
+        String region = ComputeServiceBuilderUtil.extractRegion(iaasInfo);
+        
+        FloatingIPClient floatingIpClient = novaClient.getFloatingIPExtensionForZone(region).get();
+        
+        for (FloatingIP floatingIP: floatingIpClient.listFloatingIPs()) {
+	        if(floatingIP.getIp().equals(ip)){
+	        	floatingIpClient.deallocate(floatingIP.getId());
+	        	break;
+	        }
+        }
+        
+    }
+    
+    private boolean associateIp(FloatingIPClient client, String ip, String id){
+    	try{
+    		client.addFloatingIPToServer(ip, id);
+    		return true;
+    	}catch(RuntimeException ex){
+    		return false;
+    	}
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
new file mode 100644
index 0000000..42d3e69
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/src/main/java/org/wso2/carbon/stratos/cloud/controller/iaases/VCloudIaas.java
@@ -0,0 +1,164 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.cloud.controller.iaases;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.vcloud.compute.options.VCloudTemplateOptions;
+import org.jclouds.vcloud.domain.network.IpAddressAllocationMode;
+import org.wso2.carbon.stratos.cloud.controller.exception.CloudControllerException;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.Iaas;
+import org.wso2.carbon.stratos.cloud.controller.jcloud.ComputeServiceBuilderUtil;
+import org.wso2.carbon.stratos.cloud.controller.util.IaasProvider;
+
+public class VCloudIaas extends Iaas{
+    
+    private static final Log log = LogFactory.getLog(VCloudIaas.class);
+
+    @Override
+    public void buildComputeServiceAndTemplate(IaasProvider iaasInfo) {
+
+        // builds and sets Compute Service
+        ComputeServiceBuilderUtil.buildDefaultComputeService(iaasInfo);
+        
+        // builds and sets Template
+        buildTemplate(iaasInfo);
+        
+    }
+    
+    private void buildTemplate(IaasProvider iaas) {
+        if (iaas.getComputeService() == null) {
+            String msg = "Compute service is null for IaaS provider: " + iaas.getName();
+            log.fatal(msg);
+            throw new CloudControllerException(msg);
+        }
+
+        TemplateBuilder templateBuilder = iaas.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(iaas.getImage());
+
+        // build the Template
+        Template template = templateBuilder.build();
+
+		// if you wish to auto assign IPs, instance spawning call should be blocking, but if you
+		// wish to assign IPs manually, it can be non-blocking.
+		// is auto-assign-ip mode or manual-assign-ip mode? - default mode is non-blocking 
+		boolean blockUntilRunning = Boolean.parseBoolean(iaas.getProperty("autoAssignIp"));
+		template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+		
+        // this is required in order to avoid creation of additional security groups by Jclouds.
+        template.getOptions().as(TemplateOptions.class).inboundPorts(22, 80, 8080, 443, 8243);
+
+        template.getOptions().as(VCloudTemplateOptions.class).ipAddressAllocationMode(IpAddressAllocationMode.POOL);
+
+        // set Template
+        iaas.setTemplate(template);
+    }
+
+    @Override
+    public void setDynamicPayload(IaasProvider iaasInfo) {
+
+    	// in VCloud case we need to run a script
+        if (iaasInfo.getTemplate() != null && iaasInfo.getPayload() != null) {
+
+        	Template template = iaasInfo.getTemplate();
+        	String script = "";
+        	String launchParams ="", key="";
+        	
+            // open the zip file stream
+            ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(iaasInfo.getPayload()));
+
+            try
+            {
+
+                // now iterate through each item in the stream. The get next
+                // entry call will return a ZipEntry for each file in the
+                // stream
+                ZipEntry entry;
+                while((entry = stream.getNextEntry())!=null)
+                {
+                	StringWriter writer = new StringWriter();
+                	IOUtils.copy(stream, writer);
+                	
+                	if(entry.getName().contains("launch-params")){
+                		launchParams = writer.toString();
+                	} else if(entry.getName().contains("id_rsa")){
+                		key = writer.toString();
+                	}
+                	
+                }
+            } catch (IOException e) {
+	            log.error(e.getMessage(), e);
+            }
+            finally
+            {
+                // we must always close the zip file.
+                try {
+	                stream.close();
+                } catch (IOException e) {
+
+                	log.error("failed to close the ZIP stream", e);
+                }
+            }
+            
+            script = "mkdir /var/lib/cloud && mkdir /var/lib/cloud/instance && mkdir /var/lib/cloud/instance/payload && " +
+            		 "echo \""+launchParams+"\" > /var/lib/cloud/instance/payload/launch-params && " +
+            		 "echo \""+key+"\" > /var/lib/cloud/instance/payload/id_rsa && " +
+            		 "cd /opt/ && " +
+            		 "chmod 755 wso2-openstack-init.sh && "+
+            		 "./wso2-openstack-init.sh";
+        	
+        	template.getOptions().overrideLoginUser(iaasInfo.getProperty("loginUser")).overrideLoginPassword(iaasInfo.getProperty("loginPassword")).runScript(script);
+        }
+
+    }
+
+    @Override
+    public boolean createKeyPairFromPublicKey(IaasProvider iaasInfo, String region, String keyPairName,
+        String publicKey) {
+        
+    	//TODO
+        return false;
+    }
+
+    @Override
+    public String associateAddress(IaasProvider iaasInfo, NodeMetadata node) {
+
+    	// TODO
+        return "";
+        
+    }
+
+	@Override
+    public void releaseAddress(IaasProvider iaasInfo, String ip) {
+		//TODO
+    }
+	
+}


[46/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
new file mode 100644
index 0000000..7332d38
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-service-messages-in-flight.xml
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+    <task class="org.wso2.carbon.mediator.autoscale.lbautoscale.ServiceRequestsInFlightAutoscaler"
+          name="LoadAnalyzer">
+
+        <!--
+            The private key for ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+        <!--
+            The key pair
+        -->
+        <property name="sshKey" value="stratos-1.0.0-keypair"/>
+
+        <property name="loadBalancer">
+            <loadBalancer>
+                <property name="securityGroup" value="stratos-appserver-lb"/>
+                <property name="instanceType" value="m1.large"/>
+                <property name="instances" value="1"/>
+                <property name="elasticIP" value="${ELASTIC_IP}"/>
+                <property name="availabilityZone" value="us-east-1c"/>
+                <property name="payload" value="/mnt/payload.zip"/>
+            </loadBalancer>
+        </property>
+
+        <property name="services">
+            <services>
+                <defaults>
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="as-2011-02-23"/>
+                    <property name="instanceType" value="m1.large"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="messageExpiryTime" value="60000"/>
+                </defaults>
+                <service domain="wso2.as.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                </service>
+                <service domain="wso2.ds.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="ds-2011-02-23"/>
+                </service>
+                <service domain="wso2.bps.domain">
+                    <property name="payload" value="resources/cluster_node.zip"/>
+                    <property name="minAppInstances" value="1"/>
+                    <property name="maxAppInstances" value="5"/>
+                    <property name="queueLengthPerNode" value="400"/>
+                    <property name="roundsToAverage" value="10"/>
+                    <property name="instancesPerScaleUp" value="1"/>
+                    <property name="availabilityZone" value="us-east-1c"/>
+                    <property name="securityGroup" value="bps-2011-02-23"/>
+                </service>
+            </services>
+        </property>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
new file mode 100644
index 0000000..1d017a3
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/AppDomainContextsTest.java
@@ -0,0 +1,105 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+public class AppDomainContextsTest extends TestCase {
+
+    private static Map<String, Map<String, ?>> map;
+    private LoadBalancerConfiguration lbConfig;
+    ConfigurationContext configCtx;
+    ClusteringAgent clusteringAgent;
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
+        clusteringAgent = new TribesClusteringAgent();
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                    "worker"),
+                    "wso2.as1.domain", "worker", -1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as1.domain", "mgt", -1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as2.domain", "mgt", -1);
+        configCtx.getAxisConfiguration().setClusteringAgent(clusteringAgent);
+        
+        File f = new File("src/test/resources/loadbalancer.conf");
+        System.setProperty("loadbalancer.conf", f.getAbsolutePath());
+        lbConfig = LoadBalancerConfiguration.getInstance();
+        
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+    }
+    
+    
+    public void testRemoval(){
+        // removing a cluster domain with only 1 sub domain 
+        lbConfig.removeServiceConfiguration("wso2.as2.domain", "mgt");
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, !map.containsKey("wso2.as2.domain"));
+        
+        // removing a cluster domain with more than 1 sub domain
+        lbConfig.removeServiceConfiguration("wso2.as1.domain", "mgt");
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, map.containsKey("wso2.as1.domain"));
+        Assert.assertEquals(true, map.get("wso2.as1.domain").get("mgt") == null);
+        Assert.assertEquals(true, map.get("wso2.as1.domain").get("worker") != null);
+    }
+    
+    public void testAddition(){
+        ServiceConfiguration config1 = lbConfig.new ServiceConfiguration();
+        config1.setDomain("wso2.as3.domain");
+        config1.setSub_domain("mgt");
+        lbConfig.addServiceConfiguration(config1);
+        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                "mgt"),
+                "wso2.as3.domain", "mgt", -1);
+        map = AutoscaleUtil.getAppDomainContexts(configCtx, lbConfig);
+        
+        Assert.assertEquals(true, map.containsKey("wso2.as3.domain"));
+        Assert.assertEquals(true, map.get("wso2.as3.domain").get("mgt") != null);
+    }
+
+    @Deprecated // use only for writing test cases
+    void printKeys(Map<?,?> map){
+        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
+            Object type = iterator.next();
+            System.out.println(type);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
new file mode 100644
index 0000000..1f1a084
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/java/org/wso2/carbon/mediator/autoscale/lbautoscale/ServiceRequestsInFlightAutoscalerTest.java
@@ -0,0 +1,29 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale;
+
+/**
+ * Test for ServiceRequestsInFlightAutoscaler
+ */
+//public class ServiceRequestsInFlightAutoscalerTest extends TestCase {
+//
+//    public void testInit() {
+//
+//        //new ServiceRequestsInFlightAutoscaler().init(new Axis2SynapseEnvironment());
+//    }
+//}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
new file mode 100644
index 0000000..7b2a80a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/test/resources/loadbalancer.conf
@@ -0,0 +1,50 @@
+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 as1.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      worker;
+                tenant_range    1-5;
+            }
+            wso2.as1.domain {
+            	hosts mgt.as1.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      mgt;
+                tenant_range    1-5;
+            }
+            wso2.as2.domain {
+            	hosts mgt.as2.cloud-test.wso2.com;
+            	  min_app_instances   0;
+            	  sub_domain      mgt;
+                tenant_range    1-5;
+            }
+            
+        }
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
new file mode 100644
index 0000000..49f4624
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/pom.xml
@@ -0,0 +1,107 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+        <artifactId>loadbalancer-components</artifactId>
+        <version>4.1.0</version>
+        <relativePath>../../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.lb.endpoint</artifactId>
+    <packaging>bundle</packaging>
+    <version>4.1.3</version>
+    <name>WSO2 Carbon - Tenant Aware LoadBalance Endpoint</name>
+    <url>http://wso2.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>2.1.1-wso2v4</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>1.6.1-wso2v9</version>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
+           <version>2.1.1</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.wso2.carbon.lb.endpoint.endpoint,
+                            org.wso2.carbon.lb.endpoint,
+                            org.wso2.carbon.lb.endpoint.util,
+                        </Export-Package>
+                        <Import-Package>
+                            !org.wso2.carbon.lb.endpoint.endpoint,
+                            !org.wso2.carbon.lb.endpoint,
+                            org.wso2.carbon.lb.common.*; version=${wso2carbon.version},
+                            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/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
new file mode 100644
index 0000000..cf31ef0
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointConstants.java
@@ -0,0 +1,28 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.lb.endpoint;
+
+/**
+ * The <code>EndpointConstants</code> class defined the endpoint constants.
+ */
+public class EndpointConstants {
+
+    public static final String ADDRESS_ENDPOINT = "Address Endpoint";
+    public static final String WSDL_ENDPOINT = "WSDL Endpoint";
+    public static final String FAILOVER_ENDPOINT = "Failover Group";
+    public static final String LOADBALANCE_ENDPOINT = "Loadbalance Endpoint";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
new file mode 100644
index 0000000..d9366b8
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/EndpointDeployer.java
@@ -0,0 +1,68 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.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);
+        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);
+        mpm.saveItemToRegistry(epName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+        return epName;
+    }
+
+    @Override
+    public void undeploySynapseArtifact(String artifactName) {
+        super.undeploySynapseArtifact(artifactName);
+        mpm.deleteItemFromRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+
+    @Override
+    public void restoreSynapseArtifact(String artifactName) {
+        super.restoreSynapseArtifact(artifactName);
+        mpm.saveItemToRegistry(artifactName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
new file mode 100644
index 0000000..d49758a
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantAwareLoadBalanceEndpointException.java
@@ -0,0 +1,36 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.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/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
new file mode 100644
index 0000000..dec45b4
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/TenantLoadBalanceMembershipHandler.java
@@ -0,0 +1,190 @@
+package org.wso2.carbon.lb.endpoint;
+
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.LoadBalanceMembershipHandler;
+import org.apache.synapse.endpoints.algorithms.AlgorithmContext;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Bridge between Axis2 membership notification and Synapse load balancing
+ */
+public class TenantLoadBalanceMembershipHandler implements LoadBalanceMembershipHandler {
+    private static final Log log = LogFactory.getLog(TenantLoadBalanceMembershipHandler.class);
+
+    private ConfigurationContext configCtx;
+
+    private LoadbalanceAlgorithm lbAlgo;
+    
+    /**
+     * Key - Host, Value - HostContext
+     */
+    private static Map<String, HostContext> hostContextsMap =
+            new HashMap<String, HostContext>();
+    
+    private ClusteringAgent clusteringAgent;
+    
+    private boolean isClusteringEnabled;
+    private String endpointName;
+
+    public TenantLoadBalanceMembershipHandler(Map<String, HostContext> hostContexts,
+                                              LoadbalanceAlgorithm algorithm,
+                                              ConfigurationContext configCtx,
+                                              boolean isClusteringEnabled,
+                                              String endpointName) {
+
+        lbAlgo = algorithm;
+        this.isClusteringEnabled = isClusteringEnabled;
+        this.endpointName = endpointName;
+        this.configCtx = configCtx;
+        
+        for (HostContext host : hostContexts.values()) {
+            
+            addHostContext(host);
+
+        }
+    }
+    
+    /**
+     * This will be used to add new {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void addHostContext(HostContext host){
+        
+        String hostName = host.getHostName();
+
+        AlgorithmContext algorithmContext =
+                                            new AlgorithmContext(isClusteringEnabled,
+                                                                 configCtx, endpointName + "." +
+                                                                            hostName);
+
+        host.setAlgorithm(lbAlgo.clone());
+        host.setAlgorithmContext(algorithmContext);
+
+        hostContextsMap.put(hostName, host);
+        
+    }
+    
+    /**
+     * This will be used to remove an existing {@link HostContext}s.
+     * @param host {@link HostContext}
+     */
+    public void removeHostContext(String host){
+
+        hostContextsMap.remove(host);
+        
+    }
+
+    public void init(Properties props, LoadbalanceAlgorithm algorithm) {
+        // Nothing to do
+    }
+
+    public void setConfigurationContext(ConfigurationContext configCtx) {
+        this.configCtx = configCtx;
+
+        // The following code does the bridging between Axis2 and Synapse load balancing
+        clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            String msg = "In order to enable load balancing across an Axis2 cluster, " +
+                         "the cluster entry should be enabled in the axis2.xml file";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+    }
+
+    public ConfigurationContext getConfigurationContext() {
+        return configCtx;
+    }
+
+    /**
+     * Getting the next member to which the request has to be sent in a round-robin fashion
+     *
+     * @param context The AlgorithmContext
+     * @return The current member
+     * @deprecated Use {@link #getNextApplicationMember(String, int)}
+     */
+    public Member getNextApplicationMember(AlgorithmContext context) {
+        throw new UnsupportedOperationException("This operation is invalid. " +
+                                                "Call getNextApplicationMember(String host)");
+    }
+
+    public boolean isAValidHostName(String host){
+        if(getHostContext(host) != null){
+            return true;
+        }
+        return false;
+    }
+
+    public Member getNextApplicationMember(String host, int tenantId) {
+        HostContext hostContext = getHostContext(host);
+
+        if(hostContext == null){
+            String msg = "Invalid host name : " + host;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        // here we have to pass tenant id to get domain from hostContext
+        String domain = hostContext.getDomainFromTenantId(tenantId);
+        String subDomain = hostContext.getSubDomainFromTenantId(tenantId);
+
+        LoadbalanceAlgorithm algorithm = hostContext.getAlgorithm();
+        GroupManagementAgent groupMgtAgent = clusteringAgent.getGroupManagementAgent(domain, subDomain);
+        
+        if (groupMgtAgent == null) {
+        	String tenantDomain;
+            try {
+	            tenantDomain = ConfigHolder.getInstance().getRealmService().getTenantManager().getDomain(tenantId);
+            } catch (UserStoreException ignore) {
+            	tenantDomain = ""+tenantId;
+            }
+        	
+            String msg =
+                    "No Group Management Agent found for the domain: " + domain + ", subDomain: "
+                    		+ subDomain + ", host: " + host+ " and for tenant: "
+                    		+  tenantDomain;
+            log.error(msg); 
+            throw new SynapseException(msg);
+        }
+        algorithm.setApplicationMembers(groupMgtAgent.getMembers());
+        AlgorithmContext context = hostContext.getAlgorithmContext();
+        return algorithm.getNextApplicationMember(context);
+    }
+
+    public HostContext getHostContext(String host) {
+        HostContext hostContext = hostContextsMap.get(host);
+        if (hostContext == null) {
+            int indexOfDot;
+            if ((indexOfDot = host.indexOf(".")) != -1) {
+                hostContext = getHostContext(host.substring(indexOfDot + 1));
+            } 
+        }
+        return hostContext;
+    }
+
+    public LoadbalanceAlgorithm getLoadbalanceAlgorithm() {
+        return lbAlgo;
+    }
+
+    public Properties getProperties() {
+        return null;
+    }
+    
+    public ClusteringAgent getClusteringAgent() {
+        return clusteringAgent;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
new file mode 100644
index 0000000..31e9f67
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/builder/TopologySyncher.java
@@ -0,0 +1,142 @@
+package org.wso2.carbon.lb.endpoint.builder;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
+import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.wso2.carbon.lb.endpoint.group.mgt.GroupMgtAgentBuilder;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+
+/**
+ * A Thread, which is responsible for making a sense out of a message received for
+ * ELB via topology synchronization.
+ */
+public class TopologySyncher implements Runnable {
+
+    private static final Log log = LogFactory.getLog(TopologySyncher.class);
+
+    /*
+     * This is a reference to sharedTopologyQueue ConfigHolder.
+     */
+    private BlockingQueue<String> sharedQueue;
+
+    public TopologySyncher(BlockingQueue<String> queue) {
+
+        sharedQueue = queue;
+
+    }
+
+    @Override
+    public void run() {
+        // grab the lb configuration instance
+        LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
+
+        // FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer
+        // conf
+        // in order to proper initialization of TribesClusteringAgent.
+        generateGroupMgtAgents(lbconfig);
+
+        // this thread should run for ever, untill terminated.
+        while (true) {
+            try {
+
+                // grabs a message or waits till the queue is non-empty
+                String message = sharedQueue.take();
+//                ConfigHolder data = ConfigHolder.getInstance();
+
+                // this message needs attention only if it's not same as the previous message and
+                // not null of course.
+//                if (data.getPreviousMsg() == null || !data.getPreviousMsg().equals(message)) {
+
+                    // reset the previous message
+//                    data.setPreviousMsg(message);
+
+                    // build the nginx format of this message, and get the Node object
+                    Node topologyNode = NodeBuilder.buildNode(message);
+
+                    // reset service configurations
+//                    lbconfig.resetData();
+                    // create new service configurations
+                    List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
+                    
+                    generateGroupMgtAgents(lbconfig);
+                    
+                    removeGroupMgtAgents(lbconfig, currentServiceConfigs);
+
+//                }
+
+            } catch (InterruptedException ignore) {
+            }
+        }
+
+    }
+
+    private void removeGroupMgtAgents(LoadBalancerConfiguration lbConfig, List<ServiceConfiguration> currentServiceConfigs) {
+
+        for (Iterator iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
+            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
+            
+            for (Iterator iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
+                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
+                
+                if(!currentServiceConfigs.contains(oldServiceConfig)){
+                    // if the ServiceConfiguration is not there any more in the latest topology
+                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                }
+            }
+        }
+    }
+
+    /**
+     * @param lbconfig
+     */
+    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
+        TenantLoadBalanceMembershipHandler handler =
+            ConfigHolder.getInstance()
+                .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg =
+                "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        Map<String, HostContext> hostContexts = lbconfig.getHostContextMap();
+
+        // Add the Axis2 GroupManagement agents
+        if (hostContexts != null) {
+            // iterate through each host context
+            for (HostContext hostCtxt : hostContexts.values()) {
+                // each host can has multiple Tenant Contexts, iterate through them
+                for (TenantDomainContext tenantCtxt : hostCtxt
+                    .getTenantDomainContexts()) {
+
+                    String domain = tenantCtxt.getDomain();
+                    String subDomain = tenantCtxt.getSubDomain();
+
+                    // creates the group management agent
+                    GroupMgtAgentBuilder.createGroupMgtAgent(domain,
+                        subDomain);
+                }
+
+                // add to the handler
+                handler.addHostContext(hostCtxt);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
new file mode 100644
index 0000000..1032fc9
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/cluster/manager/ClusterDomainManagerImpl.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.lb.endpoint.cluster.manager;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.wso2.carbon.cartridge.messages.ClusterDomainManager;
+import org.wso2.carbon.cartridge.messages.ClusterDomain;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
+import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+
+/**
+ * Bridge between the ELB and the Stratos2 Agent.
+ */
+public class ClusterDomainManagerImpl implements ClusterDomainManager {
+
+    private static final Log log = LogFactory.getLog(ClusterDomainManagerImpl.class);
+
+    @Override
+    public void addClusterDomain(ClusterDomain cluster) {
+
+        // create group management agent, if one doesn't exist already.
+        HostContext hostCtxt = createGroupMgtAgentIfNotExists(cluster);
+
+        // we should only update if the above step is successful.
+        if (hostCtxt != null) {
+            // create / update Service Configuration
+            createOrUpdateServiceConfig(cluster, hostCtxt);
+        }
+        
+    }
+
+    @Override
+	public void removeClusterDomain(String domain, String subDomain, String hostName) {
+
+		TenantLoadBalanceMembershipHandler handler =
+		                                             ConfigHolder.getInstance()
+		                                                         .getTenantLoadBalanceMembershipHandler();
+
+		if (handler == null) {
+			String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+			log.error(msg);
+			throw new SynapseException(msg);
+		}
+
+		handler.removeHostContext(hostName);
+		
+		LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+		
+		lbConfig.removeServiceConfiguration(domain, subDomain);
+		
+	}
+    
+    private void createOrUpdateServiceConfig(ClusterDomain cluster, HostContext ctxt) {
+        LoadBalancerConfiguration lbConfig = ConfigHolder.getInstance().getLbConfig();
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+        
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+        int minInstances = cluster.getMinInstances();
+        int maxInstances = cluster.getMaxInstances();
+        String service = cluster.getServiceName();
+        int maxRequestsPerSecond = cluster.getMaxRequestsPerSecond();
+    	int roundsToAverage = cluster.getRoundsToAverage(); 
+    	double alarmingUpperRate = cluster.getAlarmingUpperRate();
+    	double alarmingLowerRate = cluster.getAlarmingLowerRate();
+    	double scaleDownFactor = cluster.getScaleDownFactor();
+        
+        ServiceConfiguration serviceConfig ;
+        
+        if((serviceConfig = lbConfig.getServiceConfig(domain, subDomain)) == null){
+            serviceConfig = lbConfig.new ServiceConfiguration();
+        }
+        
+        // we simply override the attributes with new values
+        serviceConfig.setDomain(domain);
+        serviceConfig.setSub_domain(subDomain);
+        serviceConfig.setTenant_range(tenantRange);
+        serviceConfig.setHosts(hostName);
+        serviceConfig.setMin_app_instances(minInstances);
+        serviceConfig.setMax_app_instances(maxInstances);
+        serviceConfig.setMax_requests_per_second(maxRequestsPerSecond);
+        serviceConfig.setRounds_to_average(roundsToAverage);
+        serviceConfig.setAlarming_upper_rate(alarmingUpperRate);
+        serviceConfig.setAlarming_lower_rate(alarmingLowerRate);
+        serviceConfig.setScale_down_factor(scaleDownFactor);
+        
+        // add to host name tracker
+        lbConfig.addToHostNameTrackerMap(service, serviceConfig.getHosts());
+        
+        // add to host contexts
+        lbConfig.addToHostContextMap(hostName, ctxt);
+        
+        // finally add this service config
+        lbConfig.addServiceConfiguration(serviceConfig);
+    }
+
+    protected HostContext createGroupMgtAgentIfNotExists(ClusterDomain cluster) {
+        
+        String domain = cluster.getDomain();
+        String subDomain = cluster.getSubDomain();
+        String hostName = cluster.getHostName();
+        String tenantRange = cluster.getTenantRange();
+
+        // sub domain can be null, but others can't
+        if (domain == null || hostName == null || tenantRange == null) {
+            String msg =
+                         "Invalid value/s detected - domain: " + domain + "\n host name: " +
+                                 hostName + "\n tenant range: " + tenantRange;
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        if (subDomain == null || subDomain.isEmpty()) {
+            // uses default sub domain
+            subDomain = Constants.DEFAULT_SUB_DOMAIN;
+        }
+
+        ClusteringAgent clusteringAgent = null;
+
+        try {
+            clusteringAgent =
+                              ConfigHolder.getInstance().getAxisConfiguration()
+                                          .getClusteringAgent();
+
+        } catch (Exception e) {
+            String msg = "Failed to retrieve Clustering Agent.";
+            log.error(msg, e);
+            throw new SynapseException(msg, e);
+
+        }
+
+        if (clusteringAgent == null) {
+            String msg = "Clustering Agent is null.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        /*
+         * Add Group Management Agent if one is not already present for this domain and sub
+         * domain
+         */
+
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
+                                                    domain, subDomain,-1);
+
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent added to cluster domain: " + domain +
+                          " and sub domain: " + subDomain);
+            }
+
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("Group management agent is already available for cluster domain: " +
+                          domain + " and sub domain: " + subDomain);
+            }
+        }
+
+        TenantLoadBalanceMembershipHandler handler =
+                                                     ConfigHolder.getInstance()
+                                                                 .getTenantLoadBalanceMembershipHandler();
+
+        if (handler == null) {
+            String msg = "TenantLoadBalanceMembershipHandler is null. Thus, We cannot proceed.";
+            log.error(msg);
+            throw new SynapseException(msg);
+        }
+
+        HostContext hostCtxt;
+
+        // if there's an already registered HostContext use it
+        if((hostCtxt = handler.getHostContext(hostName)) == null){
+            hostCtxt = new HostContext(hostName);
+        }
+        
+        List<TenantDomainContext> ctxts;
+        ctxts = new ArrayList<TenantDomainContext>(hostCtxt.getTenantDomainContexts());
+
+        // default value is super tenant mode - which is defined by tenant id 0, in this context
+        int tenantId = 0;
+        if(!"*".equals(tenantRange)){
+        	tenantId = Integer.parseInt(tenantRange);
+        }
+                
+        ctxts.add(new TenantDomainContext(tenantId, domain, subDomain));
+
+        hostCtxt.addTenantDomainContexts(ctxts);
+
+        handler.addHostContext(hostCtxt);
+
+        return hostCtxt;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
new file mode 100644
index 0000000..16f392a
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/endpoint/TenantAwareLoadBalanceEndpoint.java
@@ -0,0 +1,513 @@
+package org.wso2.carbon.lb.endpoint.endpoint;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseConstants;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.config.xml.endpoints.utils.LoadbalanceAlgorithmFactory;
+import org.apache.synapse.core.LoadBalanceMembershipHandler;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.endpoints.DynamicLoadbalanceFaultHandler;
+import org.apache.synapse.endpoints.Endpoint;
+import org.apache.synapse.endpoints.algorithms.LoadbalanceAlgorithm;
+import org.apache.synapse.endpoints.dispatch.HttpSessionDispatcher;
+import org.apache.synapse.endpoints.dispatch.SALSessions;
+import org.apache.synapse.endpoints.dispatch.SessionInformation;
+import org.apache.synapse.transport.nhttp.NhttpConstants;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
+import org.wso2.carbon.lb.common.util.DomainMapping;
+import org.wso2.carbon.lb.common.group.mgt.*;
+import org.wso2.carbon.lb.common.cache.URLMappingCache;
+import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
+import org.wso2.carbon.lb.endpoint.internal.RegistryManager;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+
+public class TenantAwareLoadBalanceEndpoint extends org.apache.synapse.endpoints.DynamicLoadbalanceEndpoint implements Serializable {
+
+    private static final long serialVersionUID = 1577351815951789938L;
+    private static final Log log = LogFactory.getLog(TenantAwareLoadBalanceEndpoint.class);
+    /**
+     * Axis2 based membership handler which handles members in multiple clustering domains
+     */
+    private TenantLoadBalanceMembershipHandler tlbMembershipHandler;
+
+    /**
+     * Key - host name
+     * Value - {@link HostContext}
+     */
+    private Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
+
+    private LoadBalancerConfiguration lbConfig;
+
+    /**
+     * keep the size of cache which used to keep hostNames of url mapping.
+     */
+    private URLMappingCache mappingCache;
+    private RegistryManager registryManager;
+    private int sizeOfCache;
+
+    private boolean initialized;
+
+    private String algorithm;
+        private String configuration;
+        private String failOver;
+
+    @Override
+    public void init(SynapseEnvironment synapseEnvironment) {
+        try {
+
+            lbConfig = ConfigHolder.getInstance().getLbConfig();
+            hostContexts = lbConfig.getHostContextMap();
+            sizeOfCache = lbConfig.getLoadBalancerConfig().getSizeOfCache();
+            mappingCache = URLMappingCache.getInstance(sizeOfCache);
+            setSessionTimeout(lbConfig.getLoadBalancerConfig().getSessionTimeOut());
+            setFailover(lbConfig.getLoadBalancerConfig().getFailOver());
+
+        } catch (Exception e) {
+            String msg = "Failed while reading Load Balancer configuration";
+            log.error(msg, e);
+            throw new TenantAwareLoadBalanceEndpointException(msg, e);
+        }
+
+
+        LoadbalanceAlgorithm algorithm = null;
+        try {
+            OMElement payload = AXIOMUtil.stringToOM(generatePayLoad());
+            algorithm =
+                    LoadbalanceAlgorithmFactory.
+                            createLoadbalanceAlgorithm(payload, null);
+
+        } catch (Exception e) {
+            String msg = "Error While creating Load balance algorithm";
+            log.error(msg, e);
+            throw new SynapseException(msg, e);
+        }
+
+        if (!initialized) {
+            super.init(synapseEnvironment);
+            ConfigurationContext cfgCtx =
+                                          ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
+            ClusteringAgent clusteringAgent = cfgCtx.getAxisConfiguration().getClusteringAgent();
+            if (clusteringAgent == null) {
+                throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+            }
+
+            // Add the Axis2 GroupManagement agents
+            if (hostContexts != null) {
+                // iterate through each host context
+                for (HostContext hostCtxt : hostContexts.values()) {
+                    // each host can has multiple Tenant Contexts, iterate through them
+                    for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
+
+                        String domain = tenantCtxt.getDomain();
+                        String subDomain = tenantCtxt.getSubDomain();
+
+                        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                            String gmAgentClass = lbConfig.getLoadBalancerConfig().getGroupManagementAgentClass();
+                            GroupManagementAgent groupManagementAgent;
+                            if (gmAgentClass != null) {
+                                try {
+                                    groupManagementAgent = (GroupManagementAgent) Class.forName(gmAgentClass).newInstance();
+                                } catch (Exception e) {
+                                    String msg = "Cannot instantiate GroupManagementAgent. Class: " + gmAgentClass;
+                                    log.error(msg, e);
+                                    throw new TenantAwareLoadBalanceEndpointException(msg, e);
+                                }
+                            } else {
+                                groupManagementAgent = new SubDomainAwareGroupManagementAgent(subDomain);
+                            }
+                            clusteringAgent.addGroupManagementAgent(groupManagementAgent,
+                                                                    domain, subDomain,-1);
+                            if (log.isDebugEnabled()) {
+                                log.debug("Group management agent added to cluster domain: " +
+                                          domain + " and sub domain: " + subDomain);
+                            }
+                        }
+                    }
+                }
+
+                tlbMembershipHandler =
+                                       new TenantLoadBalanceMembershipHandler(hostContexts,
+                                                                              algorithm, cfgCtx,
+                                                                              isClusteringEnabled,
+                                                                              getName());
+
+                // set TenantLoadBalanceMembershipHandler for future reference
+                ConfigHolder.getInstance().setTenantLoadBalanceMembershipHandler(tlbMembershipHandler);
+            }
+
+            // Initialize the SAL Sessions if already has not been initialized.
+            SALSessions salSessions = SALSessions.getInstance();
+            if (!salSessions.isInitialized()) {
+                salSessions.initialize(isClusteringEnabled, cfgCtx);
+            }
+            setSessionAffinity(true);
+            setDispatcher(new HttpSessionDispatcher());
+            initialized = true;
+            log.info("Tenant Aware Load Balance Endpoint is initialized.");
+        }
+
+    }
+
+    	public void setConfiguration(String paramEle) {
+    	        configuration = paramEle;
+    	}
+
+    	    public void setAlgorithm(String paramEle) {
+    	        this.algorithm = paramEle;
+    	    }
+
+    	    public void setFailOver(String paramEle) {
+    	        this.failOver = paramEle;
+    	    }
+
+
+    public String getName() {
+		return "tlbEndpoint";
+	}
+
+    //TODO remove following hard coded element
+    private String generatePayLoad() {
+        return " <serviceDynamicLoadbalance failover=\"true\"\n" +
+                "                                           algorithm=\"org.apache.synapse.endpoints.algorithms.RoundRobin\"" +
+                //"                                           configuration=\"$system:loadbalancer.xml\"" +
+                "/>";
+    }
+
+    public LoadBalanceMembershipHandler getLbMembershipHandler() {
+        return tlbMembershipHandler;
+    }
+
+
+    public void send(MessageContext synCtx) {
+        /*   setCookieHeader(synCtx);     */
+        Member currentMember = null;
+        SessionInformation sessionInformation = null;
+        String actualHost = null;
+
+        //Gathering required information for domain mapping
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> transportHeaders = (Map<String, String>) axis2MessageContext.
+                getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String targetHost = transportHeaders.get(HTTP.TARGET_HOST);
+
+        String port = "";
+        boolean containsPort = false;
+        if (targetHost.contains(":")) {
+            containsPort = true;
+            port = targetHost.substring(targetHost.indexOf(':') + 1, targetHost.length());
+            targetHost = targetHost.substring(0, targetHost.indexOf(':'));
+        }
+        //Gathering required information for domain mapping done
+
+        boolean isValidHost = tlbMembershipHandler.isAValidHostName(targetHost);
+        DomainMapping domainMapping = null;
+        if(!isValidHost){
+            //check if the host is valid, if not valid, execute following code to check whether it is a mapped domain
+            domainMapping = mappingCache.getMapping(targetHost);
+            if(domainMapping == null){
+                registryManager = new RegistryManager();
+                domainMapping = registryManager.getMapping(targetHost);
+                mappingCache.addValidMapping(targetHost, domainMapping);
+            }
+            if (domainMapping != null) {
+                actualHost = domainMapping.getActualHost();
+
+                if(containsPort){
+                    transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
+                } else {
+                    transportHeaders.put(HTTP.TARGET_HOST, actualHost);
+                }
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
+
+            } else {
+                String msg = "Invalid host name : " + targetHost;
+                log.error(msg);
+                throw new SynapseException(msg);
+            }
+        }
+
+        if (isSessionAffinityBasedLB()) {
+            // first check if this session is associated with a session. if so, get the endpoint
+            // associated for that session.
+            sessionInformation =
+                    (SessionInformation) synCtx.getProperty(
+                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION);
+
+            currentMember = (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("Current session id : " + 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 a not heavy data structure
+                    synCtx.setProperty(
+                            SynapseConstants.PROP_SAL_CURRENT_SESSION_INFORMATION, sessionInformation);
+                }
+            }
+
+        }
+
+        // Dispatch request the relevant member
+//        String targetHost = getTargetHost(synCtx);
+        ConfigurationContext configCtx =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext().getConfigurationContext();
+
+        if (tlbMembershipHandler.getConfigurationContext() == null) {
+            tlbMembershipHandler.setConfigurationContext(configCtx);
+        }
+
+        if(tlbMembershipHandler.getClusteringAgent() == null) {
+            tlbMembershipHandler.setConfigurationContext(configCtx);
+        }
+
+        TenantDynamicLoadBalanceFaultHandlerImpl faultHandler = new TenantDynamicLoadBalanceFaultHandlerImpl();
+        log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
+        faultHandler.setHost(actualHost != null ? actualHost : targetHost);
+
+        if (sessionInformation != null && currentMember != null) {
+            //send message on current session
+            sessionInformation.updateExpiryTime();
+            sendToApplicationMember(synCtx, currentMember, faultHandler, false);
+        } else {
+//            prepare for a new session
+            int tenantId = getTenantId(synCtx);
+            //check if this is a valid host name registered in ELB
+            if(tlbMembershipHandler.isAValidHostName(targetHost)){
+                currentMember = tlbMembershipHandler.getNextApplicationMember(targetHost, tenantId);
+                if (currentMember == null) {
+                    String msg = "No application members available";
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+                sendToApplicationMember(synCtx, currentMember, faultHandler, true);
+            } else {
+                if(domainMapping == null){
+                    registryManager = new RegistryManager();
+                    domainMapping = registryManager.getMapping(targetHost);
+                    mappingCache.addValidMapping(targetHost, domainMapping);
+                }
+                if(domainMapping != null) {
+
+                    actualHost = domainMapping.getActualHost();
+                    
+                    log.debug("************* Actual Host: "+actualHost +" ****** Target Host: "+targetHost);
+                    faultHandler.setHost(actualHost != null ? actualHost : targetHost);
+
+                    if(containsPort){
+                        transportHeaders.put(HTTP.TARGET_HOST, actualHost + ":" + port);
+                    } else {
+                        transportHeaders.put(HTTP.TARGET_HOST, actualHost);
+                    }
+                    ((Axis2MessageContext) synCtx).getAxis2MessageContext().setProperty("TRANSPORT_HEADERS" , transportHeaders);
+
+                    currentMember = tlbMembershipHandler.getNextApplicationMember(actualHost,tenantId);
+                    sendToApplicationMember(synCtx,currentMember,faultHandler,true);
+                }else {
+                    String msg = "Invalid host name : " + targetHost;
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+            }
+        }
+    }
+
+
+//    public List<HostContext> getHostContexts() {
+//        return Collections.unmodifiableList(hostContexts);
+//    }
+
+    /**
+     * This FaultHandler will try to resend the message to another member if an error occurs
+     * while sending to some member. This is a failover mechanism
+     */
+
+    /**
+     * @param url to url for target
+     * @return tenantID if tenant id available else 0
+     */
+    private int getTenantId(String url) {
+        String servicesPrefix = "/t/";
+        if (url != null && url.contains(servicesPrefix)) {
+            int domainNameStartIndex =
+                    url.indexOf(servicesPrefix) + servicesPrefix.length();
+            int domainNameEndIndex = url.indexOf('/', domainNameStartIndex);
+            String domainName = url.substring(domainNameStartIndex,
+                    domainNameEndIndex == -1 ? url.length() : domainNameEndIndex);
+
+            // return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+        }
+        // return 0 if the domain name is null
+        return 0;
+    }
+
+    private int getTenantId(MessageContext synCtx){
+    	String url = synCtx.getTo().toString();
+    	int tenantId = getTenantId(url);
+    	// tenantId = 0 because domain name was null. May be this is the SSO response
+    	if(tenantId == 0 && url.contains(MultitenantConstants.TENANT_DOMAIN+"=")){
+    		// OK,this is the SAML SSO response from the IS
+    		// e.g url = https://localhost:9444/acs?teantDomain=domain
+    		String domainName = url.split("=").clone()[1];
+    		// return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return ConfigHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+    	}
+    	return tenantId;
+    }
+
+
+    /**
+     * This FaultHandler will try to resend the message to another member if an error occurs
+     * while sending to some member. This is a failover mechanism
+     */
+    private class TenantDynamicLoadBalanceFaultHandlerImpl extends DynamicLoadbalanceFaultHandler {
+
+        private EndpointReference to;
+        private Member currentMember;
+        private Endpoint currentEp;
+        private String host;
+
+        private static final int MAX_RETRY_COUNT = 5;
+
+        // ThreadLocal variable to keep track of how many times this fault handler has been
+        // called
+        private ThreadLocal<Integer> callCount = new ThreadLocal<Integer>() {
+            protected Integer initialValue() {
+                return 0;
+            }
+        };
+
+        public void setHost(String host) {
+            log.debug("Setting host name: "+host);
+            this.host = host;
+        }
+
+        public void setCurrentMember(Member currentMember) {
+            this.currentMember = currentMember;
+        }
+
+        public void setTo(EndpointReference to) {
+            this.to = to;
+        }
+
+        private TenantDynamicLoadBalanceFaultHandlerImpl() {
+        }
+
+        public void onFault(MessageContext synCtx) {
+            if (currentMember == null || to == null) {
+                return;
+            }
+
+            // Prevent infinite retrying to failed members
+            callCount.set(callCount.get() + 1);
+            if (callCount.get() >= MAX_RETRY_COUNT) {
+                log.debug("Retrying to a failed member has stopped.");
+                return;
+            }
+
+            //cleanup endpoint if exists
+            if (currentEp != null) {
+                currentEp.destroy();
+            }
+            Integer errorCode = (Integer) synCtx.getProperty(SynapseConstants.ERROR_CODE);
+            if (errorCode != null) {
+                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED)) {
+                    currentMember.suspend(10000);     // TODO: Make this configurable.
+                    log.info("Suspended member " + currentMember + " for 10s due to connection failure to that member");
+                }
+                if (errorCode.equals(NhttpConstants.CONNECTION_FAILED) ||
+                        errorCode.equals(NhttpConstants.CONNECT_CANCEL) ||
+                        errorCode.equals(NhttpConstants.CONNECT_TIMEOUT)) {
+                    
+                    if (!synCtx.getFaultStack().isEmpty()) {
+                        synCtx.getFaultStack().pop();
+                    }
+                    // Try to resend to another member
+                    Member newMember = tlbMembershipHandler.getNextApplicationMember(host, getTenantId(synCtx.toString()));
+                    if (newMember == null || newMember.isSuspended()) {
+                        String msg = "No application members available having host name : "+host+
+                                " and tenant id : "+getTenantId(synCtx.toString()+" and which is not suspended.");
+                        log.error(msg);
+                        throw new SynapseException(msg);
+                    }
+                    synCtx.setTo(to);
+                    if (isSessionAffinityBasedLB()) {
+                        // We are sending 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);
+                        }
+                    }
+                    try {
+                        Thread.sleep(1000);  // Sleep for sometime before retrying
+                    } catch (InterruptedException ignored) {
+                    }
+                    
+                    if(synCtx == null || to == null) {
+                        return;
+                    }
+                    log.info("Failed over to " + newMember);
+                    sendToApplicationMember(synCtx, newMember, this, true);
+                } else if (errorCode.equals(NhttpConstants.SND_IO_ERROR_SENDING) ||
+                        errorCode.equals(NhttpConstants.CONNECTION_CLOSED)) {
+                    // TODO: Envelope is consumed
+                    String msg = "Error sending request! Connection to host "+host+
+                            " might be closed. Error code: "+errorCode;
+                    log.error(msg);
+                    throw new SynapseException(msg);
+                }
+            }
+            // We cannot failover since we are using binary relay
+        }
+
+        public void setCurrentEp(Endpoint currentEp) {
+            this.currentEp = currentEp;
+        }
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
new file mode 100644
index 0000000..da25156
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/group/mgt/GroupMgtAgentBuilder.java
@@ -0,0 +1,62 @@
+package org.wso2.carbon.lb.endpoint.group.mgt;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.wso2.carbon.lb.common.group.mgt.SubDomainAwareGroupManagementAgent;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+
+/**
+ * Responsible for building {@link GroupManagementAgent}s.
+ */
+public class GroupMgtAgentBuilder {
+    
+    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
+	
+    /**
+     * Creates a {@link SubDomainAwareGroupManagementAgent} corresponds to the given 
+     * parameters, if and only if there's no existing agent.
+     * @param domain clustering domain.
+     * @param subDomain clustering sub domain.
+     */
+    public static void createGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(subDomain),
+                domain, subDomain,-1);
+            
+            log.info("Group management agent added to cluster domain: " +
+                domain + " and sub domain: " + subDomain);
+        }
+    }
+    
+    public static void resetGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
+            
+            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
+            
+            log.info("Group management agent of cluster domain: " +
+                domain + " and sub domain: " + subDomain+" is removed.");
+        }
+    }
+}


[20/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ClusteringClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ClusteringClient.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ClusteringClient.java
new file mode 100644
index 0000000..190e4d4
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ClusteringClient.java
@@ -0,0 +1,268 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent;
+
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.clustering.*;
+import org.apache.axis2.clustering.tribes.TribesClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.Parameter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.exception.CartridgeAgentException;
+import org.wso2.carbon.cartridge.agent.registrant.PortMapping;
+import org.wso2.carbon.cartridge.agent.registrant.Registrant;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantDatabase;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantUtil;
+import org.wso2.carbon.cartridge.messages.CreateClusterDomainMessage;
+import org.wso2.carbon.cartridge.messages.CreateRemoveClusterDomainMessage;
+
+import javax.xml.stream.XMLStreamException;
+import java.io.ByteArrayInputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+
+/**
+ * This class is used for all Axis2 clustering related activities such as joining the load balancer
+ * & joining registrants to clustering groups.
+ */
+public class ClusteringClient {
+    private static final Log log = LogFactory.getLog(ClusteringClient.class);
+    public static final Random RANDOM = new Random();
+    private Properties conf;
+    private RegistrantDatabase registrantDatabase;
+    private ClusteringAgent loadBalancerAgent;
+
+    public ClusteringClient(RegistrantDatabase registrantDatabase) {
+        this.registrantDatabase = registrantDatabase;
+    }
+
+    public void init(Properties conf,
+                     ConfigurationContext configurationContext,
+                     MembershipListener membershipListener) throws CartridgeAgentException {
+        try {
+            this.conf = conf;
+            joinLoadBalancer(configurationContext, membershipListener);
+        } catch (Exception e) {
+            String msg = "Cannot initialize ClusteringClient";
+            log.error(msg, e);
+            throw new CartridgeAgentException(msg, e);
+        }
+    }
+
+    private void joinLoadBalancer(ConfigurationContext configurationContext,
+                                  MembershipListener membershipListener)
+            throws CartridgeAgentException {
+
+        try {
+            loadBalancerAgent = createClusteringAgent(configurationContext,
+                                                      conf.getProperty("loadBalancerDomain"));
+            List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
+            membershipListeners.add(membershipListener);
+            ((TribesClusteringAgent) loadBalancerAgent).setMembershipListeners(membershipListeners);
+            loadBalancerAgent.init();
+        } catch (Exception e) {
+            String msg = "Cannot join LB group";
+            log.error(msg, e);
+            throw new CartridgeAgentException(msg, e);
+        }
+    }
+
+    /**
+     * Join a cluster group of the Elastic Load Balancer
+     *
+     * @param registrant           Registrant
+     * @param configurationContext ConfigurationContext
+     * @throws CartridgeAgentException If an error occurs while joining a cluster group
+     */
+    public void joinGroup(Registrant registrant,
+                          ConfigurationContext configurationContext) throws CartridgeAgentException {
+        if (registrantDatabase.containsActive(registrant)) {
+            throw new CartridgeAgentException("Active registrant with key " +
+                                              registrant.getKey() + " already exists");
+        }
+        registrantDatabase.add(registrant);
+
+        if (!RegistrantUtil.isHealthy(registrant)) {
+            String msg = "Couldn't add registrant " + registrant + " due to a health check failure";
+            log.error(msg);
+            return;
+            //throw new CartridgeAgentException(msg);
+        }
+        try {
+            List<ClusteringCommand> clusteringCommands =
+                    loadBalancerAgent.sendMessage(new CreateClusterDomainMessage(registrant.getService(),
+                                                                                 registrant.retrieveClusterDomain(),
+                                                                                 registrant.getHostName(),
+                                                                                 registrant.getTenantRange(),
+                                                                                 registrant.getMinInstanceCount(),
+                                                                                 registrant.getMaxInstanceCount(),
+                                                                                 registrant.getMaxRequestsPerSecond(),
+                                                                                 registrant.getRoundsToAverage(),
+                                                                                 registrant.getAlarmingUpperRate(),
+                                                                                 registrant.getAlarmingLowerRate(),
+                                                                                 registrant.getScaleDownFactor()),
+                                                  true);
+            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
+                for (ClusteringCommand clusteringCommand : clusteringCommands) {
+                    clusteringCommand.execute(configurationContext);
+                }
+            } else {
+                return;
+            }
+
+        } catch (ClusteringFault e) {
+            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
+        }
+        ClusteringAgent agent;
+        try {
+            agent = createClusteringAgent(configurationContext,
+                                          registrant.retrieveClusterDomain());
+            
+        } catch (ClusteringFault e) {
+            handleException("Cannot create ClusteringAgent for registrant", e);
+            return;
+        }
+
+        //Add port.mapping.<port> entries to member
+        /*
+       <parameter name="properties">
+           <property name="port.mapping.8281" value="9768"/>
+           <property name="port.mapping.8244" value="9448"/>
+       </parameter>
+        */
+        Parameter propsParam = new Parameter();
+        propsParam.setName("properties");
+
+        StringBuilder propertiesPayload = new StringBuilder("<parameter name=\"properties\">");
+        int httpPort = -1;
+        int httpsPort = -1;
+        for (PortMapping portMapping : registrant.getPortMappings()) {
+            propertiesPayload.append("<property name=\"portMapping.mapping.").append(portMapping.getProxyPort()).
+                    append("\" value=\"").append(portMapping.getPrimaryPort()).append("\" />");
+            if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTP)) {
+                httpPort = portMapping.getPrimaryPort();
+            } else if (portMapping.getType().equals(PortMapping.PORT_TYPE_HTTPS)) {
+                httpsPort = portMapping.getPrimaryPort();
+            }
+        }
+
+        String remoteHost = registrant.getRemoteHost();
+        propertiesPayload.append("<property name=\"httpPort\" value=\"").append(httpPort).append("\" />");
+        propertiesPayload.append("<property name=\"httpsPort\" value=\"").append(httpsPort).append("\" />");
+        propertiesPayload.append("<property name=\"remoteHost\" value=\"").append(remoteHost).append("\" />");
+        propertiesPayload.append("<property name=\"subDomain\" value=\"__$default\" />");
+        propertiesPayload.append("</parameter>");
+
+        try {
+            StAXOMBuilder builder = new StAXOMBuilder(new ByteArrayInputStream(propertiesPayload.toString().getBytes()));
+            propsParam.setParameterElement(builder.getDocumentElement());
+            agent.addParameter(propsParam);
+        } catch (XMLStreamException e) {
+            handleException("Cannot create properties ClusteringAgent parameter", e);
+        } catch (AxisFault ignored) { // will not occur
+        }
+
+        int newMemberPort = Integer.parseInt(conf.getProperty("clustering.localMemberPort")) +
+                            RANDOM.nextInt(5000) + 27;
+        addParameter(agent, "localMemberPort", newMemberPort + "");
+        try {
+            synchronized (registrant) {
+                if(!registrant.running()) {
+                    registrant.start(agent);
+                }
+            }
+        } catch (ClusteringFault e) {
+            handleException("Cannot start registrant", e);
+        }
+        
+        // Update instance state in stratos database, with active
+        new Thread(new InstanceStateNotificationClientThread(registrant, "ACTIVE")).start();
+    }
+    
+    
+    public void removeClusterDomain(String domain,
+                                    String subDomain,
+                                    String hostName,
+                                    ConfigurationContext configurationContext) throws CartridgeAgentException {
+    	try {
+            List<ClusteringCommand> clusteringCommands =
+                    loadBalancerAgent.sendMessage(new CreateRemoveClusterDomainMessage(domain, subDomain, hostName),
+                                                  true);
+            if (clusteringCommands != null && !clusteringCommands.isEmpty()) {
+                for (ClusteringCommand clusteringCommand : clusteringCommands) {
+                    clusteringCommand.execute(configurationContext);
+                }
+            } else {
+                return;
+            }
+        } catch (ClusteringFault e) {
+            handleException("Cannot send CreateClusterDomainMessage to ELB", e);
+        }
+    }
+
+    private void handleException(String msg, Exception e) throws CartridgeAgentException {
+        log.error(msg, e);
+        throw new CartridgeAgentException(msg, e);
+    }
+
+    private ClusteringAgent createClusteringAgent(ConfigurationContext configurationContext,
+                                                  String clusterDomain) throws ClusteringFault {
+        TribesClusteringAgent agent = new TribesClusteringAgent();
+        addParameter(agent, "AvoidInitiation", "true");
+        for (String key : conf.stringPropertyNames()) {
+            if (key.startsWith("clustering.")) {
+                addParameter(agent,
+                             key.substring(key.indexOf(".") + 1),
+                             conf.getProperty(key));
+            }
+        }
+
+        List<Member> members = new ArrayList<Member>();
+        for (int i = 1; i < Integer.MAX_VALUE; i++) {
+            String host = conf.getProperty("members." + i + ".host");
+            String port = conf.getProperty("members." + i + ".port");
+            if (host == null || port == null) {
+                break;
+            }
+            members.add(new Member(host, Integer.parseInt(port)));
+        }
+        agent.setMembers(members);
+
+        addParameter(agent, "domain", clusterDomain);
+        agent.setConfigurationContext(configurationContext);
+
+        List<MembershipListener> membershipListeners = new ArrayList<MembershipListener>();
+        membershipListeners.add(new RegistrantMembershipListener(this, configurationContext));
+        agent.setMembershipListeners(membershipListeners);
+        return agent;
+    }
+
+    private static void addParameter(ClusteringAgent agent,
+                                     String paramName, String paramValue) {
+        Parameter parameter = new Parameter(paramName, paramValue);
+        try {
+            agent.removeParameter(parameter);
+            agent.addParameter(parameter);
+        } catch (AxisFault ignored) {
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ELBMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ELBMembershipListener.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ELBMembershipListener.java
new file mode 100644
index 0000000..d44a778
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/ELBMembershipListener.java
@@ -0,0 +1,81 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.MembershipListener;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.exception.CartridgeAgentException;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantDatabase;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantUtil;
+
+/**
+ * This membership listener will get notified when the Elastic Load Balancer (ELB) joins or
+ * leaves the cluster
+ *
+ * When the ELB leaves the cluster, we have to disconnect all Registrants, and when the ELB rejoins,
+ * we have to reconnect all the Registrants to the ELB
+ */
+public class ELBMembershipListener implements MembershipListener {
+    private static final Log log = LogFactory.getLog(ELBMembershipListener.class);
+
+    private ClusteringClient clusteringClient;
+    private ConfigurationContext configurationContext;
+    private RegistrantDatabase registrantDatabase;
+    private RegistrantHealthChecker healthChecker;
+
+    public ELBMembershipListener(ClusteringClient clusteringClient,
+                                 ConfigurationContext configurationContext,
+                                 RegistrantDatabase registrantDatabase,
+                                 RegistrantHealthChecker healthChecker) {
+        this.clusteringClient = clusteringClient;
+        this.configurationContext = configurationContext;
+        this.registrantDatabase = registrantDatabase;
+        this.healthChecker = healthChecker;
+    }
+
+    public void memberAdded(Member member, boolean b) {
+        log.info("ELB Member [" + member + "] joined cluster");
+        Runnable runnable = new Runnable() {
+            public void run() {
+                try {
+                    try {
+                        Thread.sleep(5000);
+                    } catch (InterruptedException ignored) {
+                    }
+                    RegistrantUtil.reloadRegistrants(clusteringClient,
+                                                     configurationContext,
+                                                     registrantDatabase);
+                    healthChecker.setELBRunning(true);
+                } catch (CartridgeAgentException e) {
+                    log.error("Could not reload registrants", e);
+                }
+            }
+        };
+        new Thread(runnable).start();
+    }
+
+    public void memberDisappeared(Member member, boolean b) {
+        log.info("ELB Member [" + member + "] left cluster");
+        healthChecker.setELBRunning(false);
+        registrantDatabase.stopAll();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/InstanceStateNotificationClientThread.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/InstanceStateNotificationClientThread.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/InstanceStateNotificationClientThread.java
new file mode 100644
index 0000000..e8a7766
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/InstanceStateNotificationClientThread.java
@@ -0,0 +1,44 @@
+package org.wso2.carbon.cartridge.agent;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.instanceinfo.mgt.stub.InstanceInformationManagementServiceStub;
+import org.wso2.carbon.cartridge.agent.registrant.Registrant;
+
+import java.rmi.RemoteException;
+
+public class InstanceStateNotificationClientThread implements Runnable {
+
+	private Registrant registrant;
+	private String state;
+
+	private static final Log log = LogFactory
+			.getLog(InstanceStateNotificationClientThread.class);
+
+	public InstanceStateNotificationClientThread(Registrant registrant,
+			String state) {
+		this.registrant = registrant;
+		this.state = state;
+	}
+
+	public void run() {
+		try {
+			log.info("Instance State is updated to " + state + " "
+					+ registrant.getRemoteHost());
+			String serviceURL = "https://" + System.getProperty("adc.host")
+					+ ":" + System.getProperty("adc.port")
+					+ "/services/InstanceInformationManagementService";
+			InstanceInformationManagementServiceStub stub = new InstanceInformationManagementServiceStub(
+					serviceURL);
+			stub.updateInstanceState(registrant.getRemoteHost(), 123,
+					registrant.retrieveClusterDomain(), "__$default",
+					registrant.getService(), state);
+		} catch (AxisFault e) {
+            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
+		} catch (RemoteException e) {
+            log.warn("Error notifying state " + state + " of registrant " + registrant + " to ADC", e);
+		}
+
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/Main.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/Main.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/Main.java
new file mode 100644
index 0000000..72729fd
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/Main.java
@@ -0,0 +1,156 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.engine.AxisServer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.internal.CartridgeAgentConstants;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantDatabase;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.wso2.carbon.cartridge.agent.service.CartridgeAgentService;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * The main class which starts up the Cartridge agent
+ */
+//public class Main {
+//    private static final Log log = LogFactory.getLog(Main.class);
+//    private static RegistrantHealthChecker healthChecker;
+//    public static void main(String[] args) {
+//        FileInputStream confFileIPStream = null;
+//        try {
+//            long start = System.currentTimeMillis();
+//            log.info("Starting WSO2 Cartridge Agent...");
+//            Properties conf = new Properties();
+//            confFileIPStream = new FileInputStream("conf" + File.separator + "agent.properties");
+//            conf.load(confFileIPStream);
+//            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
+//            AxisServer axisServer = new AxisServer();
+//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
+//            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
+//            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
+//            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
+//            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
+//            int healthCheckIntervalInt =
+//                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
+//            int threadPoolSizeInt =
+//                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
+//            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
+//            healthChecker = new RegistrantHealthChecker(registrantDatabase,
+//                                                        clusteringClient,
+//                                                        configurationContext,
+//                                                        healthCheckIntervalInt,
+//                                                        threadPoolSizeInt
+//                                                        );
+//            clusteringClient.init(conf,
+//                                  configurationContext,
+//                                  new ELBMembershipListener(clusteringClient,
+//                                                            configurationContext,
+//                                                            registrantDatabase,
+//                                                            healthChecker));
+//            healthChecker.startAll();
+//            axisServer.deployService(CartridgeAgentService.class.getName());
+//
+//
+//            // Starting cliet..
+//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
+//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+//            // new InstanceStateNotificationClient().notify(null, null);
+//
+//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
+//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
+//            // ----------------------
+//
+//            writePID(".");
+//            Runtime.getRuntime().addShutdownHook(new Thread(){
+//
+//                @Override
+//                public void run() {
+//                    log.info("Shutting down WSO2 Cartridge Agent...");
+//                }
+//            });
+//            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
+//        } catch (Exception e) {
+//            log.fatal("Could not start Cartridge Agent", e);
+//            System.exit(1);
+//        } finally {
+//            if (confFileIPStream != null) {
+//                try {
+//                    confFileIPStream.close();
+//                } catch (IOException e) {
+//                    log.error("Cannot close agent.properties file", e);
+//                }
+//            }
+//        }
+//    }
+//
+//    public static RegistrantHealthChecker getHealthChecker(){
+//        return healthChecker;
+//    }
+//    /**
+//     * Write the process ID of this process to the file
+//     *
+//     * @param carbonHome carbon.home sys property value.
+//     */
+//    private static void writePID(String carbonHome) {
+//        byte[] bo = new byte[100];
+//        String[] cmd = {"bash", "-c", "echo $PPID"};
+//        Process p;
+//        try {
+//            p = Runtime.getRuntime().exec(cmd);
+//        } catch (IOException e) {
+//            //ignored. We might be invoking this on a Window platform. Therefore if an error occurs
+//            //we simply ignore the error.
+//            return;
+//        }
+//
+//        try {
+//            int bytes = p.getInputStream().read(bo);
+//        } catch (IOException e) {
+//            log.error(e.getMessage(), e);
+//        }
+//
+//        String pid = new String(bo);
+//        if (pid.length() != 0) {
+//            BufferedWriter out = null;
+//            try {
+//                FileWriter writer = new FileWriter(carbonHome + File.separator + "wso2carbon.pid");
+//                out = new BufferedWriter(writer);
+//                out.write(pid);
+//            } catch (IOException e) {
+//                log.warn("Cannot write wso2carbon.pid file");
+//            } finally {
+//                if (out != null) {
+//                    try {
+//                        out.close();
+//                    } catch (IOException ignored) {
+//                    }
+//                }
+//            }
+//        }
+//    }
+//}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/RegistrantMembershipListener.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/RegistrantMembershipListener.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/RegistrantMembershipListener.java
new file mode 100644
index 0000000..5782693
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/RegistrantMembershipListener.java
@@ -0,0 +1,55 @@
+/**
+ * 
+ */
+package org.wso2.carbon.cartridge.agent;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.MembershipListener;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.registrant.Registrant;
+
+/**
+ * @author wso2
+ *
+ */
+public class RegistrantMembershipListener implements MembershipListener{
+	
+	private ClusteringClient clusteringClient;
+	private ConfigurationContext configurationContext;
+
+	private static final Log log = LogFactory.getLog(RegistrantMembershipListener.class);
+	
+	public RegistrantMembershipListener(ClusteringClient clusteringClient,
+	                                    ConfigurationContext configurationContext) {
+		this.clusteringClient = clusteringClient;
+		this.configurationContext = configurationContext;
+    }
+
+	public void memberAdded(Member arg0, boolean arg1) {
+	    log.info(" ********* Member is added to the group ... " + arg0);
+    }
+
+	public void memberDisappeared(Member member, boolean arg1) {
+		 log.info(" **********  Member is removed from group ... " + member);
+		 Registrant registrant = new Registrant();
+		 
+		 //HostName : cartridgeName + "." + cartridgeInfo.getHostName()
+		 // sajithphpautoscale.php.slive.com.php.domain
+		 //Domain : HostName.php.domain
+		 // TODO
+    		/* String hostName = getHostNameFromDomain(member.getDomain());
+    		 log.info("Host name is returned as: " + hostName);
+    		 try {
+    	        clusteringClient.removeClusterDomain(member.getDomain(), "__$default", hostName, configurationContext);
+            } catch (CartridgeAgentException e) {
+    	        e.printStackTrace();
+            }*/
+    }
+
+	private String getHostNameFromDomain(String domain) {
+	    return domain.substring(0, domain.length()-11);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/exception/CartridgeAgentException.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/exception/CartridgeAgentException.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/exception/CartridgeAgentException.java
new file mode 100644
index 0000000..c69ba1c
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/exception/CartridgeAgentException.java
@@ -0,0 +1,39 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.exception;
+
+/**
+ * CartridgeAgentException
+ */
+public class CartridgeAgentException extends Exception {
+    public CartridgeAgentException() {
+        super();
+    }
+
+    public CartridgeAgentException(String s) {
+        super(s);
+    }
+
+    public CartridgeAgentException(String s, Throwable throwable) {
+        super(s, throwable);
+    }
+
+    public CartridgeAgentException(Throwable throwable) {
+        super(throwable);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentConstants.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentConstants.java
new file mode 100644
index 0000000..5dbe2cd
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentConstants.java
@@ -0,0 +1,26 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.cartridge.agent.internal;
+
+/**
+ * Constants used in the Cartridge Agent
+ */
+public final class CartridgeAgentConstants {
+    public static final String CLUSTERING_CLIENT = "clustering.client";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentServiceComponent.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentServiceComponent.java
new file mode 100644
index 0000000..f03ef57
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/CartridgeAgentServiceComponent.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.cartridge.agent.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.cartridge.agent.ClusteringClient;
+import org.wso2.carbon.cartridge.agent.ELBMembershipListener;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantDatabase;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantHealthChecker;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Properties;
+
+/**
+ * @scr.component name="org.wso2.carbon.cartridge.agent" immediate="true"
+ *
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ */
+public class CartridgeAgentServiceComponent {
+    private static final Log log = LogFactory.getLog(CartridgeAgentServiceComponent.class);
+
+    protected void activate(ComponentContext ctx) {
+        RegistrantHealthChecker healthChecker;
+        ConfigurationContext configurationContext = DataHolder.getServerConfigContext();
+
+        FileInputStream confFileIPStream = null;
+        try {
+            long start = System.currentTimeMillis();
+            log.info("Starting WSO2 Cartridge Agent...");
+            Properties conf = new Properties();
+            confFileIPStream = new FileInputStream(CarbonUtils.getCarbonConfigDirPath() +
+                    File.separator + "agent.properties");
+            conf.load(confFileIPStream);            
+            for (String name : conf.stringPropertyNames()) {
+    			String value = conf.getProperty(name);
+    			System.setProperty(name, value);
+    		}
+            
+            RegistrantDatabase registrantDatabase = new RegistrantDatabase();
+//            AxisServer axisServer = new AxisServer();
+//            ConfigurationContext configurationContext = axisServer.getConfigurationContext();
+            ClusteringClient clusteringClient = new ClusteringClient(registrantDatabase);
+            configurationContext.setProperty(CartridgeAgentConstants.CLUSTERING_CLIENT, clusteringClient);
+
+            String healthCheckInterval = conf.getProperty("registrant.heathCheckInterval");
+            String threadPoolSize = conf.getProperty("registrant.healthCheckThreadPoolSize");
+            int healthCheckIntervalInt =
+                    (healthCheckInterval == null) ? 2000 : Integer.parseInt(healthCheckInterval);
+            int threadPoolSizeInt =
+                    (threadPoolSize == null) ? 10 : Integer.parseInt(healthCheckInterval);
+            log.info("Registrant health check interval: " + healthCheckIntervalInt + "s");
+            healthChecker = new RegistrantHealthChecker(registrantDatabase,
+                    clusteringClient,
+                    configurationContext,
+                    healthCheckIntervalInt,
+                    threadPoolSizeInt
+            );
+            clusteringClient.init(conf,
+                    configurationContext,
+                    new ELBMembershipListener(clusteringClient,
+                            configurationContext,
+                            registrantDatabase,
+                            healthChecker));
+            healthChecker.startAll();
+            DataHolder.setHealthChecker(healthChecker);
+            /*configurationContext.deployService(AxisService.createService(CartridgeAgentService.class.getName().toString(),
+                     configurationContext.getAxisConfiguration()));*/
+//            axisServer.deployService(CartridgeAgentService.class.getName());
+
+
+            // Starting cliet..
+//            String trustStorePath = conf.getProperty("wso2.carbon.truststore");
+//            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
+//            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
+//            // new InstanceStateNotificationClient().notify(null, null);
+//
+//            System.setProperty("adc.host",  conf.getProperty("adc.host"));
+//            System.setProperty("adc.port",  conf.getProperty("adc.port"));
+            // ----------------------
+
+            Runtime.getRuntime().addShutdownHook(new Thread(){
+
+                @Override
+                public void run() {
+                    log.info("Shutting down WSO2 Cartridge Agent...");
+                }
+            });
+            log.info("Started Cartridge Agent in " + (System.currentTimeMillis() - start) + "ms");
+        } catch (Exception e) {
+            log.fatal("Could not start Cartridge Agent", e);
+            //System.exit(1);
+        } finally {
+            if (confFileIPStream != null) {
+                try {
+                    confFileIPStream.close();
+                } catch (IOException e) {
+                    log.error("Cannot close agent.properties file", e);
+                }
+            }
+        }
+
+    }
+
+    protected void deactivate(ComponentContext ctx) {
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        DataHolder.setServerConfigContext(contextService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/DataHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/DataHolder.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/DataHolder.java
new file mode 100644
index 0000000..5b5f92f
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/internal/DataHolder.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright WSO2, Inc. (http://wso2.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.cartridge.agent.internal;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.cartridge.agent.registrant.RegistrantHealthChecker;
+
+public class DataHolder {
+    private static ConfigurationContext serverConfigContext;
+    private static RegistrantHealthChecker healthChecker;
+
+    public static void setServerConfigContext(ConfigurationContext serverConfigContext) {
+        DataHolder.serverConfigContext = serverConfigContext;
+    }
+
+    public static void setHealthChecker(RegistrantHealthChecker healthChecker) {
+        DataHolder.healthChecker = healthChecker;
+    }
+
+    public static ConfigurationContext getServerConfigContext() {
+        return serverConfigContext;
+    }
+
+    public static RegistrantHealthChecker getHealthChecker() {
+        return healthChecker;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/PortMapping.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/PortMapping.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/PortMapping.java
new file mode 100644
index 0000000..8b082fe
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/PortMapping.java
@@ -0,0 +1,88 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.registrant;
+
+import java.io.Serializable;
+
+/**
+ * This class provides the mapping between the actual port &amp; proxy port of a {@link org.wso2.carbon.cartridge.agent.registrant.Registrant}
+ *
+ * e.g. if the Registrant is serving HTTP requests on port 9763, and the requests to that port have
+ * to be proxied via port 80 on the ELB, the <code>primaryPort</code> has to be specified as 9763
+ * &amp; <code>proxyPort</code> has to be specified as 80.
+ *
+ * @see org.wso2.carbon.cartridge.agent.registrant.Registrant
+ */
+@SuppressWarnings("unused")
+public class PortMapping implements Serializable {
+
+    private static final long serialVersionUID = 8020727939469156788L;
+    public static final String PORT_TYPE_HTTP = "http";
+    public static final String PORT_TYPE_HTTPS = "https";
+
+    private int primaryPort;
+    private int proxyPort;
+    private String type;
+
+    public PortMapping() {
+    }
+
+    public int getPrimaryPort() {
+        return primaryPort;
+    }
+
+    public int getProxyPort() {
+        return proxyPort;
+    }
+
+    public void setPrimaryPort(int primaryPort) {
+        this.primaryPort = primaryPort;
+    }
+
+    public void setProxyPort(int proxyPort) {
+        this.proxyPort = proxyPort;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        if (type.equalsIgnoreCase(PORT_TYPE_HTTP) && type.equalsIgnoreCase(PORT_TYPE_HTTPS)) {
+            throw new RuntimeException("Invalid port type " + type);
+        }
+        this.type = type;
+    }
+
+    public boolean equals (Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        PortMapping that = (PortMapping) o;
+        return (type.equalsIgnoreCase(that.type) &&
+               (primaryPort == that.primaryPort) &&
+               (proxyPort == that.proxyPort));
+    }
+
+    @Override
+    public int hashCode() {
+        return type.hashCode() +
+                Integer.toString(primaryPort).hashCode() +
+                Integer.toString(proxyPort).hashCode();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/Registrant.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/Registrant.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/Registrant.java
new file mode 100644
index 0000000..b6a9d2f
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/Registrant.java
@@ -0,0 +1,197 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.registrant;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+
+import java.io.Serializable;
+import java.util.Arrays;
+
+/**
+ * This class represents a process which registers itself with this Cartridge Agent
+ */
+@SuppressWarnings("unused")
+public class Registrant implements Serializable {
+
+    private static final long serialVersionUID = 1026289225178520964L;
+
+    private String key;
+    //private int tenantId;
+    private String tenantRange;
+    private String service;
+    private String hostName;
+    private PortMapping[] portMappings;
+    private String remoteHost;
+    private transient ClusteringAgent clusteringAgent;
+    private int minInstanceCount;
+    private int maxInstanceCount;
+    private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+   
+
+	public String getService() {
+        return service;
+    }
+
+    public String getTenantRange() {
+    	return tenantRange;
+    }
+
+	public void setTenantRange(String tenantRange) {
+    	this.tenantRange = tenantRange;
+    }
+
+	public void setService(String service) {
+        this.service = service;
+    }
+
+    public String getHostName() {
+        return hostName;
+    }
+
+    public void setHostName(String hostName) {
+        this.hostName = hostName;
+    }
+
+    public PortMapping[] getPortMappings() {
+        return Arrays.copyOf(portMappings, portMappings.length);
+    }
+
+    public void setPortMappings(PortMapping[] portMappings) {
+        this.portMappings = Arrays.copyOf(portMappings, portMappings.length);
+    }
+
+    public String getKey() {
+        return key;
+    }
+
+    public void setKey(String key) {
+        this.key = key;
+    }    
+    
+    public int getMinInstanceCount() {
+		return minInstanceCount;
+	}
+
+	public void setMinInstanceCount(int minInstanceCount) {
+		this.minInstanceCount = minInstanceCount;
+	}
+
+	public int getMaxInstanceCount() {
+		return maxInstanceCount;
+	}
+
+	public void setMaxInstanceCount(int maxInstanceCount) {
+		this.maxInstanceCount = maxInstanceCount;
+	}
+
+	public String retrieveClusterDomain() {
+		// alias.hostname.php.domain
+		return hostName+"."+service+".domain";
+    }
+
+    public void start(ClusteringAgent clusteringAgent) throws ClusteringFault {
+        this.clusteringAgent = clusteringAgent;
+        clusteringAgent.init();
+    }
+
+    public void stop() {
+        if (clusteringAgent != null) {
+            clusteringAgent.stop();
+        }
+        clusteringAgent = null;
+    }
+
+    public boolean running() {
+        return clusteringAgent != null;
+    }
+
+    public String getRemoteHost() {
+        return remoteHost;
+    }
+
+    public void setRemoteHost(String remoteHost) {
+        this.remoteHost = remoteHost;
+    }    
+    
+    public int getMaxRequestsPerSecond() {
+    	return maxRequestsPerSecond;
+    }
+
+	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
+    	this.maxRequestsPerSecond = maxRequestsPerSecond;
+    }
+
+	public int getRoundsToAverage() {
+    	return roundsToAverage;
+    }
+
+	public void setRoundsToAverage(int roundsToAverage) {
+    	this.roundsToAverage = roundsToAverage;
+    }
+
+	public double getAlarmingUpperRate() {
+    	return alarmingUpperRate;
+    }
+
+	public void setAlarmingUpperRate(double alarmingUpperRate) {
+    	this.alarmingUpperRate = alarmingUpperRate;
+    }
+
+	public double getAlarmingLowerRate() {
+    	return alarmingLowerRate;
+    }
+
+	public void setAlarmingLowerRate(double alarmingLowerRate) {
+    	this.alarmingLowerRate = alarmingLowerRate;
+    }
+
+	public double getScaleDownFactor() {
+    	return scaleDownFactor;
+    }
+
+	public void setScaleDownFactor(double scaleDownFactor) {
+    	this.scaleDownFactor = scaleDownFactor;
+    }
+
+	@Override
+    public String toString() {
+        return "Registrant{" +
+               "key='" + key + '\'' +
+               ", remoteHost='" + remoteHost + '\'' +
+               '}';
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        Registrant that = (Registrant) o;
+        return key.equals(that.key);
+    }
+
+    @Override
+    public int hashCode() {
+        return key.hashCode();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantDatabase.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantDatabase.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantDatabase.java
new file mode 100644
index 0000000..f6e4e2b
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantDatabase.java
@@ -0,0 +1,141 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.registrant;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.InstanceStateNotificationClientThread;
+import org.wso2.carbon.cartridge.agent.exception.CartridgeAgentException;
+
+import java.io.*;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * This class represents a database for {@link Registrant}s. Registrants added to this database will be
+ * persisted, so that when the Cartridge Agent is restarted, the Registrants can be restored.
+ *
+ * @see Registrant
+ */
+public class RegistrantDatabase {
+    private static final Log log = LogFactory.getLog(RegistrantDatabase.class);
+
+    private List<Registrant> registrants = new CopyOnWriteArrayList<Registrant>();
+
+    public void add(Registrant registrant) throws CartridgeAgentException {
+        if (registrants.contains(registrant) && registrant.running()) {
+            throw new CartridgeAgentException("Active registrant with key " +
+                                              registrant.getKey() + " already exists");
+        }
+        synchronized (registrant) {
+            if (!isAlreadyAdded(registrant)) {
+                persist(registrant);
+                registrants.add(registrant);
+                log.info("Added registrant " + registrant);
+
+            } else {
+                log.info("Registrant " + registrant + "has been already added");
+            }
+        }
+    }
+
+    private void persist(Registrant registrant) throws CartridgeAgentException {
+        try {
+            ObjectOutput out = null;
+            try {
+                // Serialize to a file
+                if (!new File("registrants").exists() && !new File("registrants").mkdirs()) {
+                    throw new IOException("Cannot create registrants directory");
+                }
+                out = new ObjectOutputStream(new FileOutputStream("registrants" + File.separator +
+                                                                  registrant.getKey() + ".ser"));
+                out.writeObject(registrant);
+                out.close();
+            } finally {
+                if (out != null) {
+                    out.close();
+                }
+            }
+        } catch (IOException e) {
+            log.error("Could not serialize registrant " + registrant, e);
+        }
+    }
+
+    public void stopAll() {
+        for (Registrant registrant : registrants) {
+        	new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+            registrant.stop();
+        }
+    }
+
+    public boolean containsActive(Registrant registrant) {
+        return registrants.contains(registrant) &&
+               registrants.get(registrants.indexOf(registrant)).running();
+    }
+
+    public List<Registrant> getRegistrants() {
+        return Collections.unmodifiableList(registrants);
+    }
+
+    public boolean isAlreadyAdded(Registrant registrant) {
+
+        boolean alreadyAdded = false;
+        for (Registrant registrantFromDb : registrants) {
+            if(registrantFromDb.getRemoteHost().equals(registrant.getRemoteHost())) {
+
+                PortMapping[] portMappingofRegistrantOfDB = registrantFromDb.getPortMappings();
+                PortMapping[] portMappingofRegistrant = registrant.getPortMappings();
+
+                if(portMappingofRegistrant.length != portMappingofRegistrantOfDB.length) {
+                    continue;
+
+                } else {
+                    alreadyAdded = checkPortMappings(registrant, registrantFromDb);
+                }
+
+            } else {
+                continue;
+            }
+        }
+        return alreadyAdded;
+    }
+
+    private boolean checkPortMappings (Registrant newRegistrant, Registrant existingRegistrant) {
+
+        PortMapping[] portMappingsOfNewRegistrant = newRegistrant.getPortMappings();
+        PortMapping[] portMappingsOfExistingRegistrant = existingRegistrant.getPortMappings();
+
+        for (PortMapping portMappingOfNewRegistrant : portMappingsOfNewRegistrant) {
+            boolean matchFound = false;
+            for (PortMapping portMappingOfExistingRegistrant : portMappingsOfExistingRegistrant) {
+                if(portMappingOfExistingRegistrant.equals(portMappingOfNewRegistrant)) {
+                    matchFound = true;
+                    break;
+                }
+            }
+            if(!matchFound) {
+                return false;
+            }
+        }
+        if(log.isDebugEnabled()) {
+            log.debug("***********************************Found matching registrant for " + newRegistrant + " in the Registrant database");
+        }
+        return true;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantHealthChecker.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantHealthChecker.java
new file mode 100644
index 0000000..c263641
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantHealthChecker.java
@@ -0,0 +1,113 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.registrant;
+
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.ClusteringClient;
+import org.wso2.carbon.cartridge.agent.InstanceStateNotificationClientThread;
+
+/**
+ * This health checker periodically checks the health of the {@link Registrant}s
+ *
+ * If a registrant is found to be unhealthy, then it is stopped. This task will also try to
+ * connect to reactivate a registrant which was previously found to be unhealthy.
+ *
+ * If the Elastic Load Balancer (ELB) is not running, this health checker will not continue with
+ * registrant health checks since it is futile to try to connect the registrants to the
+ * unavailable ELB.
+ */
+public class RegistrantHealthChecker {
+    private static final Log log = LogFactory.getLog(RegistrantHealthChecker.class);
+
+    private RegistrantDatabase database;
+    private ClusteringClient clusteringClient;
+    private ConfigurationContext configurationContext;
+    private ScheduledExecutorService scheduler;
+    private volatile boolean isELBRunning;
+    private int healthCheckInterval;
+
+    public RegistrantHealthChecker(RegistrantDatabase database,
+                                   ClusteringClient clusteringClient,
+                                   ConfigurationContext configurationContext,
+                                   int healthCheckInterval,
+                                   int threadPoolSize) {
+        this.database = database;
+        this.clusteringClient = clusteringClient;
+        this.configurationContext = configurationContext;
+        this.healthCheckInterval = healthCheckInterval;
+        scheduler = Executors.newScheduledThreadPool(threadPoolSize);
+    }
+
+    public void startAll() {
+        List<Registrant> registrants = database.getRegistrants();
+        for (Registrant registrant : registrants) {
+            scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
+                                 healthCheckInterval, TimeUnit.SECONDS);
+            if (log.isDebugEnabled()) {
+                log.debug("Started a health checker for " + registrant + " ...");
+            }
+        }
+    }
+
+    public void start(Registrant registrant){
+        scheduler.scheduleWithFixedDelay(new HealthCheckerTask(registrant), 45,
+                             healthCheckInterval, TimeUnit.SECONDS);
+        if (log.isDebugEnabled()) {
+            log.debug("Added a health checker for " + registrant + " ...");
+        }
+    }
+
+    public void setELBRunning(boolean ELBRunning) {
+        isELBRunning = ELBRunning;
+    }
+
+    private final class HealthCheckerTask implements Runnable {
+        Registrant registrant;
+        public HealthCheckerTask(Registrant registrant){
+            this.registrant = registrant;
+        }
+        public void run() {
+            if(!isELBRunning){
+                return;
+            }
+            try {
+                boolean healthyRegistrant = RegistrantUtil.isHealthy(registrant);
+                if (!healthyRegistrant && registrant.running()) {
+                    registrant.stop();
+                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+                    log.warn("Stopped registrant " + registrant + " since it is unhealthy." );
+                } else if (healthyRegistrant && !registrant.running()) {
+                    registrant.stop();
+                    new Thread(new InstanceStateNotificationClientThread(registrant, "INACTIVE")).start();
+                    clusteringClient.joinGroup(registrant, configurationContext);
+                    log.info("Restarted registrant " + registrant + " after it became active");
+                }
+            } catch (Exception e) {
+                log.error("Error occurred while running registrant health check", e);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantUtil.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantUtil.java
new file mode 100644
index 0000000..5f07ed7
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/registrant/RegistrantUtil.java
@@ -0,0 +1,175 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.registrant;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.ClusteringClient;
+import org.wso2.carbon.cartridge.agent.exception.CartridgeAgentException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.net.*;
+
+/**
+ * Utility method collection for handling {@link Registrant}s
+ *
+ * @see Registrant
+ */
+public class RegistrantUtil {
+    private static final Log log = LogFactory.getLog(RegistrantUtil.class);
+    private static boolean registrantsReloaded = false;
+    /**
+     * Before adding a member, we will try to verify whether we can connect to it
+     *
+     * @param registrant The member whose connectvity needs to be verified
+     * @return true, if the member can be contacted; false, otherwise.
+     */
+    public static boolean isHealthy(Registrant registrant) {
+        if (log.isDebugEnabled()) {
+            log.debug("Trying to connect to registrant " + registrant + "...");
+        }
+        if(log.isDebugEnabled()) {
+            log.debug("***********************************************isHealthy() method for registrant " + registrant);
+        }
+        String registrantRemoteHost = registrant.getRemoteHost();
+        log.debug("remote host : " + registrantRemoteHost);
+        if(registrantRemoteHost == null){
+            registrantRemoteHost = "localhost";
+        }
+        InetAddress addr;
+        try {
+            addr = InetAddress.getByName(registrantRemoteHost);
+            if(log.isDebugEnabled()) {
+                log.debug("***********************************************Host resolved for registrant " + registrant);
+            }
+        } catch (UnknownHostException e) {
+            log.error("Registrant " + registrant + " is unhealthy");
+            return false;
+        }
+        PortMapping[] portMappings = registrant.getPortMappings();
+
+        int maxRetries = Integer.parseInt(System.getProperty("clustering.maxRetries"));
+
+        for (int retries = maxRetries; retries > 0; retries--) {
+            try {
+                for (PortMapping portMapping : portMappings) {
+                    int port = portMapping.getPrimaryPort();
+                    if(log.isDebugEnabled()) {
+                        log.debug("***********************************************primary port" + port + " registrant " + registrant);
+                    }
+                    if (port != -1 && port != 0) {
+                        if(log.isDebugEnabled()) {
+                            log.debug("***********************************************connecting to " + registrant +
+                                    " re-try: " + retries);
+                        }
+                        SocketAddress httpSockaddr = new InetSocketAddress(addr, port);
+                        new Socket().connect(httpSockaddr, 10000);
+                        if(log.isDebugEnabled()) {
+                            log.debug("***********************************************connected successfully to port: " + port);
+                        }
+                    }
+                }
+                return true;
+            } catch (IOException e) {
+				if (log.isDebugEnabled()) {
+					log.debug("Error occurred.. " + e.getMessage());
+				}
+                String msg = e.getMessage();
+                if (!msg.contains("Connection refused") && !msg.contains("connect timed out")) {
+                    String msg2 = "Cannot connect to registrant " + registrant;
+                    log.error(msg2, e);
+                }
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException ignored) {
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Reload all the registrants persisted in the file system
+     * @param clusteringClient ClusteringClient
+     * @param configurationContext   ConfigurationContext
+     * @param registrantDatabase  RegistrantDatabase
+     * @throws CartridgeAgentException If reloading registrants fails
+     */
+    public static void reloadRegistrants(ClusteringClient clusteringClient,
+                                         ConfigurationContext configurationContext,
+                                         RegistrantDatabase registrantDatabase) throws CartridgeAgentException {
+
+        if(registrantsReloaded) {
+            log.info("Registrants already re-loaded, therefore not re-loading again");
+            return;
+        }
+
+        File registrants = new File("registrants");
+        if (!registrants.exists()) {
+            log.info("Registrant information doesn't exist in the file system");
+            return;
+        }
+        File[] files = registrants.listFiles();
+        if (files == null) {
+            log.error("Directory 'Registrants' is invalid");
+            return;
+
+        } else if (files.length == 0) {
+            log.info("No registrant information found in the Registrants directory");
+            return;
+        }
+
+        for (File file : files) {
+            try {
+                Registrant registrant =
+                        deserializeRegistrant("registrants" + File.separator + file.getName());
+                if (!registrantDatabase.containsActive(registrant)) {
+                    clusteringClient.joinGroup(registrant, configurationContext);
+                }
+            } catch (IOException e) {
+                log.error("Cannot deserialize registrant file " + file.getName(), e);
+            }
+        }
+        registrantsReloaded = true;
+    }
+
+    private static Registrant deserializeRegistrant(String fileName) throws IOException {
+        Registrant registrant = null;
+        ObjectInputStream in = null;
+
+        try {
+            // Deserialize from a file
+            File file = new File(fileName);
+            in = new ObjectInputStream(new FileInputStream(file));
+            // Deserialize the object
+            registrant = (Registrant) in.readObject();
+        } catch (ClassNotFoundException ignored) {
+        } finally {
+            if (in != null) {
+                in.close();
+            }
+        }
+        return registrant;
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/service/CartridgeAgentService.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/service/CartridgeAgentService.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/service/CartridgeAgentService.java
new file mode 100644
index 0000000..709f31b
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/java/org/wso2/carbon/cartridge/agent/service/CartridgeAgentService.java
@@ -0,0 +1,67 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.agent.service;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.cartridge.agent.exception.CartridgeAgentException;
+import org.wso2.carbon.cartridge.agent.ClusteringClient;
+import org.wso2.carbon.cartridge.agent.internal.CartridgeAgentConstants;
+import org.wso2.carbon.cartridge.agent.internal.DataHolder;
+import org.wso2.carbon.cartridge.agent.registrant.Registrant;
+
+/**
+ * Web service used for allowing {@link Registrant}s to register themselves with the Cartridge Agent
+ *
+ * @see Registrant
+ */
+@SuppressWarnings("unused")
+public class CartridgeAgentService {
+    private static final Log log = LogFactory.getLog(CartridgeAgentService.class);
+
+    public boolean register(Registrant registrant) throws CartridgeAgentException {
+
+        MessageContext messageContext = MessageContext.getCurrentMessageContext();
+        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
+        ClusteringClient clusteringClient =
+                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
+        if (registrant.getRemoteHost() == null || registrant.getRemoteHost().isEmpty()) {
+            String remoteAddr = (String) messageContext.getProperty("REMOTE_ADDR");
+            registrant.setRemoteHost(remoteAddr);
+        }
+        log.info("Trying to add new registrant " + registrant + "...");
+        clusteringClient.joinGroup(registrant, configurationContext);
+//        Main.getHealthChecker().start(registrant);
+        DataHolder.getHealthChecker().start(registrant);
+        return true;
+
+    }
+
+    public boolean unregister(String domain, String subDomain, String hostName) throws CartridgeAgentException {
+
+        MessageContext messageContext = MessageContext.getCurrentMessageContext();
+        ConfigurationContext configurationContext = messageContext.getConfigurationContext();
+        ClusteringClient clusteringClient =
+                (ClusteringClient) configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
+        clusteringClient.removeClusterDomain(domain, subDomain, hostName, configurationContext);
+        return true;
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..dfde0a9
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,27 @@
+<!-- ~ Copyright WSO2 Inc. (http://www.wso2.com) All Rights
+	Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License,
+	~ Version 2.0 (the "License"); you may not use this file except ~ in compliance
+	with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0
+	~ ~ Unless required by applicable law or agreed to in writing, ~ software
+	distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT
+	WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the
+	License for the ~ specific language governing permissions and limitations
+	~ under the License. -->
+<serviceGroup>
+    <service name="CartridgeAgentService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <description>
+            Admin service for ADC activities
+        </description>
+        <parameter name="ServiceClass">org.wso2.carbon.cartridge.agent.service.CartridgeAgentService
+        </parameter>
+        <parameter name="enableMTOM">true</parameter>
+        <parameter name="adminService" locked="true">false</parameter>
+        <parameter name="hiddenService" locked="true">false</parameter>
+        <parameter name="AuthorizationAction" locked="true">
+            /permission/admin/manage/modify/webapp    </parameter>
+        <parameter name="DoAuthentication" locked="true">true</parameter>
+    </service>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/pom.xml b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/pom.xml
new file mode 100644
index 0000000..f1e5084
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/pom.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>cartridge-agent-parent</artifactId>
+        <version>2.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
+    <packaging>bundle</packaging>
+    <version>2.1.1</version>
+    <name>WSO2 Cartridge Agent - Messages</name>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </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>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.wso2.carbon.cartridge.messages.*
+                        </Export-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/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomain.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomain.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomain.java
new file mode 100644
index 0000000..26accae
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomain.java
@@ -0,0 +1,99 @@
+package org.wso2.carbon.cartridge.messages;
+
+public class ClusterDomain {
+
+	private String domain;
+	private String subDomain;
+	private String hostName;
+	//private int tenantId;
+	private String tenantRange;
+	private int minInstances;
+	private int maxInstances;
+	private String serviceName;
+	private int maxRequestsPerSecond;
+	private int roundsToAverage;
+	private double alarmingUpperRate;
+	private double alarmingLowerRate;
+	private double scaleDownFactor;
+	
+	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;
+	}
+	public String getHostName() {
+		return hostName;
+	}
+	public void setHostName(String hostName) {
+		this.hostName = hostName;
+	}
+	/*public int getTenantId() {
+		return tenantId;
+	}
+	public void setTenantId(int tenantId) {
+		this.tenantId = tenantId;
+	}*/
+	public int getMinInstances() {
+		return minInstances;
+	}
+	public void setMinInstances(int minInstances) {
+		this.minInstances = minInstances;
+	}
+	public int getMaxInstances() {
+		return maxInstances;
+	}
+	public void setMaxInstances(int maxInstances) {
+		this.maxInstances = maxInstances;
+	}
+	public String getServiceName() {
+		return serviceName;
+	}
+	public void setServiceName(String serviceName) {
+		this.serviceName = serviceName;
+	}
+	public String getTenantRange() {
+    	return tenantRange;
+    }
+	public void setTenantRange(String tenantRange) {
+    	this.tenantRange = tenantRange;
+    }
+	public int getMaxRequestsPerSecond() {
+    	return maxRequestsPerSecond;
+    }
+	public void setMaxRequestsPerSecond(int maxRequestsPerSecond) {
+    	this.maxRequestsPerSecond = maxRequestsPerSecond;
+    }
+	public int getRoundsToAverage() {
+    	return roundsToAverage;
+    }
+	public void setRoundsToAverage(int roundsToAverage) {
+    	this.roundsToAverage = roundsToAverage;
+    }
+	public double getAlarmingUpperRate() {
+    	return alarmingUpperRate;
+    }
+	public void setAlarmingUpperRate(double alarmingUpperRate) {
+    	this.alarmingUpperRate = alarmingUpperRate;
+    }
+	public double getAlarmingLowerRate() {
+    	return alarmingLowerRate;
+    }
+	public void setAlarmingLowerRate(double alarmingLowerRate) {
+    	this.alarmingLowerRate = alarmingLowerRate;
+    }
+	public double getScaleDownFactor() {
+    	return scaleDownFactor;
+    }
+	public void setScaleDownFactor(double scaleDownFactor) {
+    	this.scaleDownFactor = scaleDownFactor;
+    }
+	
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomainManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomainManager.java b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomainManager.java
new file mode 100644
index 0000000..cdabfe0
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.messages/2.1.1/src/main/java/org/wso2/carbon/cartridge/messages/ClusterDomainManager.java
@@ -0,0 +1,34 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.cartridge.messages;
+
+/**
+ * TODO: class description
+ */
+public interface ClusterDomainManager {
+
+    void addClusterDomain(ClusterDomain clusterDomain);
+    
+    /**
+     * This will remove the corresponding ServiceConfiguration.
+     * @param domain
+     * @param subDomain
+     * @param hostName
+     */
+    void removeClusterDomain(String domain, String subDomain, String hostName);
+}


[10/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/jquery.min.js
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/jquery.min.js b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/jquery.min.js
new file mode 100644
index 0000000..8f3ca2e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.google.analytics.ui/2.1.0/src/main/resources/web.googleanalytics/js/jquery.min.js
@@ -0,0 +1,167 @@
+/*!
+ * jQuery JavaScript Library v1.4.4
+ * http://jquery.com/
+ *
+ * Copyright 2010, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2010, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Thu Nov 11 19:04:53 2010 -0500
+ */
+(function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h=
+h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"||
+h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La,
+"`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,
+e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,
+"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+
+a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,
+C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j,
+s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,
+j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length},
+toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j===
+-1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false;
+if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--;
+if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload",
+b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&&
+!F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&&
+l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z],
+z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j,
+s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v=
+s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)||
+[];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u,
+false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"),
+k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false,
+scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent=
+false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom=
+1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display=
+"none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h=
+c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);
+else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this,
+a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=
+c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,
+a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",
+colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===
+1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "),
+l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,
+"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";
+if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r=
+a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},
+attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&
+b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0};
+c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,
+arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid=
+d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+
+c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b=
+w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===
+8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k===
+"click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+
+d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
+d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this,
+Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=
+c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U};
+var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!==
+"form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V,
+xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired=
+B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type===
+"file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]===
+0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d,
+a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d=
+1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d===
+"object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}});
+c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
+(function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i,
+[y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3];
+break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr,
+q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h=
+l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*"));
+return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!==
+B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
+POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()===
+i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=
+i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g,
+"")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n,
+m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===
+true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===
+g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]-
+0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n===
+"first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===
+i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]];
+if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m,
+g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1;
+for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"),
+i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g);
+n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&&
+function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F||
+p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g=
+t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition?
+function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML;
+c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},
+not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h=
+h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):
+c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,
+2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,
+b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&
+e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1,
+"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
+c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
+wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
+prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
+this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
+return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null;
+else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=
+c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a,
+b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):
+this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",
+prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument||
+b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length-
+1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));
+d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i,
+jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,
+zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),
+h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b);
+if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=
+d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left;
+e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b===
+"object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&
+!this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})},
+getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html",
+script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data||
+!T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache=
+false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset;
+A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type",
+b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&&
+c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d||
+c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]=
+encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",
+[b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),
+e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});
+if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",
+3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",
+d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,
+d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)===
+"inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L||
+1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b,
+d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a*
+Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)}
+var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;
+this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide||
+this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=
+c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===
+b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&&
+h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle;
+for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+=
+parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",
+height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells=
+f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a,
+"marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a,
+e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&&
+c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();
+c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+
+b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/pom.xml
new file mode 100644
index 0000000..9e855ce
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/pom.xml
@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.keystore.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Keystore Generation and Management</name>
+
+    <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>
+                        <Private-Package>
+                            org.wso2.carbon.keystore.mgt.internal                            
+                        </Private-Package>
+                        <Export-Package>
+                            !org.wso2.carbon.keystore.mgt.internal,
+                            org.wso2.carbon.keystore.mgt.*,
+                        </Export-Package>
+                        <Import-Package>
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.wso2.carbon.security.*,
+                            org.apache.lucene.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Embed-Dependency>
+                            bcprov-jdk15|naming-factory|naming-resources|commons-collections;scope=compile|runtime;inline=false
+                        </Embed-Dependency>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+	<dependency>
+            <groupId>commons-codec.wso2</groupId>
+            <artifactId>commons-codec</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.equinox</groupId>
+            <artifactId>javax.servlet</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+            <artifactId>axiom</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>bouncycastle</groupId>
+            <artifactId>bcprov-jdk15</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.security.mgt</artifactId>
+        </dependency>
+    </dependencies>
+
+</project>


[24/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp
new file mode 100644
index 0000000..d0cc589
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp
@@ -0,0 +1,196 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.billing.mgt.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="adjustment.menu"
+            resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+    <script type="text/javascript">
+
+        function findInvoices(){
+            document.getElementById("invoiceDetailTable").style.display="none";
+            var tenantDomain = document.getElementById('tenantDomain').value;
+            if(tenantDomain=="" || tenantDomain==null){
+                CARBON.showErrorDialog("Please enter a tenant domain");
+            }else{
+                jQuery.ajax({
+                    type: 'GET',
+                    url: '../tenant-billing/find_invoices_ajaxprocessor.jsp',
+                    data: 'tenantDomain=' + tenantDomain,
+                    dataType: 'json',
+                    async: false,
+                    success: function(msg) {
+                        var invoiceList = document.getElementById('invoices');
+                        clearOptions(invoiceList);
+                        var invoices = msg.invoices;
+                        for(i=0; i < invoices.length; i++){
+                            addToOptionList(invoiceList, invoices[i].invoiceId, invoices[i].invoiceDate);
+                        }
+                        if(invoices.length>0){
+                            document.getElementById("invoiceDetailTable").style.display="";
+                        }else{
+                            CARBON.showInfoDialog("There are no invoices for this tenant");
+                        }
+                    },
+                    error:function (xhr) {
+                        CARBON.showErrorDialog('Could not get the invoices of tenant: ' + tenantDomain );
+                    }
+                });
+            }
+
+        }
+
+        function makeAdjustment(){
+            var invoiceList = document.getElementById('invoices');
+            var invoiceId = invoiceList.options[invoiceList.selectedIndex].value;
+            if(invoiceId>0){
+                document.adjustmentForm.invoiceId.value = invoiceId;
+            }else{
+                CARBON.showErrorDialog("Please select an invoice");
+                return;
+            }
+
+            var amount = document.getElementById("amount").value;
+            amount = $.trim(amount);
+            if(amount==null || amount==""){
+                CARBON.showErrorDialog("Please enter an amount to be adjusted");
+                return;
+            }
+            var description = document.getElementById("description").value;
+            if(description==null || description==""){
+                CARBON.showErrorDialog("Please enter a description for the adjustment");
+                return;
+            }
+
+            document.adjustmentForm.submit();
+
+
+        }
+
+        function clearOptions(OptionList) {
+
+            // Always clear an option list from the last entry to the first
+            for (x = OptionList.length; x >= 0; x = x - 1) {
+                OptionList[x] = null;
+            }
+        }
+
+        function addToOptionList(OptionList, OptionValue, OptionText) {
+            // Add option to the bottom of the list
+            OptionList[OptionList.length] = new Option(OptionText, OptionValue);
+        }
+
+        function cancel(){
+            location.href = "adjustments.jsp";
+        }
+    </script>
+
+    <%
+        String adjustmentIdStr=null;
+        if(session.getAttribute("adjustmentId")!=null){
+            adjustmentIdStr = String.valueOf(session.getAttribute("adjustmentId"));
+            session.removeAttribute("adjustmentId");
+        }
+
+        if(adjustmentIdStr!=null && !"".equals(adjustmentIdStr)){
+            int adjustmentId = Integer.parseInt(adjustmentIdStr);
+            if(adjustmentId>0){
+    %>
+    <script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showInfoDialog("Adjustment was made successfully");
+        });
+    </script>
+    <%
+    }else{
+    %>
+    <script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showErrorDialog("An error occurred while making the adjustment");
+        });
+    </script>
+    <%
+            }
+
+        }
+    %>
+
+    <div id="middle">
+        <h2><fmt:message key="invoice.adjustments"/></h2>
+        <div id="workArea">
+            <form name="adjustmentForm" action="make_adjustment_ajaxprocessor.jsp" method="post">
+                <input type="hidden" name="invoiceId" id="invoiceId" />
+                <table class="styledLeft" cellspacing="0">
+                    <thead>
+                    <tr>
+                        <th colspan="3"><fmt:message key="find.invoices"/></th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="enter.tenant.domain"/></td>
+                        <td colspan="2"><input type="text" name="tenantDomain" id="tenantDomain"
+                                               style="width:300px"/>
+                            <input type="button" onclick="javascript:findInvoices();" value="<fmt:message key="find.invoices"/>"/>
+                        </td>
+                    </tr>
+                    <tr><td colspan="3"></td></tr>
+                    </tbody>
+                </table>
+
+                <table id="invoiceDetailTable" class="styledLeft" cellspacing="0" style="display: none">
+                    <thead>
+                    <tr>
+                        <th colspan="3"><fmt:message key="adjustment.information"/></th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="select.invoice"/></td>
+                        <td colspan="2"><select id="invoices"></select></td>
+                    </tr>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="amount"/></td>
+                        <td colspan="2"><input type="text" name="amount" id="amount"></td>
+                    </tr>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="description"/></td>
+                        <td colspan="2"><input type="text" name="description" id="description"></td>
+                    </tr>
+                    <tr>
+                        <td colspan="3">
+                            <input type="button" class="button" value="<fmt:message key="submit"/>" onclick="makeAdjustment();">
+                            <input type="button" class="button" value="<fmt:message key="cancel"/>" onclick="cancel();">
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </div>
+    </div>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs
new file mode 100644
index 0000000..2ebbe74
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs
@@ -0,0 +1,7 @@
+td.packageCol {
+    border-bottom: 1 solid #CCC !important;
+}
+
+div#exp {
+    color: #0f0;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css
new file mode 100644
index 0000000..62e0509
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css
@@ -0,0 +1,58 @@
+/*td.packageCol {
+    border-bottom: 1 solid #CCC !important;
+}
+
+div#exp {
+    color: #0f0;
+}*/
+.invoice-header td{
+    background-color:#e7e7e7;
+    font-weight:bold;
+}
+.invoiceTable{
+    border-collapse:collapse;
+}
+.invice-data-table{
+    border-collapse:collapse;
+    border-top:solid 1px #e7e7e7;
+    border-right:solid 1px #e7e7e7;
+    width:100%;
+}
+.invice-data-table tr.invoice-content-row td{
+    border-bottom:solid 1px #e7e7e7;
+    border-left:solid 1px #e7e7e7;
+}
+.invoiceTable tr td{
+    padding:5px !important;    
+}
+.name-field{
+    font-weight:bold;
+}
+.invoice-heading{
+    text-transform:uppercase;
+    font-size:30px;
+    font-weight:bold;
+    line-height:40px;
+}
+.invoice-sub-heading{
+    text-transform:uppercase;
+    font-size:20px;
+    font-weight:bold;
+    line-height:40px;    
+}
+ul.invoice-inside-listing{
+    margin-top:10px;
+}
+ul.invoice-inside-listing li{
+    height:25px;
+    letter-spacing:1.2px;
+}
+.terms-section-header{
+    font-weight:bold;
+}
+.terms-section{
+    width:200px;
+    text-align:justify;
+    color: #666666;
+    margin-left:20px;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp
new file mode 100644
index 0000000..b3ab062
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp
@@ -0,0 +1,182 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.billing.mgt.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="adjustment.menu"
+            resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+    <script type="text/javascript">
+
+        function submitDiscountForm(){
+            var tenantDomain = document.getElementById("tenantDomain").value;
+            if(tenantDomain==null || tenantDomain==""){
+                CARBON.showErrorDialog("Please provide a tenant domain.");
+                return;
+            }
+
+            var discountType = document.getElementById("discountType").value;
+            var discountRadio = document.discountForm.discountTypeRadio;
+            for(var i=0; i<discountRadio.length; i++){
+                if(discountRadio[i].checked){
+                    discountType = discountRadio[i].value;
+                    break;
+                }
+            }
+            //if the hidden variable is not set properly, we should set it
+            //just making sure it is set..
+            document.getElementById("discountType").value = discountType;
+
+            if(discountType=="percentage"){
+                var percentage = document.getElementById("percentage").value;
+                if(percentage==null || percentage==""){
+                    CARBON.showErrorDialog("Please enter a valid discount percentage.");
+                    return;
+                }
+            }else if(discountType=="amount"){
+                var amount = document.getElementById("amount").value;
+                if(amount==null || amount==""){
+                    CARBON.showErrorDialog("Please enter a valid discount amount.");
+                    return;
+                }
+            }
+
+            var startDate = document.getElementById("startDate").value;
+            if(startDate==null || startDate==""){
+                CARBON.showErrorDialog("Please enter a valid start date.");
+                return;
+            }
+
+            var endDate = document.getElementById("endDate").value;
+            if(endDate==null || endDate==""){
+                CARBON.showErrorDialog("Please enter a valid end date.");
+                return;
+            }
+
+            document.discountForm.submit();
+        }
+
+        function manageDiscountTypeRow(discountType){
+            document.discountForm.discountType.value = discountType;
+
+            if(discountType=="percentage"){
+                document.getElementById("percentageRow").style.display="";
+                document.getElementById("amountRow").style.display="none";
+            }else if(discountType=="amount"){
+                document.getElementById("percentageRow").style.display="none";
+                document.getElementById("amountRow").style.display="";
+            }else{
+                //do nothing
+            }
+        }
+
+        function cancel(){
+            location.href = "discounts.jsp";
+        }
+    </script>
+
+    <%
+        String discountAdded = null;
+        if(session.getAttribute("discountAdded")!=null){
+            discountAdded = String.valueOf(session.getAttribute("discountAdded"));
+            session.removeAttribute("discountAdded");
+        }
+
+        if(discountAdded!=null){
+            if("true".equals(discountAdded)){
+
+    %>
+    <script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showInfoDialog("Discount was added successfully");
+        });
+    </script>
+    <%
+    }else{
+    %>
+    <script type="text/javascript">
+        jQuery(document).ready(function() {
+            CARBON.showErrorDialog("An error occurred while adding the discount");
+        });
+    </script>
+    <%
+            }
+
+        }
+    %>
+
+    <div id="middle">
+        <h2><fmt:message key="discounts"/></h2>
+        <div id="workArea">
+            <form name="discountForm" action="add_discount_ajaxprocessor.jsp" method="post">
+                <input type="hidden" name="discountType" id="discountType"/>
+                <table class="styledLeft" cellspacing="0">
+                    <thead>
+                    <tr>
+                        <th colspan="3"><fmt:message key="discounts.table.title"/></th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="tenant.domain"/></td>
+                        <td colspan="2"><input type="text" name="tenantDomain" id="tenantDomain"></td>
+                    </tr>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="discount.type"/></td>
+                        <td colspan="2">
+                            <input type="radio" name="discountTypeRadio" value="percentage" checked onclick="manageDiscountTypeRow(this.value);" ><fmt:message key="type.percentage"/>
+                            <input type="radio" name="discountTypeRadio" value="amount" onclick="manageDiscountTypeRow(this.value);" ><fmt:message key="type.amount"/>
+                        </td>
+                    </tr>
+                    <tr id="percentageRow">
+                        <td style="width:180px"><fmt:message key="discount.percentage"/></td>
+                        <td colspan="2"><input type="text" name="percentage" id="percentage"></td>
+                    </tr>
+                    <tr id="amountRow" style="display: none;">
+                        <td style="width:180px"><fmt:message key="amount"/></td>
+                        <td colspan="2"><input type="text" name="amount" id="amount"></td>
+                    </tr>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="discount.start.date"/></td>
+                        <td colspan="2"><input type="text" name="startDate" id="startDate"></td>
+                    </tr>
+                    <tr>
+                        <td style="width:180px"><fmt:message key="discount.end.date"/></td>
+                        <td colspan="2"><input type="text" name="endDate" id="endDate"></td>
+                    </tr>
+                    <tr>
+                        <td colspan="3">
+                            <input type="button" class="button" value="<fmt:message key="submit"/>" onclick="submitDiscountForm();">
+                            <input type="button" class="button" value="<fmt:message key="cancel"/>" onclick="cancel();">
+                        </td>
+                    </tr>
+                    </tbody>
+                </table>
+            </form>
+        </div>
+    </div>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png
new file mode 100644
index 0000000..fc710f8
Binary files /dev/null and b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png
new file mode 100644
index 0000000..333254b
Binary files /dev/null and b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png
new file mode 100644
index 0000000..0c9ff59
Binary files /dev/null and b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html
new file mode 100644
index 0000000..c790c9f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html
@@ -0,0 +1,75 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+    <title>Billing and Metering - User Guide</title>
+    <link href="../../admin/css/documentation.css" rel="stylesheet" type="text/css" media="all"/>
+</head>
+
+<body>
+<h1>Billing and Metering</h1>
+
+
+<p>
+    You can check charges for your subscription and payments you have made through Billing & Metering component. Invoice
+    data can be viewed in two ways.
+</p>
+
+<ol>
+    <li>View Invoice</li>
+    <li>Interim Invoice</li>
+</ol>
+
+<p>
+    <img src="images/billing.png" alt="Billing and Metering"/>
+
+<div><strong>Figure1: Billing and Metering</strong></div>
+</p>
+
+<h2>View Invoice</h2>
+
+
+<p style="text-align: left;">
+
+    In 'View Invoice' page, you can view invoices generated at each billing cycle. Online payments are available through
+    Paypal if you are a Paypal account holder.
+    For doing payments in a secure manner with Paypal click the Paypal button at the bottom of the invoice.
+</p>
+
+<p>
+    <img src="images/paypal.png" alt="Payments through Paypal"/>
+
+    <div><strong>Figure2: Payments through Paypal</strong></div>
+
+</p>
+
+<h2>Interim Invoice</h2>
+
+
+<p style="text-align: left;">
+
+Interim invoice shows your current state of billing.
+This includes the amount brought forward and the amount accumulated for the period starting from last date on which bill is being generated to the current date.
+
+</p>
+
+
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp
new file mode 100644
index 0000000..0b59e37
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp
@@ -0,0 +1,47 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@ page contentType="text/html" pageEncoding="UTF-8"%>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.BillingPeriod" %>
+<%@ page import="org.json.JSONArray" %>
+<%@ page import="org.json.JSONObject" %>
+<%
+    String tenantDomain = request.getParameter("tenantDomain");
+    BillingPeriod[] billingPeriods = BillingUtil.getAvailableBillingPeriodsBySuperTenant(config, session, tenantDomain);
+
+    try{
+        JSONArray invoiceArray = new JSONArray();
+
+        if(billingPeriods!=null && billingPeriods.length>0){
+            for(BillingPeriod bp : billingPeriods){
+
+                JSONObject obj = new JSONObject();
+                obj.put("invoiceId", bp.getInvoiceId());
+                obj.put("invoiceDate", bp.getInvoiceDate().toString());
+
+                invoiceArray.put(obj);
+            }
+        }
+
+        JSONObject invoicesObj = new JSONObject();
+        invoicesObj.put("invoices", invoiceArray);
+        out.write(invoicesObj.toString());
+    }catch(Exception e){
+        e.printStackTrace();
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/get_invoice_by_id_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/get_invoice_by_id_ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/get_invoice_by_id_ajaxprocessor.jsp
new file mode 100644
index 0000000..8e6d721
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/get_invoice_by_id_ajaxprocessor.jsp
@@ -0,0 +1,25 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.MultitenancyInvoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%
+    int invoiceId = Integer.parseInt(request.getParameter("invoiceId"));
+    MultitenancyInvoice invoice = BillingUtil.getPastInvoice(config, session, invoiceId);
+
+    session.setAttribute("invoice", invoice);
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png
new file mode 100644
index 0000000..f21abdb
Binary files /dev/null and b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif
new file mode 100644
index 0000000..47ca2fd
Binary files /dev/null and b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp
new file mode 100644
index 0000000..12dda0d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp
@@ -0,0 +1,355 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.*" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="java.util.Enumeration" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+
+<carbon:jsi18n
+		resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.JSResources"
+		request="<%=request%>" />
+
+
+
+<fmt:bundle basename="org.wso2.carbon.billing.mgt.ui.i18n.Resources">
+<carbon:breadcrumb
+            label="view.invoice.menu"
+            resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>" />
+
+
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="js/register_config.js"></script>
+<link href="../tenant-billing/css/billing.css" rel="stylesheet" type="text/css" media="all"/>
+<style>
+    h2.trigger{
+    -moz-box-shadow:none;
+    box-shadow:none;
+    }
+    .toggle_container {
+    -moz-box-shadow:none;
+    box-shadow:none;
+}
+</style>
+<script type="text/javascript">
+    jQuery(document).ready(function() {
+
+      jQuery(".toggle_container").show();
+      /*Hide (Collapse) the toggle containers on load use show() insted of hide() in the
+      above code if you want to keep the content section expanded. */
+
+      jQuery("h2.trigger").click(function() {
+          if (jQuery(this).next().is(":visible")) {
+              this.className = "active trigger";
+          } else {
+              this.className = "trigger";
+          }
+
+          jQuery(this).next().slideToggle("fast");
+          return false; //Prevent the browser jump to the link anchor
+      });
+  });
+</script>
+<%
+    MultitenancyInvoice invoice = BillingUtil.getCurrentInvoice(config, session);
+
+    if (invoice == null) {
+
+%>
+<div id="middle">
+
+    <h2><fmt:message key="interim.invoice"/></h2>
+    <div id="workArea">
+
+
+        <table class="styledLeft">
+		<thead>
+		<tr>
+		<th>
+			<fmt:message key="invoice.information.head"/>
+		</th>
+		</tr>
+		</thead>
+        <tbody>
+                 <tr class="packagerow">
+                    <td class="packageCol">
+                        <fmt:message key="no.invoice.information.details"/>
+                    </td>
+                </tr>
+        </tbody>
+        </table>
+    </div>
+</div>
+<%
+    }else{
+        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+            SimpleDateFormat titleDateFormat = new SimpleDateFormat("MMM yyyy");
+            int invoiceId = invoice.getInvoiceId();
+            Date billingDate = invoice.getBillingDate();
+            Date startDate = invoice.getStartDate();
+            Date endDate = invoice.getEndDate();
+            String broughtForward = invoice.getBoughtForward();
+            String carriedForward = invoice.getCarriedForward();
+            String totalPayments = invoice.getTotalPayments();
+            String totalCost = invoice.getTotalCost();
+            boolean lastInvoice = invoice.getLastInvoice();
+            MultitenancySubscription[] subscriptions = invoice.getSubscriptions();
+            MultitenancyPurchaseOrder[] purchaseOrders = invoice.getPurchaseOrders();
+%>
+<div id="middle">
+        <h2><fmt:message key="interim.invoice"/></h2>
+
+        <div id="workArea">
+
+    <div style="border:solid 1px #ccc;margin-top:20px;padding:15px !important">
+            <table style="width:600px;" class="invoiceTable">
+                <tr>
+                    <td>
+                        <img alt="WSO2" src="images/logo.png" align="top" style="display:block;"/>
+                        <div style="margin-top:10px;">Federal Tax ID 87-0750575</div>
+
+                    </td>
+                    <td>
+                        <div class="invoice-heading"> Interim Invoice</div>
+                        <!--<div class="invoice-sub-heading">for xxxy</div>
+                        <div class="invoice-sub-heading">INVOICE NO: xxxxx</div>-->
+
+                    </td>
+                </tr>
+                <tr>
+                    <td> <ul class="invoice-inside-listing">
+                            <li>4131, El Camino Real Suite 200,
+                            </li>
+                            <li>Palo Alto, CA 94306
+                            </li>
+                            <li>Tel: (408) 754 7388
+                            </li>
+                            <li>Fax: (408) 689 4328
+                            </li>
+                            <li>Email: billing@wso2.com
+                            </li>
+                        </ul>
+					</td>
+                    <td>
+                   
+                
+<!--                         <ul class="invoice-inside-listing"> -->
+<%--                             <li><fmt:message key="invoice.date"/>: <%=dateFormat.format(billingDate)%></li> --%>
+<%--                             <li><fmt:message key="start.date"/>: <%=dateFormat.format(startDate)%></li> --%>
+<%--                             <li><fmt:message key="end.date"/>: <%=dateFormat.format(endDate)%></li> --%>
+<!--                          </ul> -->
+                         <table border="0" class="normal">
+								<tr> <td><fmt:message key="invoice.date"/> </td>
+								     <td>: <%=dateFormat.format(billingDate)%></td>
+								</tr>
+									<tr> <td><fmt:message key="start.date"/> </td>
+								     <td>: <%=dateFormat.format(startDate)%></td>
+								</tr>
+									<tr> <td><fmt:message key="end.date"/></td>
+								     <td>: <%=dateFormat.format(endDate)%></td>
+								</tr>
+						</table>
+                    </td>
+                </tr>
+                <tr>
+                    <td colspan="2">
+                        
+                        <table class="invice-data-table">
+                        <tr class="invoice-header">
+                                <td>Particulars</td>
+                                <td style="text-align:right">Value (USD)</td>
+                            </tr>
+           <tr class="invoice-content-row">
+                	<td colspan="2"><strong style="color:#555"><fmt:message key="charges.subscriptions"/></strong></td>
+                </tr>
+                <%
+                    if(subscriptions!=null){
+                    for (MultitenancySubscription subscription: subscriptions) {
+
+                        String subscribedPackage = subscription.getSubscribedPackage();
+                        BilledEntry[] billedEntries = subscription.getBilledEntries();
+                        Date activeSince = subscription.getActiveSince();
+                        Date activeUntil = subscription.getActiveUntil();
+                %>
+                <!--<tr class="invoice-content-row">
+                    <td class="leftCol-med" colspan="2"></td>
+                </tr>-->
+                <tr class="invoice-content-row">
+                    <td class="leftCol-med" style="padding-top:20px !important" colspan="2">
+                        <fmt:message key="subscription"/> Type: <strong><%=subscribedPackage%></strong>
+                    </td>
+                </tr>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.since"/>: <%=dateFormat.format(activeSince)%>
+                    </td>
+                </tr>
+                <%
+                    if(subscription.getActive()){
+                %>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.until"/>: <fmt:message key="this.is.active.subscription"/>
+                    </td>
+                </tr>
+                <%
+                    }
+                    else{
+                %>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.until"/>: <%=dateFormat.format(activeUntil)%>
+                    </td>
+                </tr>
+                <%
+                    }
+                %>
+
+                <%
+                    if(billedEntries!=null && billedEntries.length>0){
+                       for (BilledEntry billedEntry: billedEntries) {
+                           if(billedEntry!=null){
+                            String name = billedEntry.getName();
+                            String cost = billedEntry.getCost();
+                %>
+                <tr class="invoice-content-row">
+                    <td>
+                        <%=name%>
+                    </td>
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=cost%>
+                    </td>
+                </tr>
+                <%
+                                    }
+                                }
+                            }
+                        }
+                    }
+                %>
+                	<tr class="invoice-content-row">
+                		<td colspan="2" style="padding-top:20px !important"><strong style="color:#555"><fmt:message key="payment.details"/></strong></td>
+                	</tr>
+                <%
+                if (purchaseOrders == null || purchaseOrders.length == 0) {
+                %>
+                 
+                 <tr class="invoice-content-row">
+                		<td colspan="2">You don't have any payment details for this period.</td></tr>                 
+                <%
+                } else {
+                    for (MultitenancyPurchaseOrder purchaseOrder: purchaseOrders) {
+                        if (purchaseOrder == null) {
+                            continue;
+                        }
+                        int id = purchaseOrder.getId();
+                        Date paymentDate = purchaseOrder.getPaymentDate();
+                        String payment = purchaseOrder.getPayment();
+                %>
+				<tr class="invoice-content-row">
+				<td class="leftCol-med"><fmt:message key="payment"/> : <strong><%=purchaseOrder.getTransactionId()%></strong> on <%=dateFormat.format(paymentDate)%></td>
+				<td style="text-align:right;font-weight:bold;"><%=payment%></td>
+				</tr>
+                
+                <%
+                    }
+                }
+                %>
+				<tr class="invoice-content-row"><td colspan="2" style="padding-top:20px !important"><strong style="color:#555"><fmt:message key="invoice.summary"/></strong></td></tr>
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="brought.forward"/>
+                    </td>
+                
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=broughtForward%>
+                    </td>
+                </tr>
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="total.cost"/>
+                    </td>
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=totalCost%>
+                    </td>
+                </tr>
+
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="total.payments"/>
+                    </td>
+
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=totalPayments%>
+                    </td>
+                </tr>
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="carried.forward"/>
+                    </td>
+
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=carriedForward%>
+                    </td>
+                </tr>
+                <tr class="invoice-content-row">
+                    <td colspan="2" id="messageTd">&nbsp;</td>
+                </tr>
+                </table>
+                </td>
+                </tr>
+                
+                <!--<tr>
+                    <td colspan="2">
+                        <div class="name-field">Padmika Dissanaike,</div>
+                        Director- Finance
+                    </td>
+                </tr>-->
+            </table>
+            <!--<div style="background-color:#e2edf9;padding:10px;">
+		    <form name="startPaymentForm" method='POST'>
+                            <input type="hidden" name="successUrl" id="successUrl" value=""/>
+                            <input type="hidden" name="cancelUrl" id="cancelUrl" value=""/>
+                            <input type="hidden" name="amount" id="amount" value=""/>
+                            <a href="#"><img src='http://images.paypal.com/images/x-click-but6.gif'
+                                    border='0' align='top' alt='PayPal' onclick="setExpressCheckout('');"/>
+                            </a>
+                        </form>
+                        <div style="color:#494949">Pay the invoice securely online</div>
+                        </div>
+                        </div>-->
+             <%
+        		}
+    		%>
+    		
+        </div>
+</div>
+
+ </fmt:bundle>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp
new file mode 100644
index 0000000..f33576c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp
@@ -0,0 +1,49 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.MultitenancyInvoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Cash" %>
+<%@ page import="java.util.Date" %>
+<%
+    int invoiceId = Integer.parseInt(request.getParameter("invoiceId"));
+    String amount = request.getParameter("amount").trim();
+    String description = request.getParameter("description").trim();
+
+    //We are making the adjustment as a payment...
+    Payment adjustment = new Payment();
+    Invoice invoice = new Invoice();
+    invoice.setId(invoiceId);
+    adjustment.setInvoice(invoice);
+    adjustment.setDescription(description);
+    adjustment.setDate(new Date(System.currentTimeMillis()));
+
+    int adjustmentId=0;
+    try{
+        adjustmentId = BillingUtil.makeAdjustment(config, session, adjustment,  amount);
+    }catch(Exception e){
+        e.printStackTrace();
+    }
+
+    session.setAttribute("adjustmentId", adjustmentId);
+
+
+%>
+
+<jsp:forward page="adjustments.jsp"/>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp
new file mode 100644
index 0000000..67bf09a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp
@@ -0,0 +1,470 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.*" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="org.wso2.carbon.stratos.common.util.CommonUtil" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="java.util.Enumeration" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+
+<carbon:jsi18n
+		resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.JSResources"
+		request="<%=request%>" />
+
+
+
+<fmt:bundle basename="org.wso2.carbon.billing.mgt.ui.i18n.Resources">
+<carbon:breadcrumb
+            label="view.invoice.menu"
+            resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>" />
+
+<script type="text/javascript">
+
+    function setExpressCheckout(paypalUrl) {
+        var successUrl = document.startPaymentForm.successUrl.value;
+        var cancelUrl = document.startPaymentForm.cancelUrl.value;
+        var amount = document.startPaymentForm.amount.value;
+	    if(amount=='$0.00'){
+            CARBON.showInfoDialog('Your total payment is '+amount+'. You are not allowed to connect to Paypal');
+        }else{
+            document.getElementById('messageTd').style.display='';
+            jQuery.ajax({
+            type: 'GET',
+            url: '../payment/setEC-ajaxprocessor.jsp',
+            data: 'successUrl=' + successUrl + '&cancelUrl=' + cancelUrl + '&amount=' + amount,
+            dataType: 'json',
+            async: false,
+            success: function(msg) {
+                var resp = msg;
+                if(resp.ack=='Success'){
+                    location.href = paypalUrl + resp.token;
+                }else{
+                    if(resp.error){
+                        CARBON.showErrorDialog('Could not connect to Paypal at the moment: ' + resp.error);
+                    }else{
+                        CARBON.showErrorDialog('Could not connect to Paypal at the moment');
+                    }
+                    document.getElementById('messageTd').style.display='none';
+                }
+            },
+            error:function () {
+                CARBON.showErrorDialog('Could not connect to PayPal site at the moment' );
+                document.getElementById('messageTd').style.display='none';
+            }
+            });
+	    }
+    }
+
+    function getInvoice(){
+
+        var index = document.getElementById('yearMonth').selectedIndex;
+        var invoiceId = document.getElementById('yearMonth').options[index].value;
+        if(invoiceId<0){
+            CARBON.showInfoDialog('Please select a month to view the invoice');
+        }else{
+            jQuery.ajax({
+                type: 'POST',
+                url: 'get_invoice_by_id_ajaxprocessor.jsp',
+                data: 'invoiceId=' + invoiceId,
+                success: function() {
+                    location.href = 'past_invoice.jsp'
+                },
+                error:function (xhr, ajaxOptions, thrownError) {
+                    CARBON.showErrorDialog('Could not get the invoice.');
+                }
+            });    
+        }
+
+
+        
+    }
+</script>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+<script type="text/javascript" src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript" src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<script type="text/javascript" src="js/register_config.js"></script>
+<link href="../tenant-billing/css/billing.css" rel="stylesheet" type="text/css" media="all"/>
+<style>
+    h2.trigger{
+    -moz-box-shadow:none;
+    box-shadow:none;
+    }
+    .toggle_container {
+    -moz-box-shadow:none;
+    box-shadow:none;
+}
+</style>
+<script type="text/javascript">
+    jQuery(document).ready(function() {
+
+      jQuery(".toggle_container").show();
+      /*Hide (Collapse) the toggle containers on load use show() insted of hide() in the
+      above code if you want to keep the content section expanded. */
+
+      jQuery("h2.trigger").click(function() {
+          if (jQuery(this).next().is(":visible")) {
+              this.className = "active trigger";
+          } else {
+              this.className = "trigger";
+          }
+
+          jQuery(this).next().slideToggle("fast");
+          return false; //Prevent the browser jump to the link anchor
+      });
+  });
+</script>
+<%
+    String paypalUrl = "";
+    if(CommonUtil.getStratosConfig()!=null){
+        paypalUrl = CommonUtil.getStratosConfig().getPaypalUrl();
+    }
+
+    String adminConsoleURL = CarbonUIUtil.getAdminConsoleURL(request);
+    adminConsoleURL = adminConsoleURL.substring(0, adminConsoleURL.indexOf("carbon"));
+    String tenantDomain = (String) session.getAttribute("tenantDomain");
+    String successUrl = adminConsoleURL + "t/" + tenantDomain + "/carbon/payment/success.jsp";
+    String cancelUrl = adminConsoleURL + "t/" + tenantDomain + "/carbon/tenant-billing/past_invoice.jsp";
+
+    BillingPeriod[] billingPeriods = BillingUtil.getAvailableBillingPeriods(config, session);
+    String[] billingMonths = BillingUtil.getAvailableBillingMonths(billingPeriods);
+
+    //invoice is retrieved at get_invoice_by_id_ajaxprocessor.jsp and it is added to session
+    MultitenancyInvoice invoice = (MultitenancyInvoice) session.getAttribute("invoice");
+    session.removeAttribute("invoice");
+    session.removeAttribute("invoiceId");
+    if(invoice!=null){
+        session.setAttribute("invoiceId", invoice.getInvoiceId());
+    }
+
+%>
+<div id="middle">
+        <h2><fmt:message key="view.invoice"/></h2>
+
+        <div id="workArea">
+            <%
+                if(billingMonths.length>0){
+            %>
+            <table class="styledLeft">
+				<thead>
+				<tr>
+				<th colspan="3" width="100%">
+					<fmt:message key="select.invoice"/>
+				</th>
+				</tr>
+				</thead>
+				<tbody>
+				         <tr class="packagerow">
+				            <td class="packageCol" width="20%">
+				                <fmt:message key="invoice"/>
+				            </td>
+				            <td colspan="2">
+				                <select name="yearMonth" id="yearMonth">
+				                    <option value="-1">--Select the Invoice--</option>
+				                    <%
+				                        for(int i=0; i< billingMonths.length; i++){
+				                    %>
+				                    <option value="<%=billingPeriods[i].getInvoiceId()%>"><%=billingMonths[i]%></option>
+				                    <%
+				                        }
+				                    %>
+				                </select>
+				                <input type="button" class="button" value="View Invoice" onclick="getInvoice();"/>
+				            </td>
+				        </tr>
+				</tbody>
+			</table>
+            <%
+                    }else{
+            %>
+                <table class="styledLeft">
+                    <thead>
+                        <tr>
+                            <th>
+                                <fmt:message key="invoice.information.head"/>
+                            </th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        <tr class="packagerow">
+                            <td class="packageCol">
+                                <fmt:message key="no.invoice.at.the.moment"/>
+                            </td>
+                        </tr>
+                    </tbody>
+                </table>
+            <%
+                    }
+            %>
+
+			
+			 <%
+        if(invoice!=null){
+            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+            SimpleDateFormat titleDateFormat = new SimpleDateFormat("MMM yyyy");
+            int invoiceId = invoice.getInvoiceId();
+            Date billingDate = invoice.getBillingDate();
+            Date startDate = invoice.getStartDate();
+            Date endDate = invoice.getEndDate();
+            String broughtForward = invoice.getBoughtForward();
+            String carriedForward = invoice.getCarriedForward();
+            String totalPayments = invoice.getTotalPayments();
+            String totalCost = invoice.getTotalCost();
+            boolean lastInvoice = invoice.getLastInvoice();
+            MultitenancySubscription[] subscriptions = invoice.getSubscriptions();
+            MultitenancyPurchaseOrder[] purchaseOrders = invoice.getPurchaseOrders();
+
+    %>
+    <div style="border:solid 1px #ccc;margin-top:20px;padding:15px !important">
+            <table style="width:600px;" class="invoiceTable">
+                <tr>
+                    <td>
+                        <img alt="WSO2" src="images/logo.png" align="top" style="display:block;"/>
+                        <div style="margin-top:10px;">Federal Tax ID 87-0750575</div>
+
+                    </td>
+                    <td>
+                        <div class="invoice-heading">Invoice</div>
+                        <div class="invoice-sub-heading"><%=titleDateFormat.format(billingDate)%></div>
+                        <div class="invoice-sub-heading">INVOICE NO: <%=invoiceId%></div>
+
+                    </td>
+                </tr>
+                <tr>
+                    <td> <ul class="invoice-inside-listing">
+                            <li>4131, El Camino Real Suite 200,
+                            </li>
+                            <li>Palo Alto, CA 94306
+                            </li>
+                            <li>Tel: (408) 754 7388
+                            </li>
+                            <li>Fax: (408) 689 4328
+                            </li>
+                            <li>Email: billing@wso2.com
+                            </li>
+                        </ul>
+					</td>
+                    <td>
+                   
+                
+<!--                         <ul class="invoice-inside-listing"> -->
+<%--                             <li><fmt:message key="invoice.date"/>: <%=dateFormat.format(billingDate)%></li> --%>
+<%--                             <li><fmt:message key="start.date"/>: <%=dateFormat.format(startDate)%></li> --%>
+<%--                             <li><fmt:message key="end.date"/>: <%=dateFormat.format(endDate)%></li> --%>
+                            
+<!--                          </ul> -->
+						  <table border="0" class="normal">
+								<tr> <td><fmt:message key="invoice.date"/> </td>
+								     <td>: <%=dateFormat.format(billingDate)%></td>
+								</tr>
+									<tr> <td><fmt:message key="start.date"/> </td>
+								     <td>: <%=dateFormat.format(startDate)%></td>
+								</tr>
+									<tr> <td><fmt:message key="end.date"/></td>
+								     <td>: <%=dateFormat.format(endDate)%></td>
+								</tr>
+						</table>		
+                    </td>
+                </tr>
+                <tr>
+                    <td colspan="2">
+                        
+                        <table class="invice-data-table">
+                        <tr class="invoice-header">
+                                <td>Particulars</td>
+                                 <td style="text-align:right">Value (USD)</td>
+                            </tr>
+           <tr class="invoice-content-row">
+                	<td colspan="2"><strong style="color:#555"><fmt:message key="charges.subscriptions"/></strong></td>
+                </tr>
+                <%
+                    if(subscriptions!=null){
+                    for (MultitenancySubscription subscription: subscriptions) {
+
+                        String subscribedPackage = subscription.getSubscribedPackage();
+                        BilledEntry[] billedEntries = subscription.getBilledEntries();
+                        Date activeSince = subscription.getActiveSince();
+                        Date activeUntil = subscription.getActiveUntil();
+                %>
+                
+                <tr class="invoice-content-row">
+                    <td class="leftCol-med" style="padding-top:20px !important" colspan="2">
+                        <fmt:message key="subscription"/> Type: <strong><%=subscribedPackage%></strong>
+                    </td>
+                </tr>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.since"/>: <%=dateFormat.format(activeSince)%>
+                    </td>
+                </tr>
+                <%
+                    if(subscription.getActive()){
+                %>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.until"/>: <fmt:message key="this.is.active.subscription"/>
+                    </td>
+                </tr>
+                <%
+                    }
+                    else{
+                %>
+                <tr class="invoice-content-row">
+                    <td colspan="2">
+                        <fmt:message key="active.until"/>: <%=dateFormat.format(activeUntil)%> 
+                    </td>
+                </tr>
+                <%
+                    }
+                %>
+
+                <%
+                    if(billedEntries!=null && billedEntries.length>0){
+                       for (BilledEntry billedEntry: billedEntries) {
+                           if(billedEntry!=null){
+                            String name = billedEntry.getName();
+                            String cost = billedEntry.getCost();
+                %>
+                <tr class="invoice-content-row">
+                    <td>
+                        <%=name%>
+                    </td>
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=cost%>
+                    </td>
+                </tr>
+                <%
+                                    }
+                                }
+                            }
+                        }
+                    }
+                %>
+                	<tr class="invoice-content-row">
+                		<td colspan="2" style="padding-top:20px !important"><strong style="color:#555"><fmt:message key="payment.details"/></strong></td>
+                	</tr>
+                <%
+                if (purchaseOrders == null || purchaseOrders.length == 0) {
+                %>
+                 
+                 <tr class="invoice-content-row">
+                		<td colspan="2">You don't have any payment details for this period.</td></tr>                 
+                <%
+                } else {
+                    for (MultitenancyPurchaseOrder purchaseOrder: purchaseOrders) {
+                        if (purchaseOrder == null) {
+                            continue;
+                        }
+                        int id = purchaseOrder.getId();
+                        Date paymentDate = purchaseOrder.getPaymentDate();
+                        String payment = purchaseOrder.getPayment();
+                %>
+				<tr class="invoice-content-row">
+				<td class="leftCol-med"><fmt:message key="payment"/> : <strong><%=purchaseOrder.getTransactionId()%></strong> on <%=dateFormat.format(paymentDate)%></td>
+				<td style="text-align:right;font-weight:bold;"><%=payment%></td>
+				</tr>
+                
+                <%
+                    }
+                }
+                %>
+			
+				<tr class="invoice-content-row"><td colspan="2" style="padding-top:20px !important"><strong style="color:#555"><fmt:message key="invoice.summary"/></strong></td></tr>
+
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="brought.forward"/>
+                    </td>
+                
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=broughtForward%>
+                    </td>
+                </tr>
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="total.cost"/>
+                    </td>
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=totalCost%>
+                    </td>
+                </tr>
+
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="total.payments"/>
+                    </td>
+
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=totalPayments%>
+                    </td>
+                </tr>
+
+                <tr class="invoice-content-row">
+                    <td>
+                        <fmt:message key="carried.forward"/>
+                    </td>
+
+                    <td style="text-align:right;font-weight:bold;">
+                        <%=carriedForward%>
+                    </td>
+                </tr>
+                <!--<tr class="invoice-content-row">
+                    <td colspan="2" id="messageTd">&nbsp;</td>
+                </tr>-->
+            </table>
+                
+                
+                    </td>
+                </tr>
+                
+                <tr>
+                    <td colspan="2">
+                        <div class="name-field">Padmika Dissanaike,</div>
+                        Director- Finance
+                    </td>
+                </tr>
+            </table>
+                    <div style="background-color:#e2edf9;padding:10px;">
+                        <form name="startPaymentForm" method='POST'>
+                            <input type="hidden" name="successUrl" id="successUrl" value="<%=successUrl%>"/>
+                            <input type="hidden" name="cancelUrl" id="cancelUrl" value="<%=cancelUrl%>"/>
+                            <input type="hidden" name="amount" id="amount" value="<%=carriedForward%>"/>
+                            <a href="#"><img src='http://images.paypal.com/images/x-click-but6.gif'
+                                             border='0' align='top' alt='PayPal' onclick="setExpressCheckout('<%=paypalUrl%>');"/>
+                            </a>
+                        </form>
+                        <div style="color:#494949">Pay the invoice securely online</div>
+                    </div>
+                    <div style="color:#494949; display:none;" id="messageTd">Please wait until you are connected to Paypal <img src="../admin/images/loading-small.gif" /></div>
+                        </div>	
+             <%
+        		}
+    		%>
+    		
+        </div>
+</div>
+
+ </fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp
new file mode 100644
index 0000000..648086f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp
@@ -0,0 +1,28 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.MultitenancyInvoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%
+MultitenancyInvoice invoice = BillingUtil.getCurrentInvoice(config, session);
+
+// carried forward is the amount left to pay
+String carriedForward = invoice.getCarriedForward();
+session.setAttribute("requiredPaymentAmount", carriedForward);
+
+response.sendRedirect("../payment-paypal/prepare_payment.jsp");
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp
new file mode 100644
index 0000000..53354b8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp
@@ -0,0 +1,171 @@
+<!--
+~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+~
+~ WSO2 Inc. licenses this file to you under the Apache License,
+~ Version 2.0 (the "License"); you may not use this file except
+~ in compliance with the License.
+~ You may obtain a copy of the License at
+~
+~ http://www.apache.org/licenses/LICENSE-2.0
+~
+~ Unless required by applicable law or agreed to in writing,
+~ software distributed under the License is distributed on an
+~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+~ KIND, either express or implied. See the License for the
+~ specific language governing permissions and limitations
+~ under the License.
+-->
+<%@ page import="org.wso2.carbon.registry.common.ui.UIException" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.PaginatedBalanceInfoBean" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.OutstandingBalanceInfoBean" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<jsp:include page="../registry_common/registry_common-i18n-ajaxprocessor.jsp"/>
+
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.JSResources"
+        request="<%=request%>"/>
+
+<fmt:bundle basename="org.wso2.carbon.billing.mgt.ui.i18n.Resources">
+    <carbon:breadcrumb
+            label="view.balance.menu"
+            resourceBundle="org.wso2.carbon.billing.mgt.ui.i18n.Resources"
+            topPage="true"
+            request="<%=request%>"/>
+
+    <div id="top">
+        <form id="findTenantForm" action="view_balance.jsp" method="post">
+            <table class="normal-nopadding" cellspacing="0">
+                <tbody>
+                <tr>
+                    <td><fmt:message key="enter.tenant.domain"/></td>
+                    <td colspan="2"><input type="text" name="tenantDomain" id="tenantDomain"
+                                           style="width:300px"/>
+                        <input type="button" onclick="javascript:document.getElementById
+                    ('findTenantForm').submit();" value="Find"/>
+                    </td>
+                </tr>
+                </tbody>
+            </table>
+        </form>
+    </div>
+
+    <div id="middle">
+
+        <%
+            String tenantDomain = request.getParameter("tenantDomain");
+            String pageNumberStr = request.getParameter("pageNumber");
+            if (pageNumberStr == null) {
+                pageNumberStr = "0";
+            }
+            int pageNumber = 0;
+            try {
+                pageNumber = Integer.parseInt(pageNumberStr);
+            } catch (NumberFormatException ignored) {
+                // page number format exception
+            }
+            int numberOfPages = 0;
+            int noOfPageLinksToDisplay = 5;  //default value is set to 5
+
+            PaginatedBalanceInfoBean paginatedBalance;
+            OutstandingBalanceInfoBean[] balanceInfoArr;
+            try {
+                if (tenantDomain == null || "".equals(tenantDomain.trim())) {
+                    paginatedBalance = BillingUtil.getPaginatedBalanceInfo(config, session, pageNumber);
+                    balanceInfoArr = paginatedBalance.getBalanceInfoBeans();
+                    numberOfPages = paginatedBalance.getNumberOfPages();
+                } else {
+                    balanceInfoArr = BillingUtil.getOutstandingBalance(config, session, tenantDomain);
+                }
+            } catch (UIException e) {
+                String error1 = "Error in viewing balance of customers: " + e.getMessage();
+                request.setAttribute(CarbonUIMessage.ID, new CarbonUIMessage(error1, error1, null));
+        %>
+
+        <jsp:forward page="../admin/error.jsp"/>
+        <%
+                return;
+            }
+        %>
+        <br/>
+        <carbon:paginator pageNumber="<%=pageNumber%>" numberOfPages="<%=numberOfPages%>"
+                          noOfPageLinksToDisplay="<%=noOfPageLinksToDisplay%>"
+                          page="view_balance.jsp" pageNumberParameterName="pageNumber"/>
+        <br/>
+
+        <h2><fmt:message key="invoice.summary"/></h2>
+
+        <div id="workArea">
+
+            <table cellpadding="0" cellspacing="0" border="0" style="width:100%" class="styledLeft">
+                <thead>
+                <tr>
+                    <th style="padding-left:5px;text-align:left;">Domain</th>
+                    <th style="padding-left:5px;text-align:left;">Active Usage Plan</th>
+                    <th style="padding-left:5px;text-align:left;">Balance at Last Invoice</th>
+                    <th style="padding-left:5px;text-align:left;">Last Invoice Date</th>
+                    <th style="padding-left:5px;text-align:left;">Last Payment Date</th>
+                    <th style="padding-left:5px;text-align:left;">Last Paid Amount</th>
+                </tr>
+                </thead>
+                <tbody>
+                <%
+                    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+                    if (balanceInfoArr != null && balanceInfoArr.length > 0) {
+                        for (OutstandingBalanceInfoBean balanceInfo : balanceInfoArr) {
+                            if (balanceInfo == null) {
+                                continue;
+                            }
+                            String carriedForwardBalance = "Not Available";
+                            String lastInvoiceDate = "Not Available";
+                            String lastPaymentDate = "Not Available";
+                            String lastPaidAmount = "Not Available";
+                            if (balanceInfo.getCarriedForward() != null) {
+                                carriedForwardBalance = balanceInfo.getCarriedForward();
+                            }
+                            if (balanceInfo.getLastInvoiceDate() != null) {
+                                lastInvoiceDate = dateFormat.format(balanceInfo.getLastInvoiceDate());
+                            }
+                            if (balanceInfo.getLastPaymentDate() != null) {
+                                lastPaymentDate = dateFormat.format(balanceInfo.getLastPaymentDate());
+                            }
+                            if (balanceInfo.getLastPaidAmount() != null) {
+                                lastPaidAmount = balanceInfo.getLastPaidAmount();
+                            }
+                %>
+                <tr>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=balanceInfo.getCustomerName()%>
+                    </td>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=balanceInfo.getSubscription()%>
+                    </td>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=carriedForwardBalance%>
+                    </td>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=lastInvoiceDate%>
+                    </td>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=lastPaymentDate%>
+                    </td>
+                    <td style="padding-left:5px;padding-top:3px;text-align:left;"><%=lastPaidAmount%>
+                    </td>
+                </tr>
+                <% }
+                } else {
+                %>
+                <tr>
+                    <td colspan="6" style="padding-left:5px;padding-top:3px;text-align:center;">
+                        Could not find information for domain <%=tenantDomain%>
+                    </td>
+                </tr>
+                <%
+                    }
+                %>
+                <carbon:paginator pageNumber="<%=pageNumber%>" numberOfPages="<%=numberOfPages%>"
+                                  noOfPageLinksToDisplay="<%=noOfPageLinksToDisplay%>"
+                                  page="view_balance.jsp" pageNumberParameterName="pageNumber"/>
+                </tbody>
+            </table>
+        </div>
+    </div>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/pom.xml
new file mode 100644
index 0000000..ff01860
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/pom.xml
@@ -0,0 +1,116 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>billing-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.billing.mgt</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Billing</name>
+
+    <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>
+                        <!--<Require-Bundle>
+                            drools;visibility:=reexport
+                        </Require-Bundle>-->
+                        <Private-Package>
+                            org.wso2.carbon.billing.mgt.internal.*,
+                            org.wso2.carbon.billing.mgt.beans.*,
+                            org.wso2.carbon.billing.mgt.util.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.wso2.carbon.billing.mgt.dataobjects.*,
+                            org.wso2.carbon.billing.mgt.handlers.*,
+                            org.wso2.carbon.billing.mgt.api.*,
+                            org.wso2.carbon.billing.mgt.services.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.rule.*,
+                            org.quartz.*; version=2.1.1,
+                            org.apache.synapse.task.*,
+                            org.wso2.carbon.stratos.common.*,
+                            org.wso2.carbon.throttling.agent.client.*,
+                            org.wso2.carbon.throttling.agent.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.billing.core</artifactId>
+			<version>2.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.usage</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.throttling.agent</artifactId>
+        </dependency>
+    </dependencies>
+</project>


[52/52] git commit: Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-stratos

Posted by la...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-stratos

Amended Author for previos commit


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

Branch: refs/heads/master
Commit: dc8b360af30d02e3a9cb563fff21f2539dd1eb23
Parents: c1efa39 384b3de
Author: Lakmal Warusawithana <la...@wso2.com>
Authored: Sat Jun 29 11:48:18 2013 +0530
Committer: Lakmal Warusawithana <la...@wso2.com>
Committed: Sat Jun 29 11:48:18 2013 +0530

----------------------------------------------------------------------

----------------------------------------------------------------------



[28/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
new file mode 100644
index 0000000..cadc052
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Stores the generated invoice in the billing database.
+ */
+public class DefaultFinalizingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(DefaultFinalizingHandler.class);
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        // saving the bill
+        saveInvoice(handlerContext);
+    }
+
+    private void saveInvoice(BillingEngineContext handlerContext) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+        
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            Invoice invoice = customer.getActiveInvoice();
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        // from the invoice set we are calculating the purchase orders
+        for (Invoice invoice : invoiceMap.values()) {
+            // save the invoice first
+            dataAccessObject.addInvoice(invoice);
+            subscriptions = invoice.getSubscriptions();
+            for (Subscription subscription : subscriptions) {
+                // associate the subscription with the invoice.
+                int invoiceSubscriptionId =
+                        dataAccessObject.addInvoiceSubscription(invoice, subscription);
+                // now iterate all the items and save it in invoice subscription item space
+                if (subscription.getItem() != null) {
+                    addInvoiceSubscriptionItem(subscription.getItem(), invoiceSubscriptionId);
+                }
+            }
+        }
+        log.info( invoiceMap.size() + " Invoices saved to the database");
+    }
+
+    private void addInvoiceSubscriptionItem(Item item, 
+                                            int invoiceSubscriptionId) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        dataAccessObject.addInvoiceSubscriptionItem(item, invoiceSubscriptionId);
+        // and iterate through all the item children
+        if (item.getChildren() != null) {
+            for (Item subItem : item.getChildren()) {
+                addInvoiceSubscriptionItem(subItem, invoiceSubscriptionId);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
new file mode 100644
index 0000000..0dc39e1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This class finds all relevant subscription entries for
+ * the period considered in billing (i.e. billing cycle)
+ */
+public class DefaultSubscriptionFeedingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(DefaultSubscriptionFeedingHandler.class);
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    /**
+     *
+     * @param handlerContext - BillingEngineContext which keeps the data
+     * used in the bill generation process
+     * @throws BillingException
+     */
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        feedSubscriptions(handlerContext);
+    }
+
+    /**
+     * Finds the subscription of all the tenants applicable for the period being
+     * considered in bill generation
+     * @param handlerContext
+     * @throws BillingException
+     */
+    private void feedSubscriptions(BillingEngineContext handlerContext) throws BillingException {
+        // get the subscriptions right here..
+        Customer customer = handlerContext.getCustomer();
+        List<Subscription> subscriptions = getFilteredActiveSubscriptions(null, customer);
+        // prepare the handler context
+        handlerContext.setSubscriptions(subscriptions);
+        String infoMsg = "Subscription feeding phase completed. ";
+        if (subscriptions!=null){
+            infoMsg += subscriptions.size() + " subscriptions fed. ";
+        }else{
+            infoMsg += "0 subscriptions fed. ";
+        }
+        log.info(infoMsg);
+    }
+
+    /**
+     *
+     * @param filter - currently we pass the string "multitencay" because we
+     * need all the subscriptions. But, if you want subscriptions of a specific usage plan
+     * then you can pass it here. 
+     * @param customer - if generating an interim invoice, this is applicable.
+     * otherwise this will be null
+     * @return a list of subscriptions
+     * @throws BillingException
+     */
+    private List<Subscription> getFilteredActiveSubscriptions(String filter,
+                                                Customer customer) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        List<Subscription> subscriptions = null;
+        try {
+            dataAccessObject.beginTransaction();
+            if (customer == null) {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptions(filter);
+            } else {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptionsForCustomer(filter,
+                                                                                           customer);
+            }
+
+            // iterate through all the subscriptions and assign correct customer and item
+            for (Subscription subscription : subscriptions) {
+                Customer dummyCustomer = subscription.getCustomer();
+                Customer correctCustomer = getCustomer(dummyCustomer.getId());
+                subscription.setCustomer(correctCustomer);
+
+                Item dummyItem = subscription.getItem();
+                Item correctItem = getItem(dummyItem.getId());
+                subscription.setItem(correctItem);
+            }
+            dataAccessObject.commitTransaction();
+        }catch(Exception e){
+            String msg = "Error occurred while feeding subscription entries: " +
+                            e.getMessage();
+            log.error(msg);
+            dataAccessObject.rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    /**
+     * Gets the billable item for a subscription
+     * @param itemId in the subscription entry
+     * @return the item retrieved from the db
+     * @throws BillingException
+     */
+    private Item getItem(int itemId) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+        Item item = null;
+        try {
+            dataAccessObject.beginTransaction();
+            item = dataAccessObject.getItem(itemId);
+            dataAccessObject.commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while retrieving item for item id: " + itemId +
+                            ": " + e.getMessage();
+            dataAccessObject.rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return item;
+    }
+
+    private Customer getCustomer(int customerId) throws BillingException {
+        Customer customer = new Customer();
+        CustomerUtils.fillCustomerData(customerId, customer);
+        return customer;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
new file mode 100644
index 0000000..0990d74
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Payment;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.email.sender.api.BulkEmailSender;
+import org.wso2.carbon.email.sender.api.EmailDataHolder;
+import org.wso2.carbon.email.sender.api.EmailSender;
+import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Handles the email notifications after the bill generation
+ */
+public class EmailSendingHandler implements BillingHandler {
+    private static Log log = LogFactory.getLog(EmailSendingHandler.class);
+    private static String DEFAULT_EMAIL_NOTIFICATION_TEMPLATE_FILE = "email-billing-notification.xml";
+    private static String DEFAULT_REPORT_EMAIL_TEMPLATE_FILE = "email-bill-generated.xml";
+    private static String EMAIL_SENDING_CONF_KEY = "file";
+    private static String REPORT_EMAIL_TO_ADDRESS ="cloudservice@wso2.com";
+    BulkEmailSender bulkEmailSender;
+    EmailSender reportMailSender;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        if(CommonUtil.getStratosConfig()!=null){
+            REPORT_EMAIL_TO_ADDRESS = CommonUtil.getStratosConfig().getNotificationEmail();
+        }
+        
+        String confFileName = handlerConfig.get(EMAIL_SENDING_CONF_KEY);
+        if (confFileName == null) {
+            confFileName = DEFAULT_EMAIL_NOTIFICATION_TEMPLATE_FILE;
+        }
+        confFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator
+                       +StratosConstants.EMAIL_CONFIG+ File.separator + confFileName;
+
+        EmailSenderConfiguration emailSenderConfig =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(confFileName);
+        bulkEmailSender = new BulkEmailSender(emailSenderConfig);
+
+        //this is the email sent to the admin after bill generation
+        String reportMailFileName = DEFAULT_REPORT_EMAIL_TEMPLATE_FILE;
+        reportMailFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator
+                             +StratosConstants.EMAIL_CONFIG+File.separator+ reportMailFileName;
+
+        EmailSenderConfiguration reportEmailSenderConfig =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(reportMailFileName);
+        reportMailSender = new EmailSender(reportEmailSenderConfig);
+
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+        List<Integer> creditLimitExceededCustomers = new ArrayList<Integer>();
+        //this holds the data to be sent to bulk email bulkEmailSender
+        List<EmailDataHolder> emailDataList = new ArrayList<EmailDataHolder>();
+        
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            Invoice invoice = customer.getActiveInvoice();
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        for (Invoice invoice : invoiceMap.values()) {
+
+            //checkinh whether the carried forward is $0 because we dont want to
+            //send emails for $0 bills
+            Cash diff = Cash.subtract(new Cash("$0"), invoice.getCarriedForward());
+            if(diff.getSign().equals(Cash.Sign.NEGATIVE)){
+                Map<String, String> mailParameters = deriveInvoiceMailParameters(invoice);
+                Customer customer = invoice.getCustomer();
+                String emailAddress = customer.getEmail();
+                EmailDataHolder emailData = new EmailDataHolder();
+                emailData.setEmail(emailAddress);
+                emailData.setEmailParameters(mailParameters);
+                //we keep the data in the list to be sent as bulk
+                emailDataList.add(emailData);
+            }
+
+            //adding the customers who have exceeded the credit limit
+            // to a list to be informed to the admin
+            if(isExceedsCreditLimit(invoice)){
+                log.debug("Customer " + invoice.getCustomer().getName() + " needs to be reported");
+                creditLimitExceededCustomers.add(invoice.getCustomer().getId());
+            }
+
+        }
+
+        try {
+            log.info("Sending emails to the customers: " + emailDataList.size());
+            bulkEmailSender.sendBulkEmails(emailDataList);
+            log.info("Email (invoices) sending completed");
+        } catch (Exception e) {
+            String msg = "Error in sending the invoices to the customers";
+            log.error(msg, e);
+        }
+        //now sending the email with customers who have exceeded the credit limit
+        Map<String, String> reportEmailParameters = deriveReportEmailParameters(creditLimitExceededCustomers, invoiceMap);
+        try {
+            reportMailSender.sendEmail(REPORT_EMAIL_TO_ADDRESS, reportEmailParameters);
+            log.info("Email sent to the admin.");
+        } catch (Exception e) {
+            String msg = "Error in sending the bill generation completed email";
+            log.error(msg, e);
+        }
+
+    }
+
+    public static Map<String, String> deriveInvoiceMailParameters(Invoice invoice) {
+        Map<String, String> mailParameters = new HashMap<String, String>();
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+        mailParameters.put("start-date", dateFormat.format(invoice.getStartDate()));
+        mailParameters.put("end-date", dateFormat.format(invoice.getEndDate()));
+
+        Customer customer = invoice.getCustomer();
+
+        try{
+            TenantManager tenantManager = Util.getRealmService().getTenantManager();
+            Tenant tenant = (Tenant) tenantManager.getTenant(customer.getId());
+            mailParameters.put("tenant-domain", tenant.getDomain());
+            String customerName =
+                    ClaimsMgtUtil.getFirstName(Util.getRealmService(), customer.getId());
+            if(customerName!=null){
+                mailParameters.put("customer-name", customerName);
+            }else{
+                mailParameters.put("customer-name", "");
+            }
+
+        }catch(Exception e){
+            log.error("Could not get tenant information for tenant: " +
+                    customer.getName() + "\n" + e.getMessage());
+            mailParameters.put("customer-name", "");
+        }
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        if (subscriptions != null) {
+            StringBuffer subscriptionText = new StringBuffer();
+            for (Subscription subscription : subscriptions) {
+
+                if(subscription.isActive()){
+                    mailParameters.put("current-subscription", subscription.getSubscriptionPlan());
+                }
+                Item item = subscription.getItem();
+                String itemName = item.getDescription();
+                Cash itemCost = item.getCost();
+
+                String subscriptionPlan = subscription.getSubscriptionPlan();
+                if(itemCost!=null){
+                    subscriptionText.append(subscriptionPlan).append("\t\t\t").append(itemCost.toString()).append("\n");
+                }else{
+                    subscriptionText.append(subscriptionPlan).append("\n");
+                }
+
+                List<? extends Item> children = item.getChildren();
+                if (children != null) {
+                    for (Item childItem : children) {
+                        String childItemName = childItem.getDescription();
+                        Cash childItemCost = childItem.getCost();
+                        String childItemCostStr;
+                        if(childItemCost!=null){
+                            childItemCostStr = childItemCost.toString();
+                        }else{
+                            childItemCostStr = "$0.00";
+                        }
+                        subscriptionText.append("\t").append(childItemName).append("\t\t")
+                                .append(childItemCostStr).append("\n");
+                    }
+                }
+                subscriptionText.append("-------------------------------------------").append("\n");
+            }
+            mailParameters.put("subscription-charges", subscriptionText.toString());
+        }
+
+        StringBuffer paymentText = new StringBuffer();
+        if (invoice.getPayments() != null && invoice.getPayments().size()>0) {
+            for (Payment payment : invoice.getPayments()) {
+                Date paymentDate = payment.getDate();
+                Cash paymentAmount = payment.getAmount();
+
+                paymentText.append(dateFormat.format(paymentDate)).append("\t\t")
+                        .append(paymentAmount.toString()).append("\n");
+            }
+        }else{
+            paymentText.append("No payment details during this period");
+        }
+        mailParameters.put("payment-details", paymentText.toString());
+
+        if (invoice.getBoughtForward() != null) {
+            mailParameters.put("bought-forward", invoice.getBoughtForward().toString());
+        } else {
+            mailParameters.put("bought-forward", "$0");
+        }
+        if (invoice.getTotalCost() != null) {
+            mailParameters.put("total-cost", invoice.getTotalCost().toString());
+        } else {
+            mailParameters.put("total-cost", "$0");
+        }
+        if (invoice.getTotalPayment() != null) {
+            mailParameters.put("total-payments", invoice.getTotalPayment().toString());
+        } else {
+            mailParameters.put("total-payments", "$0");
+        }
+        if (invoice.getCarriedForward() != null) {
+            mailParameters.put("carried-forward", invoice.getCarriedForward().toString());
+        } else {
+            mailParameters.put("carried-forward", "$0");
+        }
+
+        return mailParameters;
+    }
+
+    private boolean isExceedsCreditLimit(Invoice invoice) throws BillingException{
+        boolean exceedsCreditLimit = false;
+        Cash creditLimit = new Cash("$0");
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        for(Subscription subscription : subscriptions){
+            if(subscription.isActive()){
+                List<? extends Item> subItems = subscription.getItem().getChildren();
+                for (Item item : subItems){
+                    if(BillingConstants.SUBSCRIPTION_SUBITEM.equals(item.getName())){
+                        if(item.getCreditLimit()!=null){
+                            creditLimit = Cash.add(creditLimit, item.getCreditLimit());
+                        }else{
+                            creditLimit = Cash.add(creditLimit, new Cash("$0"));
+                        }
+                        break;
+                    }
+                }
+                break;
+            }
+        }
+
+        Cash difference = Cash.subtract(invoice.getCarriedForward(), creditLimit);
+        if(Cash.Sign.POSITIVE == difference.getSign() && difference.getWholeNumber()>0){
+            exceedsCreditLimit = true;
+        }
+        return exceedsCreditLimit;
+    }
+
+    public Map<String, String> deriveReportEmailParameters(List<Integer> creditExceededCustomers, Map<Integer, Invoice> invoiceMap){
+        Map<String, String> mailParameters = new HashMap<String, String>();
+
+        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
+        //note that I haven't considered the timezone here
+        mailParameters.put("date", dateFormat.format(new Date()));
+
+        StringBuffer reportedCustomers = new StringBuffer();
+        if(creditExceededCustomers.isEmpty()){
+            reportedCustomers.append("No customers to be reported");
+        }else{
+            for(Integer customerId : creditExceededCustomers){
+                Invoice invoice = invoiceMap.get(customerId);
+                List<Subscription> subscriptions = invoice.getSubscriptions();
+                String activeSubscriptionName = "";
+                for(Subscription subscription : subscriptions){
+                    if(subscription.isActive()){
+                        activeSubscriptionName = subscription.getSubscriptionPlan();
+                        break;
+                    }
+                }
+                reportedCustomers.append(invoice.getCustomer().getName()).append("\t\t").
+                        append(activeSubscriptionName).append("\t\t").append(invoice.getCarriedForward().toString()).
+                        append("\n");
+            }
+        }
+        mailParameters.put("reported-customers", reportedCustomers.toString());
+
+        return mailParameters;
+    }    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
new file mode 100644
index 0000000..d745d8a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.*;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+
+import java.text.NumberFormat;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Calculates overusage charges, CF value, total payments etc.
+ */
+public class InvoiceCalculationHandler implements BillingHandler {
+
+    Log log = LogFactory.getLog(InvoiceCalculationHandler.class);
+    Map<Integer, Discount> discountMap = new HashMap<Integer, Discount>();
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        //we are getting the discount list and put them in to a map
+        List<Discount> discountList = BillingManager.getInstance().getDataAccessObject().getAllActiveDiscounts();
+        for(Discount discount : discountList){
+            discountMap.put(discount.getTenantId(), discount);
+        }
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        // calculate the bill
+        calculateInvoice(handlerContext);
+    }
+
+    private void calculateInvoice(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+        Map<Integer, Invoice> invoiceMap = new HashMap<Integer, Invoice>();
+       
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+
+            // invoice should be already set..
+            Invoice invoice = customer.getActiveInvoice();
+            Cash totalCost = invoice.getTotalCost();
+            if (totalCost == null) {
+                totalCost = new Cash("$0");
+            }
+        
+            Item item = subscription.getItem();
+            //prorate the subscription cost
+            //prorateItemCosts(item, invoice, subscription);
+            calculateItemCost(item, invoice, subscription);
+            Cash itemCost = getItemCost(item);
+            totalCost = Cash.add(totalCost, itemCost);
+            invoice.setTotalCost(totalCost);
+            if (invoiceMap.get(customer.getId()) == null) {
+                invoiceMap.put(customer.getId(), invoice);
+            }
+        }
+
+        // from the invoice set we are calculating the payments       purchase orders
+        for (Invoice invoice : invoiceMap.values()) {
+            Cash totalPayment = invoice.getTotalPayment();
+            if (totalPayment == null) {
+                totalPayment = new Cash("$0");
+            }
+            List<Payment> payments = invoice.getPayments();
+            if (payments != null) {
+                for (Payment payment : payments) {
+                    Cash paymentCash = payment.getAmount();
+                    totalPayment = Cash.add(paymentCash, totalPayment);
+                }
+            }
+            invoice.setTotalPayment(totalPayment);
+
+            // setting the carried forward
+            Cash boughtForward = invoice.getBoughtForward();
+            if (boughtForward == null) {
+                boughtForward = new Cash("$0");
+            }
+            Cash totalCost = invoice.getTotalCost();
+            Cash carriedForward = Cash.subtract(Cash.add(boughtForward, totalCost), totalPayment);
+            invoice.setCarriedForward(carriedForward);
+        }
+
+        log.info("Invoice calculation phase completed. " + invoiceMap.size() + " invoices were calculated");
+    }
+
+    private Cash getItemCost(Item item) throws BillingException {
+        Cash itemCost = item.getCost();
+        if (itemCost == null) {
+            itemCost = new Cash("$0");
+        }
+        if (item.getChildren() != null) {
+            // and iterate through all the item children
+            for (Item subItem : item.getChildren()) {
+                Cash subItemCost = subItem.getCost();
+                if (subItemCost != null) {
+                    itemCost = Cash.add(itemCost, subItemCost);
+                }
+            }
+        }
+        return itemCost;
+    }
+
+    private void calculateItemCost(Item item, Invoice invoice, Subscription subscription) throws BillingException {
+        if(item.getChildren()!=null){
+            for(Item subItem : item.getChildren()){
+                if((BillingConstants.BANDWIDTH_SUBITEM.equals(subItem.getName()) ||
+                    BillingConstants.STORAGE_SUBITEM.equals(subItem.getName()) ||
+                    BillingConstants.CARTRIDGE_SUBITEM.equals(subItem.getName())) && subscription.isActive()){
+                    calculateOverUseCharges(item, subItem, subscription);
+                }else if(BillingConstants.SUBSCRIPTION_SUBITEM.equals(subItem.getName())){
+                    prorateItemCosts(subItem, invoice, subscription);
+                }
+            }
+        }
+    }
+
+    private void calculateOverUseCharges(Item item, Item subItem, Subscription subscription) throws BillingException {
+        //calculating cost for bandwidth overuse
+        if(BillingConstants.BANDWIDTH_SUBITEM.equals(subItem.getName())){
+            long bandwidthUsage = subscription.getCustomer().getTotalBandwidth()/(1024 * 1024L);
+            long bandwidthOveruse = 0;
+            if(bandwidthUsage > item.getBandwidthLimit()){
+                bandwidthOveruse = bandwidthUsage - item.getBandwidthLimit();
+                subItem.setCost(item.getBandwidthOveruseCharge().multiply(bandwidthOveruse));
+            }
+            StringBuffer description = new StringBuffer();
+            description.append(subItem.getDescription());
+            description.append(": ").append(bandwidthOveruse).append("MB");
+            subItem.setDescription(description.toString());
+        //calculating cost for storage overuse    
+        }else if(BillingConstants.STORAGE_SUBITEM.equals(subItem.getName())){
+            long storageUsage = subscription.getCustomer().getTotalStorage()/(1024 * 1024L);
+            long storageOveruse = 0;
+            if(storageUsage > item.getResourceVolumeLimit()){
+                storageOveruse = storageUsage - item.getResourceVolumeLimit();
+                subItem.setCost(item.getResourceVolumeOveruseCharge().multiply(storageOveruse));
+            }
+            StringBuffer description = new StringBuffer();
+            description.append(subItem.getDescription());
+            description.append(": ").append(storageOveruse).append("MB");
+            subItem.setDescription(description.toString());
+        //calculating the cost for cartridge overuse
+        }else if(BillingConstants.CARTRIDGE_SUBITEM.equals(subItem.getName())){
+            long cartridgeCpuUsage = subscription.getCustomer().getTotalCartridgeCPUHours();
+            long cartridgeCpuOveruse = 0;
+            if(cartridgeCpuUsage > item.getCartridgeCPUHourLimit()){
+                cartridgeCpuOveruse = cartridgeCpuUsage - item.getCartridgeCPUHourLimit();
+                subItem.setCost(item.getCartridgeCPUOveruseCharge().multiply(cartridgeCpuOveruse));
+            }
+
+            StringBuffer description = new StringBuffer();
+            description.append(subItem.getDescription());
+            description.append(": ").append(cartridgeCpuOveruse).append("Hours");
+            subItem.setDescription(description.toString());
+        }
+
+    }
+
+    //by looking at the start and end dates of the invoice, subscription item's cost is interpolated
+    private void prorateItemCosts(Item subItem, Invoice invoice, Subscription subscription) throws BillingException {
+        long milisecondsPerDay = 24*60*60*1000L;
+        NumberFormat nf = NumberFormat.getInstance();
+		nf.setMaximumFractionDigits(2);
+
+        int tenantId = invoice.getCustomer().getId();
+        Discount discount = discountMap.get(tenantId);
+
+        long period;
+        long days;
+
+        if(subscription.isActive()){
+            if(subscription.getActiveSince().before(invoice.getStartDate())){
+                period = invoice.getEndDate().getTime() - invoice.getStartDate().getTime();
+            }else{
+                period = invoice.getEndDate().getTime() - subscription.getActiveSince().getTime();
+            }
+        }else{ 
+            if(subscription.getActiveSince().before(invoice.getStartDate())){
+                period = subscription.getActiveUntil().getTime() - invoice.getStartDate().getTime();
+            }else{
+                period = subscription.getActiveUntil().getTime() - subscription.getActiveSince().getTime();
+            }
+        }
+
+        //I am considering 28 days or more as a complete month
+        days = period/milisecondsPerDay;
+        if(days<28){
+            float multiplyingFactor = (float)days/30;
+            multiplyingFactor = Float.parseFloat(nf.format(multiplyingFactor));
+
+            //prorate the subscription fee...
+            if(subItem.getCost()!=null){
+                subItem.setCost(subItem.getCost().multiply(multiplyingFactor));
+            }
+
+            //prorating the discount too (if the discount is defined as a raw amount)...
+            if(discount!=null && !discount.isPercentageType()){
+                discount.setAmount(Float.parseFloat(nf.format(discount.getAmount()*multiplyingFactor)));
+            }
+        }
+        
+        //Check whether the customer is offered any discounts and reduce the subscription fee
+        
+        if(discount!=null){
+            
+            if(discount.isPercentageType()){
+                subItem.setCost(subItem.getCost().multiply(1 - (discount.getPercentage()/100)));
+                subItem.setDescription(subItem.getDescription() + " (with " + discount.getPercentage() + "% discount)");
+                log.info("Customer: " + tenantId + " was qualified for a discount of " +
+                        discount.getPercentage() + "% for subscription:" + subscription.getSubscriptionPlan() +
+                        " which started from:" + subscription.getActiveSince().toString());
+            }else{
+                subItem.setCost(Cash.subtract(subItem.getCost(), new Cash(String.valueOf(discount.getAmount()))));
+                subItem.setDescription(subItem.getDescription() + " (with " + new Cash(String.valueOf(discount.getAmount())).toString() + " discount)");
+                log.info("Customer: " + tenantId + " was qualified for a discount of " +
+                        new Cash(String.valueOf(discount.getAmount())).toString() + " for subscription:" + subscription.getSubscriptionPlan() +
+                        " which started from:" + subscription.getActiveSince().toString());
+            }
+
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
new file mode 100644
index 0000000..630db9f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.rule.common.Rule;
+import org.wso2.carbon.rule.common.RuleSet;
+import org.wso2.carbon.rule.common.exception.RuleConfigurationException;
+import org.wso2.carbon.rule.common.exception.RuleRuntimeException;
+import org.wso2.carbon.rule.common.util.Constants;
+import org.wso2.carbon.rule.kernel.backend.RuleBackendRuntime;
+import org.wso2.carbon.rule.kernel.backend.RuleBackendRuntimeFactory;
+import org.wso2.carbon.rule.kernel.backend.Session;
+import org.wso2.carbon.rule.kernel.config.RuleEngineProvider;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.*;
+
+/**
+ * Runs the billing rules against each subscription
+ * At the moment only the subscription fee is calculated by
+ * these rules. Overusage charges are calculated by InvoiceCalculationHandler
+ */
+public class RuleHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(RuleHandler.class);
+    private Session ruleSession;
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+
+        //create a rule run time to execute rules.
+
+        RuleEngineProvider ruleEngineProvider = Util.getRuleEngineConfigService().getRuleConfig().getRuleEngineProvider();
+
+        Class ruleBackendRuntimeFactoryClass;
+
+        try {
+            ruleBackendRuntimeFactoryClass = Class.forName(ruleEngineProvider.getClassName());
+            RuleBackendRuntimeFactory ruleBackendRuntimeFactory =
+                    (RuleBackendRuntimeFactory) ruleBackendRuntimeFactoryClass.newInstance();
+            RuleBackendRuntime ruleBackendRuntime =
+                           ruleBackendRuntimeFactory.getRuleBackendRuntime(ruleEngineProvider.getProperties(),
+                           Thread.currentThread().getContextClassLoader());
+
+            // create a rule set to add
+            RuleSet ruleSet = new RuleSet();
+            Rule rule = new Rule();
+            rule.setResourceType(Constants.RULE_RESOURCE_TYPE_REGULAR);
+
+            rule.setSourceType(Constants.RULE_SOURCE_TYPE_URL);
+
+            String ruleFile = handlerConfig.get("file");
+            ruleFile = CarbonUtils.getCarbonConfigDirPath() + File.separator + ruleFile;
+            rule.setValue("file://" + ruleFile);
+            log.info("Rule: " + rule.getValue());
+
+            ruleSet.addRule(rule);
+
+            ruleBackendRuntime.addRuleSet(ruleSet);
+
+            this.ruleSession = ruleBackendRuntime.createSession(Constants.RULE_STATEFUL_SESSION);
+
+        } catch (Exception e) {
+            String msg = "Error occurred while initializing the rule executing environment: " +
+                    e.getMessage();
+            log.error(msg);
+            throw new BillingException(msg, e);
+        } 
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+
+        List<Object> rulesInput = new ArrayList<Object>();
+        Set<Integer> customerSet = new HashSet<Integer>();
+
+        for (Subscription subscription : subscriptions) {
+            // add the subscriptions
+            rulesInput.add(subscription);
+
+            // add the customers
+            Customer customer = subscription.getCustomer();
+            if (!customerSet.contains(customer.getId())) {
+                customerSet.add(customer.getId());
+                rulesInput.add(customer);
+
+                // add the invoice too
+                Invoice invoice = customer.getActiveInvoice();
+                rulesInput.add(invoice);
+
+                // add each purchases
+                List<Payment> payments = invoice.getPayments();
+                if (payments != null) {
+                    for (Payment payment : payments) {
+                        rulesInput.add(payment);
+                    }
+                }
+            }
+
+            // add the items
+            Item item = subscription.getItem();
+            rulesInput.add(item);
+
+            List<? extends Item> children = item.getChildren();
+            if (children != null) {
+                for (Item subItem : item.getChildren()) {
+                    rulesInput.add(subItem);
+                }
+            }
+        }
+
+        try {
+            this.ruleSession.execute(rulesInput);
+        } catch (RuleRuntimeException e) {
+            String msg = "Error occurred while executing rules during the bill generation: " +
+                    e.getMessage();
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+        log.info("Rule execution phase completed.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
new file mode 100644
index 0000000..131430f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Payment;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Subscriptions found in the subscription feeding handler are
+ * added to relevant invoices via this class
+ */
+public class SubscriptionTreeBuildingHandler implements BillingHandler {
+
+    private static Log log = LogFactory.getLog(SubscriptionTreeBuildingHandler.class);
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        // nothing to initialize
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        buildSubscriptionTree(handlerContext);
+    }
+
+    /**
+     * Creates maps of <customer, list of subscriptions>. Then creates
+     * invoices for each customers.
+     * @param handlerContext this is the BillingEngineContext
+     * @throws BillingException throws a BillingException
+     */
+    private void buildSubscriptionTree(BillingEngineContext handlerContext) throws BillingException {
+        DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
+
+        // get the subscription from handler context
+        List<Subscription> subscriptions = handlerContext.getSubscriptions();
+
+        Map<Customer, List<Subscription>> customersSubscriptions = new HashMap<Customer, List<Subscription>>();
+
+        for (Subscription subscription : subscriptions) {
+            Customer customer = subscription.getCustomer();
+            List<Subscription> customerSubscriptions = customersSubscriptions.get(customer);
+            if (customerSubscriptions == null) {
+                customerSubscriptions = new ArrayList<Subscription>();
+            }
+            customerSubscriptions.add(subscription);
+            customersSubscriptions.put(customer, customerSubscriptions);
+        }
+
+        // so iterating all the customers
+        for (Map.Entry<Customer, List<Subscription>> entry : customersSubscriptions.entrySet()) {
+            Customer customer = entry.getKey();
+            List<Subscription> customerSubscriptions = entry.getValue();
+
+            // create an empty invoice
+            Invoice invoice = new Invoice();
+
+            // get the last invoice for the customer
+            Invoice lastInvoice = dataAccessObject.getLastInvoice(customer);
+
+            if (lastInvoice != null) {
+                invoice.setBoughtForward(lastInvoice.getCarriedForward());
+                long lastInvoiceEnd = lastInvoice.getEndDate().getTime();
+                long currentInvoiceStart = lastInvoiceEnd + 1000;    //one second after
+                                                                    // the last invoice
+                invoice.setStartDate(new Date(currentInvoiceStart));
+            } else {
+                invoice.setBoughtForward(new Cash("$0"));
+                // the earliest of the subscriptions
+                long earliestSubscriptionStart = -1;
+                for (Subscription subscription : customerSubscriptions) {
+                    long subscriptionStartDate = subscription.getActiveSince().getTime();
+                    if (earliestSubscriptionStart == -1 ||
+                        subscriptionStartDate < earliestSubscriptionStart) {
+                        earliestSubscriptionStart = subscriptionStartDate;
+                    }
+                }
+                invoice.setStartDate(new Date(earliestSubscriptionStart));
+            }
+            
+            Date currentDate = new Date();
+            invoice.setEndDate(currentDate);
+            // this is the date the billing is initialized, this can be probably overwritten
+            invoice.setDate(currentDate);
+
+            // and we will count for the subscriptions for the invoice
+            invoice.setSubscriptions(customerSubscriptions);
+
+            // and then we will count on the un-billed purchases of all the subscriptions of the
+            // customer
+            Map<Integer, Payment> purchaseOrders = new HashMap<Integer, Payment>();
+            for (Subscription subscription : customerSubscriptions) {
+                dataAccessObject.fillUnbilledPayments(subscription, purchaseOrders, invoice );
+            }
+            for (Payment payment : purchaseOrders.values()) {
+                invoice.addPayment(payment);
+            }
+
+            customer.setActiveInvoice(invoice);
+            invoice.setCustomer(customer);
+        }
+
+        log.info("Subscription-tree building phase completed");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
new file mode 100644
index 0000000..ad697e9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
@@ -0,0 +1,171 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.internal;
+
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.BillingTenantMgtListenerImpl;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+import org.wso2.carbon.ndatasource.core.DataSourceService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.rule.kernel.config.RuleEngineConfigService;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.stratos.common.util.StratosConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * @scr.component name="org.wso2.carbon.billing.core" immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1"
+ *                policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="org.wso2.carbon.billing.core.billing.handler.service"
+ *                interface="org.wso2.carbon.billing.core.BillingHandler"
+ *                cardinality="0..n"
+ *                policy="dynamic" bind="setBillingHandlerService"
+ *                unbind="unsetBillingHandlerService"
+ * @scr.reference name="org.wso2.carbon.billing.core.task.schedule.helper.service"
+ *                interface="org.wso2.carbon.billing.core.scheduler.ScheduleHelper"
+ *                cardinality="0..n"
+ *                policy="dynamic" bind="setScheduleHelperService"
+ *                unbind="unsetScheduleHelperService"
+ * @scr.reference name="rule.engine.config.server.component"
+ *                interface="org.wso2.carbon.rule.kernel.config.RuleEngineConfigService"
+ *                cardinality="1..1"
+ *                policy="dynamic" bind="setRuleEngineConfigService"
+ *                unbind="unsetRuleEngineConfigService"
+ * @scr.reference name="org.wso2.carbon.tenant.mgt.listener.service"
+ *                interface="org.wso2.carbon.stratos.common.listeners.TenantMgtListener"
+ *                cardinality="0..n" policy="dynamic"
+ *                bind="setTenantMgtListenerService"
+ *                unbind="unsetTenantMgtListenerService"
+ * @scr.reference name="datasources.service"
+ *                interface="org.wso2.carbon.ndatasource.core.DataSourceService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setDataSourceService" unbind="unsetDataSourceService" 
+ */
+public class BillingServiceComponent {
+    private static Log log = LogFactory.getLog(BillingServiceComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            if(CommonUtil.getStratosConfig()==null){
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+            Util.initBillingManager(context.getBundleContext());
+            Util.initDataAccessManager();
+
+            BillingTenantMgtListenerImpl billingTenantMgtListener = new BillingTenantMgtListenerImpl();
+            context.getBundleContext().registerService(
+                    org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
+                    billingTenantMgtListener, null);
+            if (log.isDebugEnabled()) {
+                log.debug("******* Billing bundle is activated ******* ");
+            }
+        } catch (Throwable e) {
+            log.error("******* Billing bundle failed activating ****", e);
+        }
+    }
+
+    @SuppressWarnings("unused")
+    protected void deactivate(ComponentContext context) {
+        Util.cleanBillingManager();
+        log.debug("******* Billing is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    protected void setBillingHandlerService(BillingHandler billingHandler) {
+        BillingTaskConfiguration.addBillingHandler(billingHandler);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetBillingHandlerService(BillingHandler billingHandler) {
+        // we are not dynamically removing billing handlers
+    }
+
+    protected void setScheduleHelperService(ScheduleHelper scheduleHelper) {
+        BillingTaskConfiguration.addScheduleHelper(scheduleHelper);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetScheduleHelperService(ScheduleHelper scheduleHelper) {
+        // we are not dynamically removing schedule helpers
+    }
+
+    protected void setRuleEngineConfigService(RuleEngineConfigService ruleEngineConfigService) {
+        Util.setRuleEngineConfigService(ruleEngineConfigService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRuleEngineConfigService(RuleEngineConfigService ruleEngineConfigService) {
+        Util.setRuleEngineConfigService(null);
+    }
+
+    protected void setTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.addTenantMgtListenerService(tenantMgtListener);
+    }
+
+    protected void unsetTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.removeTenantMgtListenerService(tenantMgtListener);
+    }
+
+    protected void setDataSourceService(DataSourceService dataSourceService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the Data Sources Service");
+        }
+        Util.setDataSourceService(dataSourceService);
+    }
+
+    protected void unsetDataSourceService(DataSourceService dataSourceService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unsetting the Data Sources Service");
+        }
+        Util.setDataSourceService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
new file mode 100644
index 0000000..b6a0951
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
@@ -0,0 +1,132 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.billing.core.internal;
+
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.DataAccessManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.ndatasource.core.DataSourceService;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.rule.kernel.config.RuleEngineConfigService;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class Util {
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static RuleEngineConfigService ruleEngineConfigService;
+    private static List<TenantMgtListener> tenantMgtListeners = new ArrayList<TenantMgtListener>();
+    private static DataAccessManager dataAccessManager;
+    private static DataSourceService dataSourceService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService(){
+        return Util.realmService;
+    }
+
+    public static void setRuleEngineConfigService(RuleEngineConfigService ruleServerManagerService) {
+        Util.ruleEngineConfigService = ruleServerManagerService;
+    }
+
+    public static RuleEngineConfigService getRuleEngineConfigService() {
+        return Util.ruleEngineConfigService;
+    }
+
+    public static void initBillingManager(BundleContext bundleContext) throws BillingException {
+        // load the configuration and initialize the billing engine + do the
+        // necessary scheduling.
+        String configFile =
+                CarbonUtils.getCarbonConfigDirPath() + File.separator + BillingConstants.BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+
+        bundleContext.registerService(BillingManager.class.getName(), billingManager, null);
+    }
+    
+    public static void initDataAccessManager() throws BillingException{
+        Util.dataAccessManager = new DataAccessManager(BillingManager.getInstance().getDataAccessObject());
+    }
+
+    public static DataAccessManager getDataAccessManager(){
+        return dataAccessManager;
+    }
+
+    public static void cleanBillingManager() {
+        BillingManager.destroyInstance();
+    }
+    
+    public static void addTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.add(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void removeTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.remove(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void setDataSourceService(DataSourceService service) {
+        if (dataSourceService == null) {
+            dataSourceService = service;
+        }
+    }
+
+    public static DataSourceService getDataSourceService(){
+        return dataSourceService;
+    }
+
+    private static void sortTenantMgtListeners() {
+        Collections.sort(tenantMgtListeners, new Comparator<TenantMgtListener>() {
+            public int compare(TenantMgtListener o1, TenantMgtListener o2) {
+                return o1.getListenerOrder() - o2.getListenerOrder();
+            }
+        });
+    }
+
+    public static void alertTenantSubscriptionPlanChange(int tenantId, String oldSubscriptionPlan, 
+                                          String newSubscriptionPlan) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onSubscriptionPlanChange(
+                    tenantId, oldSubscriptionPlan, newSubscriptionPlan);
+        }
+    }
+}


[44/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
new file mode 100644
index 0000000..f5aae03
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/LoadBalancerConfiguration.java
@@ -0,0 +1,1205 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.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.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.conf.util.LoadBalancerConfigUtil;
+import org.wso2.carbon.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) {
+//            if (minAppInstances < 1) {
+//                LoadBalancerConfigUtil.handleException("minAppInstances in the autoscaler task configuration " +
+//                        "should be at least 1");
+//            }
+            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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
new file mode 100644
index 0000000..b488bf3
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/internal/LoadBalancerConfigurationDSComponent.java
@@ -0,0 +1,46 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.lb.common.conf.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.lb.common.service.impl.LoadBalancerConfigurationServiceImpl;
+
+/**
+ * Registering {@link 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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
new file mode 100644
index 0000000..a1ccc60
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/Node.java
@@ -0,0 +1,355 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
new file mode 100644
index 0000000..f7bfe2f
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/structure/NodeBuilder.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.lb.common.conf.structure;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
new file mode 100644
index 0000000..bc83ca9
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/Constants.java
@@ -0,0 +1,49 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.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]+";
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
new file mode 100644
index 0000000..1845017
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/HostContext.java
@@ -0,0 +1,160 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
new file mode 100644
index 0000000..404849b
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/LoadBalancerConfigUtil.java
@@ -0,0 +1,288 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.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) {
+            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 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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
new file mode 100644
index 0000000..fdb893e
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/conf/util/TenantDomainContext.java
@@ -0,0 +1,79 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.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 **/
+    
+    
+    
+
+}


[30/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
new file mode 100644
index 0000000..9b4f609
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class TriggerTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "carbonHome2TestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        /*RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome2";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        //billingEngine.generateBill();
+        // instead of calling the billing engine we are triggering the scheduler
+        billingEngine.scheduleBilling();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+        try {
+            Thread.currentThread().sleep(14000);
+        } catch (InterruptedException e) {
+            assertTrue(false);
+        }
+        assertEquals(2, FiveSecondTriggerTester.getCount());
+
+        for (int i = 0; i < customers.size(); i++) {
+
+            Customer customer = customers.get(i);
+            List<Invoice> invoices = billingEngine.getAllInvoices(customer);
+            assertEquals(1, invoices.size());
+            Invoice invoice = invoices.get(0);
+            //Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-config.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-config.xml
new file mode 100644
index 0000000..af722bd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-config.xml
@@ -0,0 +1,83 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+    <dbConfig>
+        <url>jdbc:mysql://localhost:3306/billing_test1</url>
+        <userName>billing</userName>
+        <password>billing</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>80</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+    <tasks>
+        <task id="carbonHome1TestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule
+                    scheduleHelperClass="org.wso2.carbon.billing.core.scheduler.scheduleHelpers.OneTimeScheduleHelper">
+                <parameter name="dayToTriggerOn">1</parameter>
+                <parameter name="hourToTriggerOn">0</parameter>
+                <parameter name="timeZone">GMT-8:00</parameter>
+            </schedule>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <!--<handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">multitenancy-billing-rule.xml</parameter>
+                </handler> -->
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+
+        <task id="ruleTestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+    </tasks>
+</billingConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
new file mode 100644
index 0000000..1905308
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
@@ -0,0 +1,15 @@
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+rule customerOneSpecial
+when
+$customer : Customer(name == "customer-1" )
+
+then
+
+Invoice invoice = $customer.getActiveInvoice();
+Cash total = invoice.getTotalCost();
+invoice.setTotalCost(Cash.subtract(total, new Cash("$1")));
+
+end

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
new file mode 100644
index 0000000..c2fcd09
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
@@ -0,0 +1,31 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <subject>WSO2 Governance as a Service - Registration completed</subject>
+    <body>
+        Hi {admin-name},
+        Congratulations!. You have successfully crated an account in WSO2 Governance as a Service.
+        Now you can access your account by visiting the following URL. Please bookmark this URL for
+        the later visits.
+
+        Your account url: https://governance.stratoslive.wso2.com/t/{domain-name}
+
+        Thanks,
+        WSO2 Governance as a Service Team
+    </body>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration.xml
new file mode 100644
index 0000000..3a3f22d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Registration confirmation</subject>
+    <body>
+        Hi,
+        Thank you for registering for an account in WSO2 Governance as a Service. In order to
+        activate your account, Please click the following link and verfiy your email.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../tenant-register/tenant_add_ajaxprocessor.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-update.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-update.xml
new file mode 100644
index 0000000..3f3b8ea
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-update.xml
@@ -0,0 +1,34 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Updating the contact email address</subject>
+    <body>
+        Hi,
+        We got a request to change the contact email address of WSO2 Governance as a Service
+        account. In order to update the contact details, Please click the following link and verfiy
+        your email address.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../account-mgt/update_verifier.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
new file mode 100644
index 0000000..3bde368
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
@@ -0,0 +1,41 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration xmlns="http://www.wso2.org/products/rule/drools">
+    <executionSet uri="simpleItemRuleXML">
+        <source key="file:{conf-dir}/billing-rules1.drl"/>
+
+        <!-- <source>
+
+       <x><![CDATA[
+        rule InvokeABC
+        // rules inbuilt to the rule conf
+        end
+
+        ]]>
+       </x>
+       </source> -->
+        <creation>
+            <property name="source" value="drl"/>
+
+        </creation>
+    </executionSet>
+    <session type="stateless"/>
+    <input name="facts" type="billing" key="dataContext"></input>
+
+    <output name="results" type="billing" key="dataContext"></output>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
new file mode 100644
index 0000000..7dc9d8b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
@@ -0,0 +1,88 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="Demo">
+        <users>
+            <limit>5</limit>
+            <charge>0</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>1000</limit>
+            <!-- mb per user -->
+            <overuseCharge>0</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="SMB">
+        <users>
+            <limit>10</limit>
+            <charge>10</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>25</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+        <userLimit>10</userLimit>
+    </package>
+    <package name="Professional">
+        <users>
+            <limit>50</limit>
+            <charge>50</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="Enterprise">
+        <users>
+            <limit>unlimited</limit>
+            <charge>5000</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>4000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+</packages>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/notification.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/notification.xml
new file mode 100644
index 0000000..25e09e8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/notification.xml
@@ -0,0 +1,23 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!-- configure the notifications -->
+<Notifications>
+    <enabled>true</enabled>
+    <host>http://localhost/feed.xml?product={product}&amp;build={build}&amp;instance={instance.id}&amp;tenant={tenant}</host>
+</Notifications>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-config.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-config.xml
new file mode 100644
index 0000000..abd2f55
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-config.xml
@@ -0,0 +1,86 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+    <dbConfig>
+        <url>jdbc:mysql://localhost:3306/billing_test1</url>
+        <userName>billing</userName>
+        <password>billing</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>80</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+    <tasks>
+        <task id="carbonHome2TestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule
+                    scheduleHelperClass="org.wso2.carbon.billing.test.FiveSecondTriggerCalculator">
+                <parameter name="countUpToLimit">2</parameter>
+            </schedule>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <!--<handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">multitenancy-billing-rule.xml</parameter>
+                </handler> -->
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.test.FiveSecondTriggerTester">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+
+        <task id="ruleTestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+    </tasks>
+</billingConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
new file mode 100644
index 0000000..1905308
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
@@ -0,0 +1,15 @@
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+rule customerOneSpecial
+when
+$customer : Customer(name == "customer-1" )
+
+then
+
+Invoice invoice = $customer.getActiveInvoice();
+Cash total = invoice.getTotalCost();
+invoice.setTotalCost(Cash.subtract(total, new Cash("$1")));
+
+end

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
new file mode 100644
index 0000000..c2fcd09
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
@@ -0,0 +1,31 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <subject>WSO2 Governance as a Service - Registration completed</subject>
+    <body>
+        Hi {admin-name},
+        Congratulations!. You have successfully crated an account in WSO2 Governance as a Service.
+        Now you can access your account by visiting the following URL. Please bookmark this URL for
+        the later visits.
+
+        Your account url: https://governance.stratoslive.wso2.com/t/{domain-name}
+
+        Thanks,
+        WSO2 Governance as a Service Team
+    </body>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration.xml
new file mode 100644
index 0000000..3a3f22d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Registration confirmation</subject>
+    <body>
+        Hi,
+        Thank you for registering for an account in WSO2 Governance as a Service. In order to
+        activate your account, Please click the following link and verfiy your email.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../tenant-register/tenant_add_ajaxprocessor.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-update.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-update.xml
new file mode 100644
index 0000000..3f3b8ea
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-update.xml
@@ -0,0 +1,34 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Updating the contact email address</subject>
+    <body>
+        Hi,
+        We got a request to change the contact email address of WSO2 Governance as a Service
+        account. In order to update the contact details, Please click the following link and verfiy
+        your email address.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../account-mgt/update_verifier.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
new file mode 100644
index 0000000..3bde368
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
@@ -0,0 +1,41 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration xmlns="http://www.wso2.org/products/rule/drools">
+    <executionSet uri="simpleItemRuleXML">
+        <source key="file:{conf-dir}/billing-rules1.drl"/>
+
+        <!-- <source>
+
+       <x><![CDATA[
+        rule InvokeABC
+        // rules inbuilt to the rule conf
+        end
+
+        ]]>
+       </x>
+       </source> -->
+        <creation>
+            <property name="source" value="drl"/>
+
+        </creation>
+    </executionSet>
+    <session type="stateless"/>
+    <input name="facts" type="billing" key="dataContext"></input>
+
+    <output name="results" type="billing" key="dataContext"></output>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
new file mode 100644
index 0000000..0239204
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
@@ -0,0 +1,88 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="multitenancy-free">
+        <users>
+            <limit>5</limit>
+            <charge>0</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>1000</limit>
+            <!-- mb per user -->
+            <overuseCharge>0</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-small">
+        <users>
+            <limit>10</limit>
+            <charge>10</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>25</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+        <userLimit>10</userLimit>
+    </package>
+    <package name="multitenancy-medium">
+        <users>
+            <limit>50</limit>
+            <charge>50</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-large">
+        <users>
+            <limit>unlimited</limit>
+            <charge>5000</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>4000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+</packages>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/notification.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/notification.xml
new file mode 100644
index 0000000..25e09e8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/notification.xml
@@ -0,0 +1,23 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!-- configure the notifications -->
+<Notifications>
+    <enabled>true</enabled>
+    <host>http://localhost/feed.xml?product={product}&amp;build={build}&amp;instance={instance.id}&amp;tenant={tenant}</host>
+</Notifications>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/pom.xml
new file mode 100644
index 0000000..e7837b0
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/pom.xml
@@ -0,0 +1,140 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>billing-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.billing.core</artifactId>
+    <version>2.1.3</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Carbon - Billing Core</name>
+
+    <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.wso2.carbon.billing.core.*,
+                        </Export-Package>
+                        <!--<Require-Bundle>
+                            drools;visibility:=reexport
+                        </Require-Bundle>-->
+                        <Import-Package>
+                            org.wso2.carbon.rule.*,
+                            org.wso2.carbon.email.sender.api,
+                            org.quartz.*; version=2.1.1,
+                            org.apache.synapse.task.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+            <plugin>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <inherited>true</inherited>
+                <configuration>
+                    <forkMode>pertest</forkMode>
+                    <argLine>-enableassertions</argLine>
+                    <testFailureIgnore>false</testFailureIgnore>
+                    <excludes>
+                        <exclude>**/CashTest.java</exclude>
+                        <exclude>**/MonthlyTriggerCalculatorTest.java</exclude>
+                        <exclude>**/RuleTest.java</exclude>
+                        <exclude>**/CarbonHome1Test.java</exclude>
+                        <exclude>**/InvoiceMsgTest.java</exclude>
+                        <exclude>**/TestUtils.java</exclude>
+                        <exclude>**/TriggerTest.java</exclude>
+                    </excludes>
+                </configuration>
+            </plugin>            
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.email.sender</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.kernel</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.backend</artifactId>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.stratos.common</artifactId>
+       </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ndatasource.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
new file mode 100644
index 0000000..6979f65
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+public class BillingConstants {
+    public static final String GROUP_ID = "BillingTasks";
+    public static final String TASK_NAME_KEY = "taskName";
+    public static final String SCHEDULER_KEY = "scheduler";
+    public static final String SCHEDULER_CONTEXT = "schedulerContext";
+    public static final String BILLING_ENGINE_KEY = "billingEngine";
+    public static final String BILLING_CONFIG = "billing-config.xml";
+    public static final String CONFIG_NS = "http://wso2.com/carbon/multitenancy/billing/config";
+    public static final String TRIGGER_CALCULATOR_CLASS_ATTR = "scheduleHelperClass";
+    public static final String TRIGGER_CALCULATOR_SERVICE_ATTR = "scheduleHelperService";
+    public static final String SCHEDULE_CONF_KEY = "schedule";
+    public static final String SCHEDULE_CONF_PARAM_KEY = "parameter";
+    public static final String SCHEDULE_CONF_PARAM_NAME_KEY = "name";
+    public static final String HANDLER = "handler";
+    public static final String HANDLERS = "handlers";
+    public static final String HANDLER_CLASS_ATTR = "class";
+    public static final String HANDLER_SERVICE_ATTR = "service";
+    public static final String SUBSCRIPTION_FILTER_KEY = "subscriptionFilter";
+    public static final String DB_CONFIG = "dbConfig";
+    public static final String TASKS = "tasks";
+    public static final String ATTR_ID = "id";
+    public static final String NS_PREFIX = "";
+    public static final String DBCONFIG_VALIDATION_QUERY = "validationQuery";
+    public static final String DBCONFIG_MAX_WAIT = "maxWait";
+    public static final String DBCONFIG_MIN_IDLE = "minIdle";
+    public static final String DBCONFIG_MAX_ACTIVE = "maxActive";
+    public static final String DBCONFIG_DRIVER_NAME = "driverName";
+    public static final String DBCONFIG_PASSWORD = "password";
+    public static final String DBCONFIG_USER_NAME = "userName";
+    public static final String DBCONFIG_URL = "url";
+    public static final String SUBSCRIPTION_SUBITEM = "subscription";
+    public static final String BANDWIDTH_SUBITEM = "bwOveruse";
+    public static final String STORAGE_SUBITEM = "storageOveruse";
+    public static final String CARTRIDGE_SUBITEM = "cartridgeOveruse";
+    public static final String PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-payment-received-customer.xml";
+    public static final String REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-registration-payment-received-customer.xml";
+    public static final String PAYMENT_RECEIVED_EMAIL_WSO2_FILE = "email-payment-received-wso2.xml";
+    public static final String WSO2_BILLING_DS = "WSO2BillingDS";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
new file mode 100644
index 0000000..b6f8265
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
@@ -0,0 +1,466 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.scheduler.BillingScheduler;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.email.sender.api.EmailSender;
+import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Billing engine work on billing per a seller
+ */
+public class BillingEngine {
+
+    private static Log log = LogFactory.getLog(BillingEngine.class);
+    private BillingTaskConfiguration billingTaskConfig;
+    BillingScheduler billingScheduler;
+    DataAccessObject dataAccessObject;
+
+    public BillingEngine(BillingTaskConfiguration billingTaskConfig,
+                         DataAccessObject dataAccessObject) {
+        this.billingTaskConfig = billingTaskConfig;
+        billingScheduler = new BillingScheduler(this, billingTaskConfig);
+        this.dataAccessObject = dataAccessObject;
+    }
+
+    public void scheduleBilling() throws BillingException {
+        // the logic to schedule the billing
+        SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
+        if(schedulerContext.getCronString() != null || !schedulerContext.getCronString().equals("")) {
+        	billingScheduler.scheduleNextCycle(schedulerContext);
+        } else {
+        	log.debug("Billing is not scheduled : due to undefined cron expression");
+        }
+    }
+
+    public void generateBill() throws BillingException {
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        generateBill(billingEngineContext);
+    }
+
+    public void generateBill(SchedulerContext schedulerContext) throws BillingException {
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        billingEngineContext.setSchedulerContext(schedulerContext);
+        generateBill(billingEngineContext);
+    }
+
+    public void generateBill(BillingEngineContext billingEngineContext) throws BillingException {
+
+        try {
+            beginTransaction();
+            if (billingEngineContext.getSchedulerContext() == null) {
+                SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
+                billingEngineContext.setSchedulerContext(schedulerContext);
+            }
+
+            billingEngineContext.setTaskConfiguration(billingTaskConfig);
+
+            // now iterator through all the handlers
+            List<BillingHandler> handlers = billingTaskConfig.getBillingHandlers();
+            for (BillingHandler handler : handlers) {
+                handler.execute(billingEngineContext);
+            }
+            //commit transaction
+            commitTransaction();
+        }catch (Exception e){
+            String msg = "Error occurred while generating the bill:" + e.getMessage();
+            log.error(msg, e);
+            //rollback transaction
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        
+    }
+
+    public void beginTransaction() throws BillingException {
+        dataAccessObject.beginTransaction();
+    }
+
+    public void commitTransaction() throws BillingException {
+        dataAccessObject.commitTransaction();
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        dataAccessObject.rollbackTransaction();
+    }
+
+    public List<Item> getItemsWithName(String itemName) throws BillingException {
+        List<Item> items;
+        try {
+            beginTransaction();
+            items = dataAccessObject.getItemsWithName(itemName);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item with name: " + itemName +
+                        " " + e.getMessage();
+            log.error(msg);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return items;
+    }
+
+    public int addItem(Item item) throws BillingException {
+        int itemId = 0;
+        try {
+            beginTransaction();
+            itemId = dataAccessObject.addItem(item);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding item: " + item.getName() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return itemId;
+    }
+
+    public Item getItem(int itemId) throws BillingException {
+        Item item;
+        try {
+            beginTransaction();
+            item = dataAccessObject.getItem(itemId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item with id: " + itemId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return item;
+    }
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if(tenant!=null){
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        }catch(Exception e){
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public int addSubscription(Subscription subscription) throws BillingException {
+        int subscriptionId = 0;
+        try {
+            beginTransaction();
+            subscriptionId =
+                    dataAccessObject.addSubscription(subscription,
+                            subscription.getSubscriptionPlan());
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding subscription: " + subscription.getSubscriptionPlan()+
+                            " for the customer " + subscription.getCustomer().getName() + " " + e.getMessage() ;
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptionId;
+    }
+
+    public int addPayment(Payment payment) throws BillingException {
+        int paymentId = 0;
+        try {
+            beginTransaction();
+            paymentId = dataAccessObject.addPayment(payment);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding payment record (transaction id): " + payment.getDescription() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return paymentId;
+    }
+
+    public int addRegistrationPayment(Payment payment, String usagePlan) throws BillingException {
+        int paymentId = 0;
+        try {
+            beginTransaction();
+            paymentId = dataAccessObject.addRegistrationPayment(payment, usagePlan);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding registration payment record (transaction id): " + payment.getDescription() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return paymentId;
+    }
+
+    public Invoice getLastInvoice(Customer customer) throws BillingException {
+        Invoice invoice = null;
+        try {
+            beginTransaction();
+            invoice = dataAccessObject.getLastInvoice(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting last invoice for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoice;
+    }
+
+    public List<Invoice> getAllInvoices(Customer customer) throws BillingException {
+        List<Invoice> invoices = null;
+        try {
+            beginTransaction();
+            invoices = dataAccessObject.getAllInvoices(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting all invoices for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoices;
+    }
+
+    public List<Subscription> getActiveSubscriptions(Customer customer) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions =
+                    dataAccessObject.getFilteredActiveSubscriptionsForCustomer(
+                            null, customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscriptions for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    public Subscription getActiveSubscriptionOfCustomer(int customerId) throws BillingException {
+        Subscription subscription;
+        try {
+            beginTransaction();
+            subscription =
+                    dataAccessObject.getActiveSubscriptionOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscription for customer: " + customerId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public List<Invoice> getInvoices(Customer customer) throws BillingException {
+        List<Invoice> invoices;
+        try {
+            beginTransaction();
+            invoices = dataAccessObject.getInvoices(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoices for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoices;
+    }
+
+    public Invoice getInvoice(int invoiceId) throws BillingException {
+        Invoice invoice = null;
+        try {
+            beginTransaction();
+            invoice = dataAccessObject.getInvoice(invoiceId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoice with id: " + invoiceId +
+                            " " + e.getMessage();                
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoice;
+    }
+
+    public List<Item> getBilledItems(Subscription subscription) throws BillingException {
+        List<Item> billedItems;
+        try {
+            beginTransaction();
+            billedItems = dataAccessObject.getBilledItems(subscription);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting billed items for subscription: " + subscription.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return billedItems;
+    }
+
+    public List<Subscription> getInvoiceSubscriptions(int invoiceId) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions = dataAccessObject.getInvoiceSubscriptions(invoiceId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoice subscriptions for invoice id: " + invoiceId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    public Payment getLastPayment(Customer customer) throws BillingException {
+        Payment payment;
+        try {
+            beginTransaction();
+            payment = dataAccessObject.getLastPayment(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting the last payment for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return payment;
+    }
+
+    public List<Customer> getAllCustomers() throws BillingException {
+        return CustomerUtils.getAllCustomers();
+    }
+
+    public List<OutstandingBalanceInfoBean> getAllOutstandingBalanceInfoBeans(String tenantDomain)
+            throws BillingException {
+        if(tenantDomain==null || "".equals(tenantDomain)){
+            return getAllOutstandingBalances(null);
+        }else{
+            List<Customer> customers = getCustomersWithName(tenantDomain);
+            if(customers!=null && customers.size()>0){
+                return getAllOutstandingBalances(customers.get(0));
+            }else{
+                return new ArrayList<OutstandingBalanceInfoBean>();
+            }
+        }
+    }
+
+    public List<OutstandingBalanceInfoBean> getAllOutstandingBalances(Customer preferredCustomer) throws BillingException{
+        List<Customer> customers;// = getAllCustomers();
+        List<OutstandingBalanceInfoBean> outstandingBalances = new ArrayList<OutstandingBalanceInfoBean>();
+        if(preferredCustomer!=null){
+            customers = new ArrayList<Customer>();
+            customers.add(preferredCustomer);
+        }else{
+            customers = getAllCustomers();
+        }
+        for(Customer customer : customers){
+            OutstandingBalanceInfoBean balanceBean = new OutstandingBalanceInfoBean();
+            balanceBean.setCustomerName(customer.getName());
+            Invoice invoice = getLastInvoice(customer);
+            if(invoice!=null){
+                balanceBean.setCarriedForward(invoice.getCarriedForward().toString());
+                balanceBean.setLastInvoiceDate(invoice.getDate());
+            }
+            //setting the active usage plan
+            Subscription subscription = getActiveSubscriptionOfCustomer(customer.getId());
+            if(subscription!=null){
+                balanceBean.setSubscription(subscription.getSubscriptionPlan());
+            }else{
+                balanceBean.setSubscription("Not Available");
+            }
+
+            Payment payment = getLastPayment(customer);
+            if(payment!=null){
+                balanceBean.setLastPaidAmount(payment.getAmount().toString());
+                balanceBean.setLastPaymentDate(payment.getDate());
+            }
+            outstandingBalances.add(balanceBean);
+        }
+        return outstandingBalances;
+    }
+
+    public void sendPaymentReceivedEmail(String toAddress, String emailFile,
+                                         Map<String,String> mailParameters) throws Exception {
+        String emailTemplateFile = CarbonUtils.getCarbonConfigDirPath()+ File.separator
+                                   + StratosConstants.EMAIL_CONFIG + File.separator + emailFile;
+        EmailSenderConfiguration senderConfiguration =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(emailTemplateFile);
+        EmailSender sender = new EmailSender(senderConfiguration);
+        sender.sendEmail(toAddress, mailParameters);
+    }
+    
+    public boolean addDiscount(Discount discount) throws Exception {
+        boolean added = false;
+        try {
+            beginTransaction();
+            added = dataAccessObject.addDiscount(discount);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding the discount for tenant: " + discount.getTenantId()+
+                    ". " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+
+        return added;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
new file mode 100644
index 0000000..8d97dc1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.List;
+
+public class BillingEngineContext {
+    List<Subscription> subscriptions;
+    SchedulerContext schedulerContext;
+    Customer customer;
+    BillingTaskConfiguration taskConfiguration;
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public SchedulerContext getSchedulerContext() {
+        return schedulerContext;
+    }
+
+    public void setSchedulerContext(SchedulerContext schedulerContext) {
+        this.schedulerContext = schedulerContext;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public BillingTaskConfiguration getTaskConfiguration() {
+        return taskConfiguration;
+    }
+
+    public void setTaskConfiguration(BillingTaskConfiguration taskConfiguration) {
+        this.taskConfiguration = taskConfiguration;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java
new file mode 100644
index 0000000..2aae5a4
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+@SuppressWarnings("serial")
+public class BillingException extends Exception {
+    public BillingException(String msg, Exception e) {
+        super(msg, e);
+    }
+
+    public BillingException(String msg) {
+        super(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
new file mode 100644
index 0000000..2e7e0fc
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import java.util.Map;
+
+public interface BillingHandler {
+    public void init(Map<String, String> handlerConfig) throws BillingException;
+
+    /**
+     * Performs the tasks needed to generate bill, sending bills, etc. 
+     *
+     * @param handlerContext
+     * @throws BillingException
+     */
+    public void execute(BillingEngineContext handlerContext) throws BillingException;
+}


[13/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-xsd.xsl
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-xsd.xsl b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-xsd.xsl
new file mode 100644
index 0000000..3209e7c
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/annotated-xsd.xsl
@@ -0,0 +1,850 @@
+<?xml version="1.0"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
+                xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
+    <!--
+         Created by: Jonathan Marsh <jo...@wso2.com>
+         23 October 2006
+         7 November 2006 - JM: code review and cleanup
+     -->
+    <xsl:output method="html" indent="yes" encoding="UTF-8"/>
+    <!--
+         Many schemas refer to the built-in schema types.  In order to navigate to those types, one needs
+         to know where to load the schema for schemas, hopefully a local version with this stylesheet
+         applied so the user can continue to navigate.
+      -->
+    <xsl:param name="xsd-schema-location" select="'/service-mgt/styles/XMLSchema.xsd'"/>
+
+    <!-- QName resolving functions require the targetNamespace, so stuff it in a global variable. -->
+    <xsl:variable name="targetNamespace" select="xs:schema/@targetNamespace"/>
+
+    <!-- Mozilla doesn't support the namespace axis, which makes simulating namespace declarations
+         problematic.  At least we can try alternate reconstruction methods if we know the functionality
+         isn't there.  -->
+    <xsl:variable name="supports-namespace-axis" select="count(/*/namespace::*) &gt; 0"/>
+
+    <!-- ===  Main  ========================================
+         Main template for the schema document
+     -->
+    <xsl:template match="/">
+        <html>
+            <head>
+                <title>Schema for
+                    <xsl:value-of select="xs:schema/@targetNamespace"/>
+                </title>
+                <style type="text/css">
+                    <xsl:call-template name="css"/>
+                </style>
+            </head>
+            <body>
+                <!-- use a table to ensure sidebars longer than their associated tag don't run into the following sidebar.
+                        CSS would be preferable (progressive rendering would be improved) if there were a way to do this (I can't find one.) -->
+                <table cellpadding="0" cellspacing="0">
+                    <xsl:apply-templates select="xs:schema"/>
+                </table>
+                <p/>
+                <hr/>
+                <table cellpadding="0" cellspacing="0" id="index">
+                    <xsl:call-template name="generate-xsd-index"/>
+                </table>
+            </body>
+        </html>
+    </xsl:template>
+    <!-- ===  Elements  ========================================
+         The following templates format elements of various flavors
+         (xs:schema, children of xs:schema, grandchildren etc. of schema, and extension elements)
+     -->
+    <xsl:template match="xs:schema">
+        <!--
+              Schema element has schema-block classes, enabling a stylesheet to style the
+              entire schema, especially useful when embedding schema in another langage (e.g. WSDL).
+          -->
+        <tr>
+            <td class="schema-block annotation-area">
+                <div class="sidebar">
+                    <xsl:call-template name="index-reference"/>
+                </div>
+            </td>
+            <td class="schema-block">
+                <div class="arrow">&#160;</div>
+            </td>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-start"/>
+                </div>
+            </td>
+        </tr>
+        <xsl:apply-templates/>
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:schema/xs:*">
+        <xsl:variable name="identifier">
+            <xsl:call-template name="schema-identifier"/>
+        </xsl:variable>
+        <tr>
+            <xsl:choose>
+                <!-- Decide which top-level schema elements get sidebars -->
+                <xsl:when test="not(self::xs:annotation or self::xs:import or self::xs:include)">
+                    <td class="schema-block annotation-area">
+                        <div class="{local-name()} sidebar sidebar-title">
+                            <xsl:if test="$identifier">
+                                <xsl:attribute name="id">
+                                    <xsl:value-of select="$identifier"/>
+                                </xsl:attribute>
+                            </xsl:if>
+                            <span class="sidebar-title-highlight">
+                                <xsl:value-of select="@name"/>
+                            </span>
+                            <xsl:text></xsl:text>
+                            <xsl:value-of select="local-name()"/>
+                            <xsl:call-template name="referenced-by"/>
+                        </div>
+                    </td>
+                    <td class="schema-block">
+                        <div class="arrow">&#160;</div>
+                    </td>
+                </xsl:when>
+                <xsl:otherwise>
+                    <td colspan="2" class="schema-block annotation-area"/>
+                </xsl:otherwise>
+            </xsl:choose>
+            <td class="schema-block source-area">
+                <div class="schema-top-level">
+                    <xsl:call-template name="element-start"/>
+                </div>
+                <div class="schema-top-level">
+                    <xsl:apply-templates/>
+                </div>
+                <div class="schema-top-level">
+                    <xsl:call-template name="element-end"/>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="xs:*">
+        <!-- Third and deeper levels of schema elements (no sidebar, therefore no table row - just a div. -->
+        <xsl:variable name="identifier">
+            <xsl:call-template name="schema-identifier"/>
+        </xsl:variable>
+        <div class="indent">
+            <xsl:if test="$identifier != ''">
+                <xsl:attribute name="id">
+                    <xsl:value-of select="$identifier"/>
+                </xsl:attribute>
+            </xsl:if>
+            <div>
+                <xsl:call-template name="element-start"/>
+            </div>
+            <xsl:apply-templates/>
+            <div>
+                <xsl:call-template name="element-end"/>
+            </div>
+        </div>
+    </xsl:template>
+    <xsl:template match="xs:schema/*[not(self::xs:*)]">
+        <!-- Top-level extension elements -->
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema-top-level extension">
+                    <xsl:call-template name="element-start">
+                        <xsl:with-param name="class" select="'markup-extension-element'"/>
+                    </xsl:call-template>
+                </div>
+                <xsl:apply-templates/>
+                <div class="extension">
+                    <xsl:call-template name="element-end">
+                        <xsl:with-param name="class" select="'markup-extension-element'"/>
+                    </xsl:call-template>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="*">
+        <!-- If we've got to here, we're dealing with non-top-level extension elements.  -->
+        <div class="indent">
+            <div class="extension">
+                <xsl:call-template name="element-start">
+                    <xsl:with-param name="class" select="'markup-extension-element'"/>
+                </xsl:call-template>
+            </div>
+            <xsl:apply-templates/>
+            <div class="extension">
+                <xsl:call-template name="element-end">
+                    <xsl:with-param name="class" select="'markup-extension-element'"/>
+                </xsl:call-template>
+            </div>
+        </div>
+    </xsl:template>
+    <!-- ===  Attributes  =========================================
+         The following templates format attributes of various flavors
+     -->
+    <xsl:template match="xs:*/@id">
+        <a name="{@id}"/>
+        <xsl:call-template name="attribute"/>
+    </xsl:template>
+    <xsl:template match="xs:*/@name">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="xs:*/@ref">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-reference"/>
+                <xsl:text>#_</xsl:text>
+                <xsl:value-of select="local-name(..)"/>
+                <xsl:text>_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="xs:*/@type | xs:*/@base | xs:*/@itemType | xs:*/@memberTypes">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="value-class">markup-name-attribute-value</xsl:with-param>
+            <xsl:with-param name="reference">
+                <xsl:call-template name="external-reference"/>
+                <xsl:text>#_type_</xsl:text>
+                <xsl:value-of select="substring-after(.,':')"/>
+            </xsl:with-param>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="xs:*/@source | xs:*/@schemaLocation">
+        <xsl:call-template name="attribute">
+            <xsl:with-param name="reference" select="."/>
+        </xsl:call-template>
+    </xsl:template>
+    <xsl:template match="@*">
+        <xsl:call-template name="attribute"/>
+    </xsl:template>
+
+    <!-- ===  Text nodes  ========================================
+         The following template formats text nodes
+     -->
+    <xsl:template match="text()[normalize-space(.) != '']">
+        <div class="markup-text-content">
+            <xsl:value-of select="."/>
+        </div>
+    </xsl:template>
+
+    <!-- ===  Comments  ========================================
+         The following template formats comment nodes
+     -->
+    <xsl:template match="xs:schema/comment()">
+        <tr>
+            <td colspan="2" class="schema-block annotation-area"/>
+            <td class="schema-block source-area">
+                <div class="schema-top-level markup-comment">
+                    <xsl:text>&lt;!--</xsl:text>
+                    <xsl:value-of select="."/>
+                    <xsl:text>--&gt;</xsl:text>
+                </div>
+            </td>
+        </tr>
+    </xsl:template>
+    <xsl:template match="comment()">
+        <div class="markup-comment indent">
+            <xsl:text>&lt;!--</xsl:text>
+            <xsl:value-of select="."/>
+            <xsl:text>--&gt;</xsl:text>
+        </div>
+    </xsl:template>
+
+    <!-- ===  Library templates  ========================================
+         Library of useful named templates
+     -->
+    <xsl:template name="css"><![CDATA[
+.schema {padding-left:5em; text-indent:-5em}
+.schema-top-level {padding-left: 6em; text-indent:-5em}
+.indent {margin-left:1em}
+.double-indent {margin-left:2em}
+.trivialText {color:gray}
+
+td {vertical-align:top; font: 100%/1.3 "Lucida Grande","Lucida Sans","Lucida Sans Unicode","trebuchet ms",verdana,sans-serif}
+.annotation-area {width:16em}
+.source-area    {font-size:80%; padding-bottom:.6em}
+.sidebar        {font-size:80%; padding-bottom:.6em; margin-bottom:2px}
+.arrow          {border-top: 1px dashed black; width:2em; position:relative; top:.5em}
+.note           {background-color:rgb(255,255,210); text-align:right; border: 1px dashed black; padding:.5em}
+.simpleType     {background-color:rgb(255,242,210); text-align:right; border: 1px dashed black; padding:.5em} 
+.complexType    {background-color:rgb(255,242,210); text-align:right; border: 1px dashed black; padding:.5em} 
+.element        {background-color:rgb(225,237,246); text-align:right; border: 1px dashed black; padding:.5em}
+.group          {background-color:rgb(225,237,246); text-align:right; border: 1px dashed black; padding:.5em} 
+.attribute      {background-color:rgb(225,246,235); text-align:right; border: 1px dashed black; padding:.5em} 
+.attributeGroup {background-color:rgb(225,246,235); text-align:right; border: 1px dashed black; padding:.5em} 
+.redefine       {background-color:rgb(255,255,210); text-align:right; border: 1px dashed black; padding:.5em} 
+.notation       {background-color:rgb(255,255,210); text-align:right; border: 1px dashed black; padding:.5em} 
+.sidebar-title  {} 
+.sidebar-title-highlight {font-weight:bold}
+.sidebar-text   {padding-top:.3em}
+ul {margin-left:1em; margin-top:0em; margin-bottom:0em}
+.referenced-item {list-style-type:square; text-align:left; margin-left:.5em}
+.referenced-list {margin-top:.5em; text-align:left}
+
+#index {margin-top:2em; margin-bottom:2em} 
+
+.markup {color:gray}
+.markup-element {color:gray; text-indent:-2em; }
+.markup-extension-element {color:navy}
+.markup-attribute {color:gray}
+.markup-extension-attribute {color:navy}
+.markup-attribute-value {}
+.markup-name-attribute-value {font-weight:bold}
+.markup-namespace {color:purple}
+.markup-namespace-uri {color:purple}
+.markup-text-content  {margin-left:-4em; text-indent:0em}
+.markup-comment  {color:green}
+]]>
+    </xsl:template>
+    <xsl:template name="attribute">
+        <xsl:param name="value-class" select="'markup-attribute-value'"/>
+        <xsl:param name="reference"/>
+        <xsl:param name="native-attribute" select="parent::xs:* and namespace-uri(.)=''"/>
+        <xsl:text></xsl:text>
+        <span>
+            <xsl:choose>
+                <xsl:when test="$native-attribute">
+                    <xsl:attribute name="class">markup-attribute</xsl:attribute>
+                </xsl:when>
+                <xsl:otherwise>
+                    <xsl:attribute name="class">markup-extension-attribute</xsl:attribute>
+                </xsl:otherwise>
+            </xsl:choose>
+            <xsl:value-of select="name(.)"/>
+        </span>
+        <span class="markup">
+            <xsl:text>="</xsl:text>
+        </span>
+        <span class="{$value-class}">
+            <xsl:choose>
+                <xsl:when test="$reference">
+                    <a href="{$reference}">
+                        <xsl:value-of select="."/>
+                    </a>
+                </xsl:when>
+                <xsl:otherwise>
+                    <xsl:value-of select="."/>
+                </xsl:otherwise>
+            </xsl:choose>
+        </span>
+        <span class="markup">
+            <xsl:text>"</xsl:text>
+        </span>
+    </xsl:template>
+    <xsl:template name="namespaces">
+        <xsl:variable name="current" select="current()"/>
+        <!-- Unfortunately Mozilla doesn't support the namespace axis, need to check for that and simulate declarations -->
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <!--
+                        When the namespace axis is present (e.g. Internet Explorer), we can simulate
+                        the namespace declarations by comparing the namespaces in scope on this element
+                        with those in scope on the parent element.  Any difference must have been the
+                        result of a namespace declaration.  Note that this doesn't reflect the actual
+                        source - it will strip out redundant namespace declarations.
+                    -->
+                <xsl:for-each select="namespace::*[. != 'http://www.w3.org/XML/1998/namespace']">
+                    <xsl:if test="not($current/parent::*[namespace::*[. = current()]])">
+                        <span class="markup-namespace">
+                            <xsl:text>xmlns</xsl:text>
+                            <xsl:if test="name() != ''">:</xsl:if>
+                            <xsl:value-of select="name()"/>
+                            <xsl:text>="</xsl:text>
+                        </span>
+                        <span class="markup-namespace-uri">
+                            <xsl:value-of select="."/>
+                        </span>
+                        <span class="markup-namespace">
+                            <xsl:text>"</xsl:text>
+                        </span>
+                    </xsl:if>
+                </xsl:for-each>
+            </xsl:when>
+            <xsl:otherwise>
+                <!--
+                        When the namespace axis isn't supported (e.g. Mozilla), we can simulate
+                        appropriate declarations from namespace elements.
+                        This currently doesn't check for namespaces on attributes.
+                        In the general case we can't reliably detect the use of QNames in content, but
+                        in the case of schema, we know which content could contain a QName and look
+                        there too.  This mechanism is rather unpleasant though, since it records
+                        namespaces where they are used rather than showing where they are declared
+                        (on some parent element) in the source.  Yukk!
+                    -->
+                <xsl:if test="namespace-uri(.) != namespace-uri(parent::*)">
+                    <span class="markup-namespace">
+                        <xsl:text>xmlns</xsl:text>
+                        <xsl:if test="substring-before(name(),':') != ''">:</xsl:if>
+                        <xsl:value-of select="substring-before(name(),':')"/>
+                        <xsl:text>="</xsl:text>
+                    </span>
+                    <span class="markup-namespace-uri">
+                        <xsl:value-of select="namespace-uri(.)"/>
+                    </span>
+                    <span class="markup-namespace">
+                        <xsl:text>"</xsl:text>
+                    </span>
+                </xsl:if>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="element-start">
+        <xsl:param name="class" select="'markup-element'"/>
+        <span class="markup">&lt;</span>
+        <span class="{$class}">
+            <xsl:value-of select="name(.)"/>
+        </span>
+        <xsl:apply-templates select="@*"/>
+        <xsl:call-template name="namespaces"/>
+        <span class="markup">
+            <xsl:if test="not(node())">
+                <xsl:text>/</xsl:text>
+            </xsl:if>
+            <xsl:text>&gt;</xsl:text>
+        </span>
+    </xsl:template>
+    <xsl:template name="element-end">
+        <xsl:param name="class" select="'markup-element'"/>
+        <xsl:if test="node()">
+            <span class="markup">
+                <xsl:text>&lt;/</xsl:text>
+            </span>
+            <span class="{$class}">
+                <xsl:value-of select="name(.)"/>
+            </span>
+            <span class="markup">
+                <xsl:text>&gt;</xsl:text>
+            </span>
+        </xsl:if>
+    </xsl:template>
+
+    <xsl:template name="schema-identifier">
+        <!-- Calculate a fragment identifier for the element this element refers to, if any -->
+        <xsl:if test="@name | @ref">
+            <xsl:choose>
+                <xsl:when
+                        test="(self::xs:attribute or self::xs:element) and not(parent::xs:schema)">
+                    <xsl:variable name="top" select="ancestor::*[parent::xs:schema]"/>
+                    <xsl:variable name="toptype">
+                        <xsl:choose>
+                            <xsl:when test="$top[self::xs:complexType or self::xs:simpleType]">type
+                            </xsl:when>
+                            <xsl:otherwise>
+                                <xsl:value-of select="local-name($top)"/>
+                            </xsl:otherwise>
+                        </xsl:choose>
+                    </xsl:variable>
+                    <xsl:text>_local</xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                    <xsl:text>_</xsl:text>
+                    <xsl:value-of select="$toptype"/>
+                    <xsl:text>_</xsl:text>
+                    <xsl:value-of select="$top/@name"/>
+                </xsl:when>
+                <xsl:when test="local-name()='complexType' or local-name()='simpleType'">_type
+                </xsl:when>
+                <xsl:otherwise>
+                    <xsl:text>_</xsl:text>
+                    <xsl:value-of select="local-name()"/>
+                </xsl:otherwise>
+            </xsl:choose>
+            <xsl:text>_</xsl:text>
+            <xsl:value-of select="@name | @ref"/>
+        </xsl:if>
+    </xsl:template>
+
+    <xsl:template name="componentListItem">
+        <xsl:variable name="typeIdentifier">
+            <xsl:choose>
+                <xsl:when test="self::xs:complexType or self::xs:simpleType">type</xsl:when>
+                <xsl:otherwise>
+                    <xsl:value-of select="local-name()"/>
+                </xsl:otherwise>
+            </xsl:choose>
+        </xsl:variable>
+        <xsl:if test="position()>1">
+            <xsl:text>,</xsl:text>
+        </xsl:if>
+        <a href="#_{$typeIdentifier}_{@name}">
+            <xsl:value-of select="@name"/>
+        </a>
+    </xsl:template>
+    <xsl:template name="localComponentListItem">
+        <xsl:variable name="typeIdentifier" select="local-name()"/>
+        <xsl:variable name="top" select="ancestor::*[parent::xs:schema]"/>
+        <xsl:variable name="toptype">
+            <xsl:choose>
+                <xsl:when test="$top[self::xs:complexType or self::xs:simpleType]">type</xsl:when>
+                <xsl:otherwise>
+                    <xsl:value-of select="local-name($top)"/>
+                </xsl:otherwise>
+            </xsl:choose>
+        </xsl:variable>
+        <xsl:variable name="tnsName">
+            <xsl:choose>
+                <xsl:when test="contains(@name, ':') and namespace::*[. = $targetNamespace and name(.) =
+					substring-before(@name,':')]">
+                    <xsl:value-of select="substring-after(@name,':')"/>
+                </xsl:when>
+                <xsl:otherwise>
+                    <xsl:value-of select="@name"/>
+                </xsl:otherwise>
+            </xsl:choose>
+        </xsl:variable>
+        <xsl:if test="position()>1">
+            <xsl:text>,</xsl:text>
+        </xsl:if>
+        <a href="#_local{$typeIdentifier}_{$toptype}_{$top/@name}_{@name}">
+            <xsl:value-of select="$tnsName"/>
+        </a>
+        <span class="trivialText">of the</span>
+        <xsl:value-of select="$top/@name"/>
+        <xsl:text></xsl:text>
+        <span class="trivialText">
+            <xsl:value-of select="local-name($top)"/>
+        </span>
+    </xsl:template>
+    <xsl:template name="insert-reference">
+        <xsl:if test="self::xs:attribute">
+            <xsl:variable name="top" select="ancestor::*[parent::xs:schema]"/>
+            <xsl:variable name="toptype">
+                <xsl:choose>
+                    <xsl:when test="$top[self::xs:complexType or self::xs:simpleType]">type
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <xsl:value-of select="local-name($top)"/>
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:variable>
+            <a href="#_localattribute_{$toptype}_{$top/@name}_{@name | @ref}">
+                <xsl:value-of select="@name | @ref"/>
+            </a>
+            <xsl:text>local attribute of the</xsl:text>
+        </xsl:if>
+        <xsl:for-each select="ancestor-or-self::xs:*[last() - 1]">
+            <xsl:variable name="type">
+                <xsl:choose>
+                    <xsl:when test="self::xs:complexType or self::xs:simpleType">type</xsl:when>
+                    <xsl:otherwise>
+                        <xsl:value-of select="local-name(.)"/>
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:variable>
+            <a href="#_{$type}_{@name}">
+                <xsl:value-of select="@name"/>
+            </a>
+            <xsl:text></xsl:text>
+            <xsl:value-of select="local-name(.)"/>
+        </xsl:for-each>
+    </xsl:template>
+    <xsl:template name="referenced-by">
+        <xsl:variable name="target" select="@name"/>
+        <xsl:if test="parent::xs:schema">
+            <div class="sidebar-text">
+                <xsl:variable name="extended-by" select="ancestor::xs:schema//xs:extension[substring-after(@base | @type | @ref |
+					@itemType,':') = $target]"/>
+                <xsl:if test="count($extended-by) > 0">
+                    <div class="referenced-list">Extended by:</div>
+                    <ul>
+                        <xsl:for-each select="$extended-by">
+                            <xsl:sort select="@base | @type | @ref | @itemType"/>
+                            <li class="referenced-item">
+                                <xsl:call-template name="insert-reference"/>
+                            </li>
+                        </xsl:for-each>
+                    </ul>
+                </xsl:if>
+                <xsl:variable name="restricted-by" select="ancestor::xs:schema//xs:restriction[substring-after(@base | @type | @ref |
+					@itemType,':') = $target]"/>
+                <xsl:if test="count($restricted-by) > 0">
+                    <div class="referenced-list">Restricted by:</div>
+                    <ul>
+                        <xsl:for-each select="$restricted-by">
+                            <xsl:sort select="@base | @type | @ref | @itemType"/>
+                            <li class="referenced-item">
+                                <xsl:call-template name="insert-reference"/>
+                            </li>
+                        </xsl:for-each>
+                    </ul>
+                </xsl:if>
+                <xsl:variable name="referenced-by" select="ancestor::xs:schema//xs:*[not(self::xs:extension) and
+					not(self::xs:restriction)][substring-after(@base | @type | @ref | @itemType,':')
+					= $target]"/>
+                <xsl:if test="count($referenced-by) > 0">
+                    <div class="referenced-list">Referenced by:</div>
+                    <ul>
+                        <xsl:for-each select="$referenced-by">
+                            <xsl:sort select="@base | @type | @ref | @itemType"/>
+                            <li class="referenced-item">
+                                <xsl:call-template name="insert-reference"/>
+                            </li>
+                        </xsl:for-each>
+                    </ul>
+                </xsl:if>
+                <xsl:call-template name="additional-references">
+                    <xsl:with-param name="target" select="$target"/>
+                </xsl:call-template>
+            </div>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="additional-references">
+        <xsl:param name="target"/>
+        <!-- override this template to list additonal references -->
+    </xsl:template>
+    <xsl:template name="external-reference">
+        <xsl:choose>
+            <xsl:when test="$supports-namespace-axis">
+                <xsl:if test="not(../namespace::*[. = $targetNamespace and name(.) =
+					substring-before(current(),':')])">
+                    <xsl:variable name="prefix" select="substring-before(.,':')"/>
+                    <xsl:variable name="uri" select="../namespace::*[name(.) = $prefix]"/>
+                    <xsl:choose>
+                        <xsl:when test="$uri = 'http://www.w3.org/2001/XMLSchema'">
+                            <xsl:value-of select="$xsd-schema-location"/>
+                        </xsl:when>
+                        <xsl:otherwise>
+                            <xsl:value-of
+                                    select="ancestor::xs:schema/xs:import[@namespace=$uri]/@schemaLocation"/>
+                        </xsl:otherwise>
+                    </xsl:choose>
+                </xsl:if>
+            </xsl:when>
+            <xsl:otherwise>
+                <xsl:choose>
+                    <!-- Take a wild guess at the most commonly used type prefixes -->
+                    <xsl:when
+                            test="substring-before(current(),':') = 'xs' or substring-before(current(),':') = 'xsd'">
+                        <xsl:value-of select="$xsd-schema-location"/>
+                    </xsl:when>
+                    <xsl:otherwise>
+                        <!-- The link will be broken.  Bad Mozilla! -->
+                    </xsl:otherwise>
+                </xsl:choose>
+            </xsl:otherwise>
+        </xsl:choose>
+    </xsl:template>
+    <xsl:template name="generate-xsd-index">
+        <xsl:if test="xs:schema/xs:complexType">
+            <tr>
+                <td id="complexType-list" class="annotation-area">
+                    <div class="complexType sidebar sidebar-title-highlight">Index of complexTypes
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:complexType">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/xs:simpleType">
+            <tr>
+                <td id="simpleType-list" class="annotation-area">
+                    <div class="simpleType sidebar sidebar-title-highlight">Index of simpleTypes
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:simpleType">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/xs:element">
+            <tr>
+                <td id="global-element-list" class="annotation-area">
+                    <div class="element sidebar sidebar-title-highlight">Index of global elements
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:element">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/*//xs:element[@name]">
+            <tr>
+                <td id="local-element-list" class="annotation-area">
+                    <div class="element sidebar sidebar-title-highlight">Index of local elements
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/*//xs:element[@name]">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="localComponentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/xs:attribute">
+            <tr>
+                <td id="global-attribute-list" class="annotation-area">
+                    <div class="attribute sidebar sidebar-title-highlight">Index of global
+                        attributes
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:attribute">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/*//xs:attribute[@name]">
+            <tr>
+                <td id="local-attribute-list" class="annotation-area">
+                    <div class="attribute sidebar sidebar-title-highlight">Index of local attributes
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/*//xs:attribute[@name]">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="localComponentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/xs:group">
+            <tr>
+                <td id="model-group-list" class="annotation-area">
+                    <div class="group sidebar sidebar-title-highlight">Index of model groups</div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:group">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+        <xsl:if test="xs:schema/xs:attributeGroup">
+            <tr>
+                <td id="attributeGroup-list" class="annotation-area">
+                    <div class="attributeGroup sidebar sidebar-title-highlight">Index of attribute
+                        groups
+                    </div>
+                </td>
+                <td>
+                    <div class="arrow">&#160;</div>
+                </td>
+                <td class="source-area">
+                    <xsl:for-each select="xs:schema/xs:attributeGroup">
+                        <xsl:sort select="@name"/>
+                        <xsl:call-template name="componentListItem"/>
+                    </xsl:for-each>
+                </td>
+            </tr>
+        </xsl:if>
+    </xsl:template>
+    <xsl:template name="index-reference">
+        <div class="note sidebar-text">See the
+            <a href="#index">index</a>
+            of
+            <xsl:variable name="ss1">
+                <xsl:if test="xs:complexType">
+                    <a href="#complexType-list">complexTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss2">
+                <xsl:copy-of select="$ss1"/>
+                <xsl:if test="xs:simpleType">
+                    <xsl:if test="$ss1!=''">,</xsl:if>
+                    <a href="#simpleType-list">simpleTypes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss3">
+                <xsl:copy-of select="$ss2"/>
+                <xsl:if test="xs:element">
+                    <xsl:if test="$ss2!=''">,</xsl:if>
+                    <a href="#global-element-list">global elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss4">
+                <xsl:copy-of select="$ss3"/>
+                <xsl:if test="*//xs:element[@name]">
+                    <xsl:if test="$ss3!=''">,</xsl:if>
+                    <a href="#local-element-list">local elements</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss5">
+                <xsl:copy-of select="$ss4"/>
+                <xsl:if test="xs:attribute">
+                    <xsl:if test="$ss4!=''">,</xsl:if>
+                    <a href="#global-attribute-list">global attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss6">
+                <xsl:copy-of select="$ss5"/>
+                <xsl:if test="*//xs:attribute[@name]">
+                    <xsl:if test="$ss5!=''">,</xsl:if>
+                    <a href="#local-attribute-list">local attributes</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss7">
+                <xsl:copy-of select="$ss6"/>
+                <xsl:if test="xs:group">
+                    <xsl:if test="$ss6!=''">,</xsl:if>
+                    <a href="#model-group-list">model groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:variable name="ss8">
+                <xsl:copy-of select="$ss7"/>
+                <xsl:if test="xs:attributeGroup">
+                    <xsl:if test="$ss7!=''">,</xsl:if>
+                    <a href="#attributeGroup-list">attribute groups</a>
+                </xsl:if>
+            </xsl:variable>
+            <xsl:copy-of select="$ss8"/>
+            <xsl:text>defined in this schema.</xsl:text>
+        </div>
+    </xsl:template>
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/atom.xsl
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/atom.xsl b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/atom.xsl
new file mode 100644
index 0000000..7ce7e04
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/atom.xsl
@@ -0,0 +1,130 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+    <xsl:output method="html"/>
+
+    <xsl:template match="ns1:feed" xmlns:ns1="http://www.w3.org/2005/Atom">
+        <html>
+            <head>
+                <title>
+                    <xsl:value-of select="ns2:title" xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                </title>
+                <style media="all" lang="en" type="text/css">
+                    :root:before, :root:before {
+                    font: 80% "Lucida Grande", Verdana, Lucida, Helvetica, Arial, sans-serif;
+                    font-size:70%;
+                    content: "This data file is meant to be read in a XML Atom reader. See document
+                    source."
+                    }
+                    .AtomTitle
+                    {
+                    display: block;
+                    font-size:200%;
+                    font-weight:bolder;
+                    color:#436976;
+                    text-decoration:none;
+                    border-bottom: 20px solid #dee7ec;
+                    }
+                    .Entry
+                    {
+                    border-width: 2px;
+                    border-color: #336699;
+                    border-style: solid;
+                    width: 500px;
+                    }
+                    .Title
+                    {
+                    background-color: #436976;
+                    color: #FFFFFF;
+                    font-size: 1.4em;
+                    font-family: Verdana;
+                    font-size: 9pt;
+                    font-weight: bold;
+                    padding-left: 5px;
+                    padding-top: 5px;
+                    padding-bottom: 5px;
+                    }
+                    .Title A:visited
+                    {
+                    color: #FFFFFF;
+                    text-decoration: underline;
+                    }
+                    .Title A:link
+                    {
+                    color: #FFFFFF;
+                    text-decoration: underline;
+                    }
+                    .Title A:hover
+                    {
+                    color: #FFFF00;
+                    text-decoration: none;
+                    }
+                    .Summary
+                    {
+                    color: #000000;
+                    font-family: Verdana;
+                    font-size: 9pt;
+                    padding-left: 5px;
+                    padding-top: 5px;
+                    padding-bottom: 5px;
+                    padding-right: 5px;
+                    }
+                </style>
+            </head>
+            <body>
+                <div class="AtomTitle">
+                    <xsl:value-of select="ns2:title" xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                </div>
+                <br/>
+
+                <xsl:for-each select="ns2:entry" xmlns:ns2="http://www.w3.org/2005/Atom">
+
+                    <div class="Entry">
+                        <div class="Title">
+                            <a>
+                                <xsl:attribute name="href">
+                                    <xsl:value-of select="ns2:link/@href"
+                                                  xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                                </xsl:attribute>
+                                <xsl:value-of select="ns2:title"
+                                              xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                            </a>
+                            <xsl:text>&#160;&#160;&#160;&#160;</xsl:text>
+                            <xsl:value-of select="ns2:updated"
+                                          xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                        </div>
+                        <div class="Summary">
+                            <xsl:choose>
+                                <xsl:when test="ns2:summary"
+                                          xmlns:ns2="http://www.w3.org/2005/Atom">
+                                    <b>Summary:</b>
+                                    <xsl:value-of select="ns2:summary"
+                                                  xmlns:ns2="http://www.w3.org/2005/Atom"/>
+                                </xsl:when>
+                            </xsl:choose>
+
+                        </div>
+                    </div>
+                    <br/>
+
+                </xsl:for-each>
+            </body>
+        </html>
+    </xsl:template>
+
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/datatypes.dtd
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/datatypes.dtd b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/datatypes.dtd
new file mode 100644
index 0000000..cd47625
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/datatypes.dtd
@@ -0,0 +1,216 @@
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<!--
+        DTD for XML Schemas: Part 2: Datatypes
+        $Id: datatypes.dtd,v 1.23 2001/03/16 17:36:30 ht Exp $
+        Note this DTD is NOT normative, or even definitive. - - the
+        prose copy in the datatypes REC is the definitive version
+        (which shouldn't differ from this one except for this comment
+        and entity expansions, but just in case)
+  -->
+<!--
+        This DTD cannot be used on its own, it is intended
+        only for incorporation in XMLSchema.dtd, q.v.
+  -->
+<!-- Define all the element names, with optional prefix -->
+<!ENTITY % simpleType "%p;simpleType">
+<!ENTITY % restriction "%p;restriction">
+<!ENTITY % list "%p;list">
+<!ENTITY % union "%p;union">
+<!ENTITY % maxExclusive "%p;maxExclusive">
+<!ENTITY % minExclusive "%p;minExclusive">
+<!ENTITY % maxInclusive "%p;maxInclusive">
+<!ENTITY % minInclusive "%p;minInclusive">
+<!ENTITY % totalDigits "%p;totalDigits">
+<!ENTITY % fractionDigits "%p;fractionDigits">
+<!ENTITY % length "%p;length">
+<!ENTITY % minLength "%p;minLength">
+<!ENTITY % maxLength "%p;maxLength">
+<!ENTITY % enumeration "%p;enumeration">
+<!ENTITY % whiteSpace "%p;whiteSpace">
+<!ENTITY % pattern "%p;pattern">
+<!--
+        Customisation entities for the ATTLIST of each element
+        type. Define one of these if your schema takes advantage
+        of the anyAttribute='##other' in the schema for schemas
+  -->
+<!ENTITY % simpleTypeAttrs "">
+<!ENTITY % restrictionAttrs "">
+<!ENTITY % listAttrs "">
+<!ENTITY % unionAttrs "">
+<!ENTITY % maxExclusiveAttrs "">
+<!ENTITY % minExclusiveAttrs "">
+<!ENTITY % maxInclusiveAttrs "">
+<!ENTITY % minInclusiveAttrs "">
+<!ENTITY % totalDigitsAttrs "">
+<!ENTITY % fractionDigitsAttrs "">
+<!ENTITY % lengthAttrs "">
+<!ENTITY % minLengthAttrs "">
+<!ENTITY % maxLengthAttrs "">
+<!ENTITY % enumerationAttrs "">
+<!ENTITY % whiteSpaceAttrs "">
+<!ENTITY % patternAttrs "">
+<!-- Define some entities for informative use as attribute
+        types -->
+<!ENTITY % URIref "CDATA">
+<!ENTITY % XPathExpr "CDATA">
+<!ENTITY % QName "NMTOKEN">
+<!ENTITY % QNames "NMTOKENS">
+<!ENTITY % NCName "NMTOKEN">
+<!ENTITY % nonNegativeInteger "NMTOKEN">
+<!ENTITY % boolean "(true|false)">
+<!ENTITY % simpleDerivationSet "CDATA">
+<!--
+        #all or space-separated list drawn from derivationChoice
+  -->
+<!--
+        Note that the use of 'facet' below is less restrictive
+        than is really intended:  There should in fact be no
+        more than one of each of minInclusive, minExclusive,
+        maxInclusive, maxExclusive, totalDigits, fractionDigits,
+        length, maxLength, minLength within datatype,
+        and the min- and max- variants of Inclusive and Exclusive
+        are mutually exclusive. On the other hand,  pattern and
+        enumeration may repeat.
+  -->
+<!ENTITY % minBound "(%minInclusive; | %minExclusive;)">
+<!ENTITY % maxBound "(%maxInclusive; | %maxExclusive;)">
+<!ENTITY % bounds "%minBound; | %maxBound;">
+<!ENTITY % numeric "%totalDigits; | %fractionDigits;">
+<!ENTITY % ordered "%bounds; | %numeric;">
+<!ENTITY % unordered "%pattern; | %enumeration; | %whiteSpace; | %length; |
+   %maxLength; | %minLength;">
+<!ENTITY % facet "%ordered; | %unordered;">
+<!ENTITY % facetAttr "value CDATA #REQUIRED
+        id ID #IMPLIED">
+<!ENTITY % fixedAttr "fixed %boolean; #IMPLIED">
+<!ENTITY % facetModel "(%annotation;)?">
+<!ELEMENT %simpleType; ((%annotation;)?, (%restriction; | %list; | %union;))>
+<!ATTLIST %simpleType;
+	name %NCName; #IMPLIED
+	final %simpleDerivationSet; #IMPLIED
+	id ID #IMPLIED
+	%simpleTypeAttrs; 
+>
+<!-- name is required at top level -->
+<!ELEMENT %restriction; ((%annotation;)?, (%restriction1; | ((%simpleType;)?, (%facet;)*)), (%attrDecls;))>
+<!ATTLIST %restriction;
+	base %QName; #IMPLIED
+	id ID #IMPLIED
+	%restrictionAttrs; 
+>
+<!--
+        base and simpleType child are mutually exclusive,
+        one is required.
+
+        restriction is shared between simpleType and
+        simpleContent and complexContent (in XMLSchema.xsd).
+        restriction1 is for the latter cases, when this
+        is restricting a complex type, as is attrDecls.
+  -->
+<!ELEMENT %list; ((%annotation;)?, (%simpleType;)?)>
+<!ATTLIST %list;
+	itemType %QName; #IMPLIED
+	id ID #IMPLIED
+	%listAttrs; 
+>
+<!--
+        itemType and simpleType child are mutually exclusive,
+        one is required
+  -->
+<!ELEMENT %union; ((%annotation;)?, (%simpleType;)*)>
+<!ATTLIST %union;
+	id ID #IMPLIED
+	memberTypes %QNames; #IMPLIED
+	%unionAttrs; 
+>
+<!--
+        At least one item in memberTypes or one simpleType
+        child is required
+  -->
+<!ELEMENT %maxExclusive; %facetModel;>
+<!ATTLIST %maxExclusive;
+	%facetAttr; 
+	%fixedAttr; 
+	%maxExclusiveAttrs; 
+>
+<!ELEMENT %minExclusive; %facetModel;>
+<!ATTLIST %minExclusive;
+	%facetAttr; 
+	%fixedAttr; 
+	%minExclusiveAttrs; 
+>
+<!ELEMENT %maxInclusive; %facetModel;>
+<!ATTLIST %maxInclusive;
+	%facetAttr; 
+	%fixedAttr; 
+	%maxInclusiveAttrs; 
+>
+<!ELEMENT %minInclusive; %facetModel;>
+<!ATTLIST %minInclusive;
+	%facetAttr; 
+	%fixedAttr; 
+	%minInclusiveAttrs; 
+>
+<!ELEMENT %totalDigits; %facetModel;>
+<!ATTLIST %totalDigits;
+	%facetAttr; 
+	%fixedAttr; 
+	%totalDigitsAttrs; 
+>
+<!ELEMENT %fractionDigits; %facetModel;>
+<!ATTLIST %fractionDigits;
+	%facetAttr; 
+	%fixedAttr; 
+	%fractionDigitsAttrs; 
+>
+<!ELEMENT %length; %facetModel;>
+<!ATTLIST %length;
+	%facetAttr; 
+	%fixedAttr; 
+	%lengthAttrs; 
+>
+<!ELEMENT %minLength; %facetModel;>
+<!ATTLIST %minLength;
+	%facetAttr; 
+	%fixedAttr; 
+	%minLengthAttrs; 
+>
+<!ELEMENT %maxLength; %facetModel;>
+<!ATTLIST %maxLength;
+	%facetAttr; 
+	%fixedAttr; 
+	%maxLengthAttrs; 
+>
+<!-- This one can be repeated -->
+<!ELEMENT %enumeration; %facetModel;>
+<!ATTLIST %enumeration;
+	%facetAttr; 
+	%enumerationAttrs; 
+>
+<!ELEMENT %whiteSpace; %facetModel;>
+<!ATTLIST %whiteSpace;
+	%facetAttr; 
+	%fixedAttr; 
+	%whiteSpaceAttrs; 
+>
+<!-- This one can be repeated -->
+<!ELEMENT %pattern; %facetModel;>
+<!ATTLIST %pattern;
+	%facetAttr; 
+	%patternAttrs; 
+>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/rss.xsl
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/rss.xsl b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/rss.xsl
new file mode 100644
index 0000000..be86baf
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/styles/rss.xsl
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+    <xsl:output method="html"/>
+    <xsl:template match="rss/channel">
+        <html>
+            <head>
+                <title>
+                    <xsl:value-of select="title"/>
+                </title>
+                <style media="all" lang="en" type="text/css">
+                    :root:before, :root:before {
+                    font: 80% "Lucida Grande", Verdana, Lucida, Helvetica, Arial, sans-serif;
+                    font-size:70%;
+                    content: "This data file is meant to be read in a XML feed reader. See document
+                    source."
+                    }
+                    .ChannelTitle
+                    {
+                    display: block;
+                    font-size:200%;
+                    font-weight:bolder;
+                    color:#436976;
+                    text-decoration:none;
+                    border-bottom: 20px solid #dee7ec;
+                    }
+                    .ArticleEntry
+                    {
+                    border-width: 2px;
+                    border-color: #336699;
+                    border-style: solid;
+                    width: 500px;
+                    }
+                    .ArticleTitle
+                    {
+                    background-color: #436976;
+                    color: #FFFFFF;
+                    font-size: 1.4em;
+                    font-family: Verdana;
+                    font-size: 9pt;
+                    font-weight: bold;
+                    padding-left: 5px;
+                    padding-top: 5px;
+                    padding-bottom: 5px;
+                    }
+                    .ArticleTitle A:visited
+                    {
+                    color: #FFFFFF;
+                    text-decoration: underline;
+                    }
+                    .ArticleTitle A:link
+                    {
+                    color: #FFFFFF;
+                    text-decoration: underline;
+                    }
+                    .ArticleTitle A:hover
+                    {
+                    color: #FFFF00;
+                    text-decoration: none;
+                    }
+                    .ArticleDescription
+                    {
+                    color: #000000;
+                    font-family: Verdana;
+                    font-size: 9pt;
+                    padding-left: 5px;
+                    padding-top: 5px;
+                    padding-bottom: 5px;
+                    padding-right: 5px;
+                    }
+                </style>
+            </head>
+            <body>
+                <xsl:apply-templates select="title"/>
+                <xsl:apply-templates select="item"/>
+            </body>
+        </html>
+    </xsl:template>
+    <xsl:template match="title">
+        <div class="ChannelTitle">
+            <xsl:value-of select="text()"/>
+        </div>
+        <br/>
+    </xsl:template>
+    <xsl:template match="item">
+        <div class="ArticleEntry">
+            <div class="ArticleTitle">
+                <a href="{link}">
+                    <xsl:value-of select="title"/>
+                </a>
+                <xsl:text>&#160;&#160;&#160;&#160;</xsl:text>
+                <xsl:value-of select="pubDate"/>
+            </div>
+            <div class="ArticleDescription">
+                <b>Description:</b>
+                <xsl:value-of select="description"/>
+            </div>
+        </div>
+        <br/>
+    </xsl:template>
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe.jsp
new file mode 100644
index 0000000..a3d65c1
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe.jsp
@@ -0,0 +1,303 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient" %>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.PolicyDefinition" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.ResourceBundle" %>
+<jsp:include page="../dialog/display_messages.jsp"/>
+
+
+<%
+    response.setHeader("Cache-Control", "no-cache");
+    String cartridgeType = request.getParameter("cartridgeType");
+    String multiTenantValue = request.getParameter("multiTenant");
+    String cartridgeProvider = request.getParameter("cartridgeProvider");
+    boolean multiTenant = Boolean.valueOf(multiTenantValue);
+    String item = request.getParameter("item");
+    
+    PolicyDefinition[] policyDefinitions = null;
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+          (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+    
+    boolean internalRepoFeatureEnabled = false;
+
+    try{
+        client = new CartridgeAdminClient(cookie, backendServerURL, configContext,request.getLocale());
+        policyDefinitions = client.getPolicyDefinitions();
+        
+        if (policyDefinitions == null || policyDefinitions.length == 0) {
+        	throw new IllegalStateException("Policy Definitions not found.");
+        }
+        internalRepoFeatureEnabled = client.isFeatureEnabled("feature.internalrepo.enabled");
+    }catch (Exception e) {
+        response.setStatus(500);
+        CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
+        session.setAttribute(CarbonUIMessage.ID, uiMsg);
+        %>
+            <jsp:include page="../admin/error.jsp"/>
+        <%
+        return;
+    }
+
+%>
+<fmt:bundle basename="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources">
+<carbon:breadcrumb
+    label="subscribe"
+    resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources"
+    topPage="true"
+    request="<%=request%>"/>
+<div id="middle">
+<%if(cartridgeType != null) {%>
+    <h2><fmt:message key="subscribe.to"><fmt:param value="<%= cartridgeType%>"/></fmt:message></h2>
+<%} else {%>
+	<h2><fmt:message key="subscribe.new.cartridge"/></h2>
+    <p>&nbsp;</p>
+<%} %>
+<div id="workArea">
+    <form id="subscribeForm" name="subscribeToCartridge">
+        <table id="subscribeToCartridgeTbl" width="100%" class="styledLeft">
+	        <thead>
+	        <tr>
+	            <th>
+	                <fmt:message key="cartridge.information"/>
+	            </th>
+	        </tr>
+	        </thead>
+            <tbody>
+            <tr>
+            <td class="nopadding">
+           	<table class="normal-nopadding" cellspacing="0">
+            <tbody>
+                <tr>
+                	<!-- Keep 30% width to give more space for inputs -->
+                    <td style="width: 30%"><label>Cartridge Type</label><span class="required">*</span></td>
+                    <td>
+                        <span><%=cartridgeType%></span>
+                        <input name="cartridge_type" type="hidden" value="<%=cartridgeType%>"/>
+                        <input name="cartridge_provider" type="hidden" value="<%=cartridgeProvider%>"/>
+                    </td>
+                </tr>
+                <tr>
+                    <td><label for="cartridge_alias">Alias</label><span class="required">*</span></td>
+                    <td><input id="cartridge_alias" name="cartridge_alias" type="text" style="width: 400px" maxlength="300" /></td>
+                </tr>
+                <%if((cartridgeProvider != null && !cartridgeProvider.equalsIgnoreCase("data")) && !multiTenant) {%>
+                    <tr>
+                    	<td><label for="policy">Policy</label><span class="required">*</span></td>
+						<td style="border: 0;"><select name="policy" id="policy">
+								<%
+									for (PolicyDefinition policy : policyDefinitions) {
+												
+								%>
+								<option value="<%=policy.getName()%>" <%if (policy.getDefaultPolicy()) {%>selected="selected"<%}%>>
+									<%=policy.getDescription()%>
+								</option>
+								<%
+									}
+								%>
+						</select></td>
+                    </tr>
+                <%}%>
+                <%if((cartridgeProvider != null && !cartridgeProvider.equalsIgnoreCase("data"))) {%>
+               		<tr>
+                        <td colspan="2" class="middle-header"><fmt:message key="repository.information"/></td>
+                    </tr>
+                	<%if(internalRepoFeatureEnabled) {%>
+                	<tr>
+                        <td><label for="internalRepo" id="internalRepoLabel">Use Internal Repository</label><span class="required">*</span></td>
+                        <td>
+                        	<input name="internalRepo" type="radio" value="yes" /> Yes
+							<input name="internalRepo" type="radio" value="no" checked="checked" /> No
+						</td>
+                    </tr>
+                    <%} %>
+                    <tr class="repoDetails">
+                        <td><label for="repoType" id="repoTypeLabel">Repository Type</label><span class="required">*</span></td>
+                        <td>
+                        	<input name="repoType" type="radio" value="public" checked="checked" /> Public
+							<input name="repoType" type="radio" value="private" /> Private
+						</td>
+                    </tr>
+                    <tr class="repoDetails">
+                        <td><label for="repo_url" id="repoLabel">GIT repository URL: (http:// or https://)</label><span class="required">*</span></td>
+                        <td><input id="repo_url" name="repo_url" type="text" style="width: 400px" maxlength="1000" />
+                        </td>
+                    </tr>
+                    <tr class="repoDetails repoCredentials">
+                        <td><label for="repo_username" id="repo_usernameLabel">GIT Repository Username</label><span class="required" style="display: none;">*</span></td>
+                        <td><input id="repo_username" name="repo_username" type="text" style="width: 400px" maxlength="500" autocomplete="off" /></td>
+                    </tr>
+                    <tr class="repoDetails repoCredentials">
+                        <td><label for="repo_password" id="repo_passwordLabel">GIT Repository Password</label><span class="required" style="display: none;">*</span></td>
+                        <td><input id="repo_password" name="repo_password" type="password" style="width: 400px" maxlength="500" autocomplete="off" /></td>
+                    </tr>
+                    <tr class="repoDetails" id="testConnectionRow">
+                    	<td></td>
+                    	<td>
+                    		<input id="testGitButton" type="button" class="button" value="Test Connection"
+                        		onclick="postToBEService('test_git_ajaxprocessor.jsp', jQuery('#subscribeForm').serialize(), null, '#testGitButton', validateRepository);">
+                       	</td>
+                    </tr>
+                    <tr class="dataCartridgeRow" style="display: none;">
+                        <td colspan="2" class="middle-header"><fmt:message key="cartridge.connect.information"/></td>
+                    </tr>
+                    <tr class="dataCartridgeRow" style="display: none;">
+                        <td><label for="other_cartridge_type">Connect Data Cartridge</label><span class="required">*</span></td>
+                        <td><select id="other_cartridge_type" name="other_cartridge_type" ><option value="mysql">mysql</option></select></td>
+                    </tr>
+                    <tr class="dataCartridgeRow" style="display: none;">
+                        <td><label for="other_alias">Data Cartridge Alias</label><span class="required">*</span></td>
+                        <td><input id="other_alias" name="other_alias" type="text" style="width: 400px" maxlength="300" /></td>
+                    </tr>
+                <%}%>
+            </tbody>
+            </table>
+            </td>
+        </tr>
+        <tr id="buttonRow" class="buttonRow">
+            <td>
+                <input id="subscribeButton" type="submit" class="button" value="Subscribe" />
+                <input id="subscribeCancelButton" type="button" class="button" value="Cancel" onclick="cancelSubscribe('<%=item%>');" />
+                <%if(!"data".equalsIgnoreCase(cartridgeProvider) && !multiTenant){%>
+                    <a id="showConnect" onclick="showConnectCartridge();" style="cursor: pointer;">Connect another cartridge...</a>
+                    <a id="hideConnect" onclick="hideConnectCartridge();" style="cursor: pointer; display: none;">Hide connecting cartridge fields...</a>
+                <%}%>
+            </td>
+        </tr>
+        </tbody>
+        </table>
+    </form>
+
+    <p>&nbsp;</p>
+    </div>
+
+</div>
+
+<script type="text/javascript">
+	jQuery(document).ready(
+		function() {
+			if (jQuery("#internalRepoLabel").length > 0) {
+				jQuery('input:radio[name="internalRepo"]').click(
+					function() {
+						var $this = jQuery(this);
+						if ($this.val() == "no") {
+							jQuery(".repoDetails").show();
+						} else {
+							jQuery(".repoDetails").hide();
+							jQuery("#repo_url").val("");
+							jQuery("#repo_username").val("");
+							jQuery("#repo_password").val("");
+						}
+					})
+			};
+	
+			jQuery('input:radio[name="repoType"]').click(
+				function() {
+					var $this = jQuery(this);
+					if ($this.val() == "private") {
+						jQuery(".repoCredentials .required").show();
+					} else {
+						jQuery(".repoCredentials .required").hide();
+					}
+				})
+			
+			setStratosFormSubmitFunction("#subscribeForm", validate, "subscribe_ajaxprocessor.jsp", "subscribed_cartridges.jsp", "#subscribeButton");
+		});
+
+	function validate() {
+		if (jQuery("#cartridge_alias").val().length == 0) {
+			CARBON.showErrorDialog('Please enter an alias for the cartridge.');
+			return false;
+		}
+		if (!validateRepository()) {
+			return false;
+		}
+		if (jQuery(".dataCartridgeRow").length > 0 && 
+				jQuery(".dataCartridgeRow").css("display") != "none" && jQuery("#other_alias").val().length == 0) {
+			CARBON.showErrorDialog('Please enter an alias for the data cartridge.');
+			return false;
+		}
+		return true;
+	}
+
+	function validateRepository() {
+		var repoRequired = false;
+		if (jQuery("#internalRepoLabel").length > 0) {
+			if (jQuery('input[name="internalRepo"]:checked').val() == "no") {
+				repoRequired = true;
+				if (jQuery("#repo_url").val().length == 0) {
+					CARBON.showWarningDialog('Please enter GIT repository URL.');
+					return false;
+				}
+			}
+		} else {
+			// Some cartridges do not have a repo URL
+			if (jQuery("#repo_url").length > 0) {
+				repoRequired = true;
+				if (jQuery("#repo_url").val().length == 0) {
+					CARBON.showWarningDialog('Please enter GIT repository URL.');
+					return false;
+				}
+			}
+		}
+
+		if (repoRequired && jQuery("#repoTypeLabel").length > 0
+				&& jQuery('input[name="repoType"]:checked').val() == "private") {
+			if (jQuery("#repo_username").val().length == 0) {
+				CARBON.showWarningDialog('Please enter GIT repository username.');
+				return false;
+			}
+			if (jQuery("#repo_password").val().length == 0) {
+				CARBON.showWarningDialog('Please enter GIT repository password.');
+				return false;
+			}
+		}
+		return true;
+	}
+
+	function showConnectCartridge() {
+		jQuery(".dataCartridgeRow").show();
+		jQuery("#showConnect").hide();
+		jQuery("#hideConnect").show();
+	}
+
+	function hideConnectCartridge() {
+		jQuery(".dataCartridgeRow").hide();
+		jQuery("#showConnect").show();
+		jQuery("#hideConnect").hide();
+	}
+	
+	function cancelSubscribe(item) {
+		location.href = "available_cartridges.jsp?item=" + item;
+	}
+</script>
+<script type="text/javascript" src="js/jquery.blockUI-1.33.js"></script>
+<script type="text/javascript" src="js/common.js"></script>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe_ajaxprocessor.jsp
new file mode 100644
index 0000000..6b0ec40
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribe_ajaxprocessor.jsp
@@ -0,0 +1,88 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge" %>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.SubscriptionInfo" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.ResourceBundle" %>
+<%@ page import="java.util.Map" %>
+<jsp:include page="../dialog/display_messages.jsp"/>
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle
+        .getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+          (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+    String repoUrl = "";
+    String repoUserName = "";
+    String repoPassword = "";
+    String otherCartridgeType = "";
+    String otherAlias = "";
+    String policy = null;
+    String repoType = null;
+    
+    String cartridgeType = request.getParameter("cartridge_type");
+    String cartridgeProvider = request.getParameter("cartridge_provider");
+    String cartridgeAlias = request.getParameter("cartridge_alias");
+    if(!"data".equalsIgnoreCase(cartridgeProvider)){
+        repoUrl = request.getParameter("repo_url");
+        repoUserName = request.getParameter("repo_username");
+        repoPassword = request.getParameter("repo_password");
+        otherCartridgeType = request.getParameter("other_cartridge_type");
+        otherAlias = request.getParameter("other_alias");
+        policy = request.getParameter("policy");
+        repoType = request.getParameter("repoType");
+    }
+    try{
+   		client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+   		SubscriptionInfo info = client.subscribeToCartridge(cartridgeType, cartridgeAlias, policy, repoUrl, "private".equals(repoType), repoUserName, repoPassword,
+				otherCartridgeType, otherAlias);
+   		String message = "";
+   		if (info != null && info.getHostname() != null) {
+   			message = "Successfully subscribed. Please map the host name " + info.getHostname() + " to ELB IP";
+   		} else {
+   			message = "Successfully subscribed.";
+   		}
+		//CarbonUIMessage.sendCarbonUIMessage(message, CarbonUIMessage.INFO, request);
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+	} catch (Exception e) {
+		response.setStatus(500);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+		//CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request);
+	}
+%>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges.jsp
new file mode 100644
index 0000000..4ea474b
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges.jsp
@@ -0,0 +1,174 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.CartridgeWrapper"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<%@ page import="java.util.ArrayList"%>
+
+<jsp:include page="../dialog/display_messages.jsp" />
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+    String pageNumber = request.getParameter("pageNumber");
+    if (pageNumber == null) {
+        pageNumber = "0";
+    }
+    int pageNumberInt = 0;
+    try {
+        pageNumberInt = Integer.parseInt(pageNumber);
+    } catch (NumberFormatException ignored) {
+    }
+
+    String cartridgeSearchString = request.getParameter("cartridgeSearchString");
+    if (cartridgeSearchString == null) {
+        cartridgeSearchString = "";
+    }
+    
+    // Fix issue when subscribed_cartridges_ajaxprocessor.jsp page return errors continuously 
+    String reloadCount = request.getParameter("reload");
+    if (reloadCount == null) {
+    	reloadCount = "0";
+    }
+    int reloadCountInt = 0;
+    try {
+    	reloadCountInt = Integer.parseInt(reloadCount);
+    } catch (NumberFormatException ignored) {
+    }
+    
+    if (new Boolean(request.getParameter("loginStatus"))) {
+    	// This is a login request
+    	// Initialize the reload count to zero
+    	reloadCountInt = 0;
+    }
+%>
+
+<fmt:bundle basename="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources">
+	<carbon:breadcrumb label="cartrigdes.subscribed.header" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources"
+		topPage="false" request="<%=request%>" />
+
+	<script type="text/javascript">
+		function searchCartridges() {
+			document.searchForm.submit();
+		}
+	    function showCartridgeInfo(popupID, alias) {
+	        CARBON.showPopupDialog(jQuery('#' + popupID).html(), "Cartridge Information for " + alias, 350, null, null, 400);
+	    }
+	    function unsubscribeCartridge(alias) {
+	        if (alias) {
+	            CARBON.showConfirmationDialog("<fmt:message key="cartridge.unsubscribe.prompt"></fmt:message>",
+	                                          function() {
+	                                              //location.href = './call_unsubscribe.jsp?cartridge_alias=' + alias;
+	                                              postToBEService('unsubscribe_ajaxprocessor.jsp', 'cartridge_alias=' + alias, 'subscribed_cartridges.jsp');
+	                                          }
+	                    );
+	        }
+	    }
+	    
+	    function syncRepo(alias) {
+	        if (alias) {
+            	postToBEService('sync_repo_ajaxprocessor.jsp', 'cartridge_alias=' + alias);
+	        }
+	    }
+	    
+	    function removeDomain(alias) {
+	        if (alias) {
+            	postToBEService('remove_domain_ajaxprocessor.jsp', 'cartridge_alias=' + alias, 'subscribed_cartridges.jsp');
+	        }
+	    }
+	</script>
+
+	<div id="middle">
+		<h2>
+			<fmt:message key="cartrigdes.subscribed.header" />
+		</h2>
+
+		<div id="workArea">
+			<form action="subscribed_cartridges.jsp" name="searchForm">
+				<table class="styledLeft">
+					<tr>
+						<td>
+							<table style="border: 0;">
+								<tbody>
+									<tr style="border: 0;">
+										<td style="border: 0;"><fmt:message key="search.cartrigdes" /> <input type="text"
+											name="cartridgeSearchString" value="<%=cartridgeSearchString != null ? cartridgeSearchString : ""%>" />&nbsp;
+										</td>
+										<td style="border: 0;"><a class="icon-link" href="#" style="background-image: url(images/search.gif);"
+											onclick="searchCartridges(); return false;" alt="<fmt:message key="search"/>"> </a></td>
+									</tr>
+								</tbody>
+							</table>
+						</td>
+					</tr>
+				</table>
+			</form>
+
+			<p>&nbsp;</p>
+			<div id="cartridges"></div>
+		</div>
+	</div>
+	<script type="text/javascript">
+		var refresh;
+        jQuery(document).ready(function() {
+            var refreshTable = function(){
+            	jQuery.ajax({
+                    url:'subscribed_cartridges_ajaxprocessor.jsp?pageNumber=<%=pageNumber%>&cartridgeSearchString=<%=cartridgeSearchString%>',
+                    success:function(data){
+                    	jQuery('#cartridges').html(data);
+                    },
+                    error:function(jqXHR, textStatus, errorThrown) {
+                    	reloadPage();
+                    }
+                })
+            }
+            // Call this initially
+            refreshTable();
+            refresh = setInterval(refreshTable, 15000);
+        });
+        
+        function stopRefreshTable() {
+            if (refresh) {
+                clearInterval(refresh);
+            }
+        }
+        
+        function reloadPage() {
+        	stopRefreshTable();
+        	<%
+        	if (reloadCountInt <= 1) {
+        	%>
+        	// Reload page. If the session is not there, the page should redirect to login page.
+        	location.href = 'subscribed_cartridges.jsp?reload=<%=++reloadCountInt%>';
+        	<% 
+        	}
+        	%>
+        }
+	</script>
+	<script type="text/javascript" src="js/jquery.blockUI-1.33.js"></script>
+	<script type="text/javascript" src="js/common.js"></script>
+</fmt:bundle>


[12/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges_ajaxprocessor.jsp
new file mode 100644
index 0000000..17e394b
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/subscribed_cartridges_ajaxprocessor.jsp
@@ -0,0 +1,279 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.CartridgeWrapper"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<%@ page import="java.util.ArrayList"%>
+
+<jsp:include page="../dialog/display_messages.jsp" />
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+            (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+    Cartridge[] cartridges = null;
+
+    int numberOfPages = 0;
+    String pageNumber = request.getParameter("pageNumber");
+    if (pageNumber == null) {
+        pageNumber = "0";
+    }
+    int pageNumberInt = 0;
+    try {
+        pageNumberInt = Integer.parseInt(pageNumber);
+    } catch (NumberFormatException ignored) {
+    }
+
+    String cartridgeSearchString = request.getParameter("cartridgeSearchString");
+    if (cartridgeSearchString == null) {
+        cartridgeSearchString = "";
+    }
+
+    try {
+        client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+        CartridgeWrapper cartridgeWrapper = client.getPagedSubscribedCartridges(cartridgeSearchString, pageNumberInt);
+        if (cartridgeWrapper != null) {
+        	numberOfPages = cartridgeWrapper.getNumberOfPages();
+        	cartridges = cartridgeWrapper.getCartridges();
+        }
+    } catch (Exception e) {
+        response.setStatus(500);
+        CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
+        session.setAttribute(CarbonUIMessage.ID, uiMsg);
+%>
+<jsp:include page="../admin/error.jsp" />
+<%
+	return;
+    }
+%>
+
+<fmt:bundle basename="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources">
+	<div>
+		<%
+			if (cartridges != null) {
+				String parameters = "cartridgeSearchString=" + cartridgeSearchString;
+		%>
+	
+		<carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>" page="subscribed_cartridges.jsp"
+			pageNumberParameterName="pageNumber" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources" prevKey="prev"
+			nextKey="next" parameters="<%=parameters%>" />
+		<p>&nbsp;</p>
+	
+		<form id="frmSubC" name="cartridgesForm" method="post">
+			<input type="hidden" name="pageNumber" value="<%=pageNumber%>" />
+			<table id="cartridgesTable" class="styledLeft" style="width: 100%">
+				<thead>
+					<tr>
+						<th style="width: 10%"><fmt:message key="cartridge.display.name" /></th>
+						<th style="width: 70px"><fmt:message key="cartridge.version" /></th>
+						<th style="width: 125px"><fmt:message key="cartridge.tenancymodel" /></th>
+						<th style="width: 10%"><fmt:message key="alias" /></th>
+						<th style="width: 5%"><fmt:message key="status" /></th>
+						<th style="text-align: right; padding-right: 5px; width: 125px;"><fmt:message key="instance.count" /></th>
+						<th><fmt:message key="url" /></th>
+						<th style="width: 12%"><fmt:message key="repo.url" /></th>
+						<th style="width: 8%"><fmt:message key="action" /></th>
+					</tr>
+				</thead>
+				<tbody>
+	
+					<%
+						int id = 1; // To generate ID
+					
+						for (Cartridge cartridge : cartridges) {
+							
+							String popupID = "cartridge_popup_" + id;
+							String rowStyleClass = ((id & 1) == 0) ? "tableEvenRow" : "tableOddRow";
+							
+							// Increment ID
+							id++;
+											
+							String[] accessURLs = cartridge.getAccessURLs();
+							StringBuilder urlBuilder = new StringBuilder();
+							if (accessURLs != null) {
+								for (int i = 0; i < accessURLs.length; i++) {
+									String url = accessURLs[i];
+									if (url != null) {
+										if (i > 0) {
+											urlBuilder.append("<br />");
+										}
+										urlBuilder.append("<a href=\"").append(url).append("\" target=\"_blank\">").append(url).append("</a>");
+									}
+								}
+							}
+							
+							String displayName = (cartridge.getDisplayName() != null ? cartridge.getDisplayName() : "");
+							String version = (cartridge.getVersion() != null ? cartridge.getVersion() : "");
+							String description = (cartridge.getDescription() != null ? cartridge.getDescription() : "");
+							String alias = (cartridge.getCartridgeAlias() != null ? cartridge.getCartridgeAlias() : "");
+							String status = (cartridge.getStatus() != null ? cartridge.getStatus() : "");
+							int activeInstances = cartridge.getActiveInstances();
+							String instances = cartridge.getMultiTenant() ? "N/A" : String.valueOf(activeInstances);
+							String accessURL = urlBuilder.toString();
+							String repoURL = (cartridge.getRepoURL() != null ? cartridge.getRepoURL() : "");
+							String ip = (cartridge.getIp() != null ? cartridge.getIp() : "");
+							String dbUsername = (cartridge.getDbUserName() != null ? cartridge.getDbUserName() : "");
+							String password = (cartridge.getPassword() != null ? cartridge.getPassword() : "");
+							String mappedDomain = (cartridge.getMappedDomain() != null ? cartridge.getMappedDomain() : "");
+							String policy = (cartridge.getPolicyDescription() != null ? cartridge.getPolicyDescription() : "");
+							String tenancyModel = cartridge.getMultiTenant() ? "Multi-Tenant" : "Single-Tenant";
+							
+							if (repoURL.startsWith("http")) {
+								StringBuilder repoURLBuilder = new StringBuilder();
+								repoURL = repoURLBuilder.append("<a href=\"").append(repoURL).append("\" target=\"_blank\">").append(repoURL).append("</a>").toString();
+							}
+					%>
+	
+					<tr class="<%=rowStyleClass%>">
+						<td><%=displayName%></td>
+						<td><%=version%></td>
+						<td><%=tenancyModel%></td>
+						<td><a onclick="showCartridgeInfo('<%=popupID%>', '<%=alias%>')" style="background-image:url(../admin/images/information.gif);" class="icon-link"><%=alias%></a></td>
+						<td><span <%if (!"ACTIVE".equalsIgnoreCase(status)) {%>
+							style="background-image: url(images/ajax-loading.gif); background-repeat: no-repeat; background-position: left center; padding-left: 22px;"
+							<%}%>><%=status%></span></td>
+						<td style="text-align: right;"><%=instances%></td>
+						<td><%=accessURL%></td>
+						<td><%=repoURL%></td>
+						<td><a onclick="unsubscribeCartridge('<%=alias%>');" style="background-image:url(images/unsubscribe.png);" class="icon-link">
+	                              <fmt:message key="unsubscribe"/></a>
+	                              <% if (mappedDomain.length() == 0) {	%>
+	                              	<a href="./map_domain.jsp?cartridge_alias=<%=alias%>&domain=<%=mappedDomain%>" class="icon-link">
+	                              	<fmt:message key="mapdomain"/></a>
+	                              <% } %>
+	                              <% if (repoURL.length() > 0) {	%>
+	                              	<a onclick="syncRepo('<%=alias%>');" class="icon-link">
+	                              	<fmt:message key="syncrepo"/></a>
+	                              <% } %>
+	                              <% if (mappedDomain.length() > 0) {	%>
+	                              	<a onclick="removeDomain('<%=alias%>');" class="icon-link">
+                      				<fmt:message key="removedomain"/></a>
+	                              <% } %>
+	                              <div id="<%=popupID%>" style="display: none">
+	                              	<table class="popupTable" style="width: 100%">
+	                              		<tbody>
+	                              			<tr class="tableOddRow">
+	                              				<td style="width: 40%"><fmt:message key="cartridge.display.name" /></td>
+	                              				<td><%=displayName%></td>
+	                              			</tr>
+	                              			<tr class="tableEvenRow">
+	                              				<td style="width: 40%"><fmt:message key="cartridge.version" /></td>
+	                              				<td><%=version%></td>
+	                              			</tr>
+	                              			<tr class="tableOddRow">
+	                              				<td style="width: 40%"><fmt:message key="cartridge.description" /></td>
+	                              				<td><%=description%></td>
+	                              			</tr>
+	                              			<tr class="tableEvenRow">
+	                              				<td style="width: 40%"><fmt:message key="cartridge.tenancymodel" /></td>
+	                              				<td><%=tenancyModel%></td>
+	                              			</tr>
+	                              			<tr class="tableOddRow">
+	                              				<td style="width: 40%"><fmt:message key="alias" /></td>
+	                              				<td><%=alias%></td>
+	                              			</tr>
+	                              			<tr class="tableEvenRow">
+	                              				<td style="width: 40%"><fmt:message key="status" /></td>
+	                              				<td><%=status%></td>
+	                              			</tr>
+	                              			<tr class="tableOddRow">
+	                              				<td style="width: 40%"><fmt:message key="instance.count" /></td>
+	                              				<td><%=instances%></td>
+	                              			</tr>
+	                              			<tr class="tableEvenRow">
+	                              				<td style="width: 40%"><fmt:message key="url" /></td>
+	                              				<td><%=accessURL%></td>
+	                              			</tr>
+											<% 
+											// Assign style class according to row
+											int popupRowId = 0; 
+											%>
+	                              			<% if (policy.length() > 0) { %>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="policy" /></td>
+	                              				<td><%=policy%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              			<% if (repoURL.length() > 0) { %>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="repo.url" /></td>
+	                              				<td><%=repoURL%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              			<% if (ip.length() > 0) { %>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="ip" /></td>
+	                              				<td><%=ip%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              			<% if (dbUsername.length() > 0) { %>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="username" /></td>
+	                              				<td><%=dbUsername%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              			<% if (password.length() > 0) {	%>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="password" /></td>
+	                              				<td><%=password%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              			<% if (mappedDomain.length() > 0) {	%>
+	                              			<tr class="<%=(((++popupRowId & 1) == 0) ? "tableEvenRow" : "tableOddRow")%>">
+	                              				<td style="width: 40%"><fmt:message key="mappeddomain" /></td>
+	                              				<td><%=mappedDomain%></td>
+	                              			</tr>
+	                              			<% } %>
+	                              		</tbody>
+	                              	</table>
+	                              </div>
+	                          </td>
+					</tr>
+					<%
+						}
+					%>
+				</tbody>
+			</table>
+		</form>
+		<p>&nbsp;</p>
+		<carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>" page="subscribed_cartridges.jsp"
+			pageNumberParameterName="pageNumber" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources" prevKey="prev"
+			nextKey="next" parameters="<%=parameters%>" />
+		<%
+			} else {
+		%>
+		<b><fmt:message key="no.cartridges.found" /></b>
+		<%
+			}
+		%>
+	</div>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/sync_repo_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/sync_repo_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/sync_repo_ajaxprocessor.jsp
new file mode 100644
index 0000000..e79444b
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/sync_repo_ajaxprocessor.jsp
@@ -0,0 +1,60 @@
+<!--
+ ~ Copyright (c) 2005-2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<jsp:include page="../dialog/display_messages.jsp" />
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle.getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+	String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+	ConfigurationContext configContext = (ConfigurationContext) config.getServletContext().getAttribute(
+			CarbonConstants.CONFIGURATION_CONTEXT);
+
+	String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+	CartridgeAdminClient client;
+
+	String cartridgeAlias = request.getParameter("cartridge_alias");
+	try {
+		client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+		client.synchronizeRepository(cartridgeAlias);
+		//CarbonUIMessage.sendCarbonUIMessage("Initiated repository synchronization", CarbonUIMessage.INFO, request);
+		String message = "Initiated repository synchronization";
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+	} catch (Exception e) {
+		//CarbonUIMessage.sendCarbonUIMessage(e.getMessage(), CarbonUIMessage.ERROR, request);
+		response.setStatus(500);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+	}
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/test_git_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/test_git_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/test_git_ajaxprocessor.jsp
new file mode 100644
index 0000000..fa4b8a0
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/test_git_ajaxprocessor.jsp
@@ -0,0 +1,71 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.RepositoryInformation" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.ResourceBundle" %>
+<%@ page import="java.util.Map" %>
+<jsp:include page="../dialog/display_messages.jsp"/>
+
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle
+        .getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+          (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+    String repoUrl = "";
+    String repoUserName = "";
+    String repoPassword = "";
+    String repoType = null;
+    
+    repoUrl = request.getParameter("repo_url");
+    repoUserName = request.getParameter("repo_username");
+    repoPassword = request.getParameter("repo_password");
+    repoType = request.getParameter("repoType");
+    try{
+   		client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+   		RepositoryInformation repositoryInformation = client.testRepositoryConnection(repoUrl, repoUserName, repoPassword, "private".equals(repoType));
+   		String message = "";
+   		if (repositoryInformation != null) {
+   			message = "Successfully connected to the repository: " + repositoryInformation.getRepoURL();
+   		}
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+	} catch (Exception e) {
+		response.setStatus(500);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+	}
+%>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/unsubscribe_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/unsubscribe_ajaxprocessor.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/unsubscribe_ajaxprocessor.jsp
new file mode 100644
index 0000000..c246091
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/unsubscribe_ajaxprocessor.jsp
@@ -0,0 +1,64 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+    <%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%@ page import="java.util.ResourceBundle" %>
+<jsp:include page="../dialog/display_messages.jsp"/>
+
+
+<%
+    response.setHeader("Cache-Control", "no-cache");
+
+	ResourceBundle bundle = ResourceBundle
+        .getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+          (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+
+    String cartridgeAlias = request.getParameter("cartridge_alias");
+    
+    try{
+        client= new CartridgeAdminClient(cookie, backendServerURL, configContext,request.getLocale());
+        client.unsubscribe(cartridgeAlias);
+        //CarbonUIMessage.sendCarbonUIMessage("Successfully unsubscribed "  ,
+        //                                                        CarbonUIMessage.INFO, request);
+        String message = "Successfully unsubscribed";
+%>
+<span id="responseMsg"><%=message%></span>
+<%
+    }catch (Exception e) {
+        response.setStatus(500);
+        //CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR,  e.getMessage(), e);
+        //session.setAttribute(CarbonUIMessage.ID, uiMsg);
+%>
+<span id="responseMsg"><%=e.getMessage()%></span>
+<%
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/pom.xml
new file mode 100644
index 0000000..3438d6d
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/pom.xml
@@ -0,0 +1,116 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.db.keep.alive</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - DB Keep Alive</name>
+
+    <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>
+                        <Private-Package>
+                            org.wso2.carbon.db.keep.alive.*,
+                        </Private-Package>
+                        <Import-Package>
+                            org.quartz.*,
+                            org.apache.synapse.task.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            org.wso2.carbon.stratos.common.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.mgt</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.billing.mgt</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.billing.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-commons</artifactId>
+        </dependency>
+
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingBillingAction.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingBillingAction.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingBillingAction.java
new file mode 100644
index 0000000..e668040
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingBillingAction.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.db.keep.alive.actions;
+
+import org.wso2.carbon.billing.core.BillingEngine;
+
+public class AccessingBillingAction {
+    BillingEngine billingEngine;
+    public AccessingBillingAction(BillingEngine billingEngine) {
+        this.billingEngine = billingEngine;
+    }
+    public void execute() throws Exception {
+        billingEngine.beginTransaction();
+        boolean succeeded = false;
+        try {
+            billingEngine.getCustomersWithName("some-non-existance-customer");
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingRegistryAction.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingRegistryAction.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingRegistryAction.java
new file mode 100644
index 0000000..e48ecc5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/AccessingRegistryAction.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.db.keep.alive.actions;
+
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+
+import java.util.Date;
+
+public class AccessingRegistryAction {
+    private static final String KEEP_ALIVE_RESOURCE =
+            "/repository/components/org.wso2.carbon.keep-alive-resource";
+    Registry registry;
+    public AccessingRegistryAction(Registry registry) {
+        this.registry = registry;
+    }
+    public void execute() throws Exception {
+        Collection c;
+        if (registry.resourceExists(KEEP_ALIVE_RESOURCE)) {
+            c = (Collection)registry.get(KEEP_ALIVE_RESOURCE);
+        } else {
+            c = registry.newCollection();
+        }
+        long currentTime = new Date().getTime();
+        c.setProperty("currentTime", String.valueOf(currentTime));
+        registry.put(KEEP_ALIVE_RESOURCE, c);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/UserMgtAction.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/UserMgtAction.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/UserMgtAction.java
new file mode 100644
index 0000000..0eb2b21
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/actions/UserMgtAction.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.db.keep.alive.actions;
+
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.AuthorizationManager;
+import org.wso2.carbon.user.core.Permission;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
+
+public class UserMgtAction {
+    UserRealm realm;
+    public UserMgtAction(RegistryService registryService) throws RegistryException {
+        realm = registryService.getUserRealm(0);
+    }
+    public void execute() throws Exception {
+        UserStoreManager userStoreManager = realm.getUserStoreManager();
+        if (!userStoreManager.isExistingUser("tracker")) {
+            userStoreManager.addUser("tracker", "tracker123", null, null, null, false);
+            Permission[] permisions = new Permission[] { new Permission("high security", "read")};
+            userStoreManager.addRole("tracker_role", new String[] {"tracker"}, permisions);
+        }
+        userStoreManager.updateCredentialByAdmin("tracker", "tracker123");
+        // do some authorizations
+        AuthorizationManager authManager = realm.getAuthorizationManager();
+        authManager.authorizeRole("tracker_role", "tracker_obj", "read");
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/internal/DBKeepAliveServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/internal/DBKeepAliveServiceComponent.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/internal/DBKeepAliveServiceComponent.java
new file mode 100644
index 0000000..c208845
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/internal/DBKeepAliveServiceComponent.java
@@ -0,0 +1,81 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.db.keep.alive.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.db.keep.alive.util.Util;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+
+/**
+ * @scr.component name="org.wso2.carbon.db.keep.alive"
+ * immediate="true"
+ * @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="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="billingManager.service"
+ * interface="org.wso2.carbon.billing.core.BillingManager" cardinality="1..1"
+ * policy="dynamic" bind="setBillingManager" unbind="unsetBillingManager"
+ */
+public class DBKeepAliveServiceComponent {
+    private static Log log = LogFactory.getLog(DBKeepAliveServiceComponent.class);
+
+
+    protected void activate(ComponentContext context) {
+        Util.registerJob();
+        log.debug("******* DBKeepAlive bundle is activated ******* ");
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* DBKeepAlive is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    public void setBillingManager(BillingManager billingManager) {
+        log.debug("Receiving billingManager service");
+        Util.setBillingManager(billingManager);
+    }
+
+    public void unsetBillingManager(BillingManager billingManager) {
+        log.debug("Unsetting billingManager service");
+        Util.setBillingManager(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/KeepAliveJob.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/KeepAliveJob.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/KeepAliveJob.java
new file mode 100644
index 0000000..550bfc5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/KeepAliveJob.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.db.keep.alive.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.quartz.Job;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.db.keep.alive.actions.AccessingBillingAction;
+import org.wso2.carbon.db.keep.alive.actions.AccessingRegistryAction;
+import org.wso2.carbon.db.keep.alive.actions.UserMgtAction;
+
+public class KeepAliveJob implements Job {
+    private static final Log log = LogFactory.getLog(KeepAliveJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+        log.debug("-------------Running the db keep alive job------------------");
+        RegistryService registryService = Util.getRegistryService();
+        try {
+            new AccessingRegistryAction(registryService.getLocalRepository()).execute();
+            new AccessingRegistryAction(registryService.getConfigSystemRegistry()).execute();
+            new AccessingRegistryAction(registryService.getGovernanceSystemRegistry()).execute();
+        } catch (Exception e) {
+            String msg = "Error in running registry actions.";
+            log.error(msg, e);
+            throw new JobExecutionException(msg, e);
+        }
+        try {
+            new AccessingBillingAction(Util.getBillingEngine()).execute();
+        } catch (Exception e) {
+            String msg = "Error in running billing engine action.";
+            log.error(msg, e);
+            throw new JobExecutionException(msg, e);
+        }
+        try {
+            new UserMgtAction(registryService).execute();
+        } catch (Exception e) {
+            String msg = "Error in running user manager actions.";
+            log.error(msg, e);
+            throw new JobExecutionException(msg, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/Util.java b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/Util.java
new file mode 100644
index 0000000..7af5c72
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.db.keep.alive/2.1.0/src/main/java/org/wso2/carbon/db/keep/alive/util/Util.java
@@ -0,0 +1,115 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.db.keep.alive.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskScheduler;
+import org.apache.synapse.task.TaskSchedulerFactory;
+import org.osgi.framework.ServiceRegistration;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+public class Util {
+
+    private static final Log log = LogFactory.getLog(Util.class);
+    private static int JOB_INTERVAL = 15; // in mins
+    private static String TASK_ID = "taskId"; 
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static ServiceRegistration redirectorServiceRegistration = null;
+    private static BillingManager billingManager;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static BillingManager getBillingManager() {
+        return billingManager;
+    }
+
+    public static void setBillingManager(BillingManager billingManager) {
+        Util.billingManager = billingManager;
+    }
+
+    public static UserRealm getUserRealm(int tenantId) throws RegistryException {
+        return registryService.getUserRealm(tenantId);     
+    }
+
+    public static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+    public static BillingEngine getBillingEngine() {
+        return billingManager.getBillingEngine(StratosConstants.MULTITENANCY_SCHEDULED_TASK_ID);
+    }
+
+    public static void registerJob() {
+
+        String taskName = UUIDGenerator.generateUUID();
+        String groupId = UUIDGenerator.generateUUID();
+
+        TaskDescription taskDescription = new TaskDescription();
+        taskDescription.setName(taskName);
+        taskDescription.setGroup(groupId);
+        // we are triggering only at the period
+
+        //taskDescription.setInterval(200);
+        taskDescription.setInterval(JOB_INTERVAL * 60 * 1000L);
+
+        Map<String, Object> resources = new HashMap<String, Object>();
+
+        TaskScheduler taskScheduler =
+                TaskSchedulerFactory.getTaskScheduler(TASK_ID);
+        if (!taskScheduler.isInitialized()) {
+            Properties properties = new Properties();
+            taskScheduler.init(properties);
+        }        
+        taskScheduler.scheduleTask(taskDescription, resources, KeepAliveJob.class);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.email.sender/2.1.0/pom.xml
new file mode 100644
index 0000000..6d28e10
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/pom.xml
@@ -0,0 +1,86 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.email.sender</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Email Sender Component</name>
+
+    <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>
+                        <Private-Package>
+                            org.wso2.carbon.email.sender.internal.*,
+                            org.wso2.carbon.email.sender.util.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.wso2.carbon.email.sender.api.*
+                        </Export-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>log4j</groupId>
+            <artifactId>log4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/BulkEmailSender.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/BulkEmailSender.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/BulkEmailSender.java
new file mode 100644
index 0000000..f30aaa6
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/BulkEmailSender.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.email.sender.api;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.mail.MailConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.email.sender.util.Util;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The class that handles the bulk email sending logic for stratos.
+ */
+public class BulkEmailSender extends EmailSender{
+    private static Log log = LogFactory.getLog(BulkEmailSender.class);
+
+    public BulkEmailSender(EmailSenderConfiguration config) {
+        super(config);
+    }
+
+    /**
+     * Sends the email
+     * @param bulkEmailData List of email data holder objects
+     * @throws Exception, if sending the email notification failed.
+     */
+    public void sendBulkEmails(List<EmailDataHolder> bulkEmailData) throws Exception {
+
+        final List<EmailDataHolder> emailDataHolderList = bulkEmailData;
+
+        final ServiceClient serviceClient;
+        ConfigurationContext configContext = Util.getConfigurationContext();
+        if (configContext != null) {
+            serviceClient = new ServiceClient(configContext, null);
+        } else {
+            serviceClient = new ServiceClient();
+        }
+
+        new Thread() {
+            public void run() {
+
+                for(EmailDataHolder dataHolder : emailDataHolderList){
+
+                    String subject = getMessageTitle(dataHolder.getEmailParameters());
+                    String body = getMessageBody(dataHolder.getEmailParameters());
+                    String email = dataHolder.getEmail(); // no change in here,
+
+                    Map<String, String> headerMap = new HashMap<String, String>();
+                    headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject);
+                    OMElement payload = OMAbstractFactory.getOMFactory().createOMElement(
+                            BaseConstants.DEFAULT_TEXT_WRAPPER, null);
+                    payload.setText(body);
+
+                    try {
+                        Options options = new Options();
+                        options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
+                        options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
+                        options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT,
+                                MailConstants.TRANSPORT_FORMAT_TEXT);
+                        options.setTo(new EndpointReference("mailto:" + email));
+                        serviceClient.setOptions(options);
+                        serviceClient.fireAndForget(payload);
+                        serviceClient.cleanup();
+                    } catch (AxisFault e) {
+                        String msg = "Error in delivering the message, " +
+                                "subject: " + subject + ", to: " + email + ".";
+                        log.error(msg);
+                    }
+                }
+
+            }
+        }.start();
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailDataHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailDataHolder.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailDataHolder.java
new file mode 100644
index 0000000..32ab7f9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailDataHolder.java
@@ -0,0 +1,26 @@
+package org.wso2.carbon.email.sender.api;
+
+import java.util.Map;
+
+//This holds the email address and email parameter map
+public class EmailDataHolder {
+
+    private String email;
+    private Map<String, String> emailParameters;
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public Map<String, String> getEmailParameters() {
+        return emailParameters;
+    }
+
+    public void setEmailParameters(Map<String, String> emailParameters) {
+        this.emailParameters = emailParameters;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSender.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSender.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSender.java
new file mode 100644
index 0000000..aec1eef
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSender.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.email.sender.api;
+
+import org.wso2.carbon.email.sender.util.Util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.axis2.transport.mail.MailConstants;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axis2.Constants;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.addressing.EndpointReference;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * The class that handles the email sending logic for stratos.
+ */
+public class EmailSender{
+    private static Log log = LogFactory.getLog(EmailSender.class);
+    private EmailSenderConfiguration config = null;
+
+    public EmailSender(EmailSenderConfiguration config) {
+        this.config = config;
+    }
+
+    /**
+     * Sends the email
+     * @param toEmail Email Address (To:)
+     * @param userParameters - map of user parameters
+     * @throws Exception, if sending the email notification failed.
+     */
+    public void sendEmail(String toEmail, Map<String, String>userParameters) throws Exception {
+        final String subject = getMessageTitle(userParameters);
+        final String body = getMessageBody(userParameters);
+        final String email = toEmail; // no change in here,
+        new Thread() {
+            public void run() {
+                Map<String, String> headerMap = new HashMap<String, String>();
+                headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject);
+                OMElement payload = OMAbstractFactory.getOMFactory().createOMElement(
+                        BaseConstants.DEFAULT_TEXT_WRAPPER, null);
+                payload.setText(body);
+
+                try {
+                    ServiceClient serviceClient;
+                    ConfigurationContext configContext = Util.getConfigurationContext();
+                    if (configContext != null) {
+                        serviceClient = new ServiceClient(configContext, null);
+                    } else {
+                        serviceClient = new ServiceClient();
+                    }
+                    Options options = new Options();
+                    options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
+                    options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
+                    options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT,
+                                        MailConstants.TRANSPORT_FORMAT_TEXT);
+                    options.setTo(new EndpointReference("mailto:" + email));
+                    serviceClient.setOptions(options);
+                    serviceClient.fireAndForget(payload);
+                    log.debug("Sending confirmation mail to " + email);
+                } catch (AxisFault e) {
+                    String msg = "Error in delivering the message, " +
+                                "subject: " + subject + ", to: " + email + ".";
+                    log.error(msg);
+                }
+            }
+        }.start();
+    }
+
+    /**
+     * gets the title of the message
+     * @param userParameters - map of user parameters
+     * @return the title of the message
+     */
+    protected String getMessageTitle(Map<String, String> userParameters) {
+        return Util.replacePlaceHolders(config.getSubject(), userParameters);
+    }
+
+    /**
+     * gets the body of the message
+     * @param userParameters - map of user parameters
+     * @return the body of the message
+     */
+    protected String getMessageBody(Map<String, String> userParameters) {
+        return Util.replacePlaceHolders(config.getBody(), userParameters);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSenderConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSenderConfiguration.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSenderConfiguration.java
new file mode 100644
index 0000000..faaf2d9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/api/EmailSenderConfiguration.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.email.sender.api;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * The class that handles the configuration of the email sender for Stratos
+ */
+public class EmailSenderConfiguration {
+    private static Log log = LogFactory.getLog(EmailSenderConfiguration.class);
+
+    public final static String DEFAULT_VALUE_SUBJECT = "EmailSender";
+    public final static String DEFAULT_VALUE_MESSAGE = "Sent form WSO2 Carbon";
+
+    private String fromEmail;
+    private String subject = DEFAULT_VALUE_SUBJECT;
+    private String body = DEFAULT_VALUE_MESSAGE;
+    private Map<String, String> customParameters;
+
+    public Map<String, String> getCustomParameters() {
+        return customParameters;
+    }
+
+    public void setCustomParameters(Map<String, String> customParameters) {
+        this.customParameters = customParameters;
+    }
+
+
+    public String getSubject() {
+        return subject;
+    }
+
+    public void setSubject(String subject) {
+        this.subject = subject.trim();
+    }
+
+    public String getBody() {
+        return body;
+    }
+
+    public void setBody(String emailMessage) {
+        this.body = emailMessage.trim();
+    }
+
+    public String getFromEmail() {
+        return fromEmail;
+    }
+
+    public void setFromEmail(String fromEmail) {
+        this.fromEmail = fromEmail;
+    }
+
+    /**
+     * Loads the email sender configuration
+     * @param configFilename configuration file name
+     * @return EmailSenderConfiguration.
+     */    
+    public static EmailSenderConfiguration loadEmailSenderConfiguration(String configFilename) {
+        File configFile = new File(configFilename);
+        if (!configFile.exists()) {
+            log.error("Email sender configuration File is not present at: " + configFilename);
+            return null;
+        }
+        EmailSenderConfiguration config = new EmailSenderConfiguration();
+        FileInputStream ip = null;
+        try {
+            ip = new FileInputStream(configFile);
+            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ip);
+            StAXOMBuilder builder = new StAXOMBuilder(parser);
+            OMElement documentElement = builder.getDocumentElement();
+            Iterator it = documentElement.getChildElements();
+            while (it.hasNext()) {
+                OMElement element = (OMElement) it.next();
+                if ("subject".equals(element.getLocalName())) {
+                    config.setSubject(element.getText());
+                } else if ("body".equals(element.getLocalName())) {
+                    config.setBody(element.getText());
+                } else if ("customParameters".equals(element.getLocalName())) {
+                    Map<String, String> customParameters = new HashMap<String, String>();
+                    Iterator customParamIt = element.getChildElements();
+                    while (customParamIt.hasNext()) {
+                        OMElement customElement = (OMElement) it.next();
+                        customParameters.put(customElement.getLocalName(), customElement.getText());
+                    }
+                    config.setCustomParameters(customParameters);
+                }
+            }
+            return config;
+        } catch (Exception e) {
+            String msg = "Error in loading configuration for email verification: " +
+                         configFilename + ".";
+            log.error(msg, e);
+            return null;
+        } finally {
+            if (ip != null) {
+                try {
+                    ip.close();
+                } catch (IOException e) {
+                    log.warn("Could not close InputStream for file " + configFile.getAbsolutePath());
+                }
+            }
+
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/internal/EmailSenderServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/internal/EmailSenderServiceComponent.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/internal/EmailSenderServiceComponent.java
new file mode 100644
index 0000000..d7ad8bb
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/internal/EmailSenderServiceComponent.java
@@ -0,0 +1,82 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.email.sender.internal;
+
+import org.wso2.carbon.email.sender.util.Util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="org.wso2.carbon.email.sender"
+ * immediate="true"
+ * @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="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ * @scr.reference name="configuration.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
+ * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
+ */
+public class EmailSenderServiceComponent {
+    private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            log.debug("******* Email Sender bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Email Sender bundle failed activating ****", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Email Sender bundle is deactivated ******* ");
+    }
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService configurationContextService){
+        log.debug("Receiving ConfigurationContext Service");
+        Util.setConfigurationContextService(configurationContextService);
+
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService){
+        log.debug("Unsetting ConfigurationContext Service");
+        Util.setConfigurationContextService(null);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/util/Util.java b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/util/Util.java
new file mode 100644
index 0000000..d83eebf
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.email.sender/2.1.0/src/main/java/org/wso2/carbon/email/sender/util/Util.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.email.sender.util;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.api.RealmConfiguration;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import java.util.Map;
+import java.util.regex.Matcher;
+
+/**
+ * Utility methods for the email sender component
+ */
+public class Util {
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static ConfigurationContextService configurationContextService;
+
+
+    public static ConfigurationContextService getConfigurationContextService() {
+        return configurationContextService;
+    }
+
+    public static void setConfigurationContextService(
+            ConfigurationContextService configurationContextService) {
+        Util.configurationContextService = configurationContextService;
+    }
+
+    public static ConfigurationContext getConfigurationContext() {
+        if (configurationContextService.getServerConfigContext() == null) {
+            return null;
+        }
+        return configurationContextService.getServerConfigContext();
+    }
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static RealmConfiguration getBootstrapRealmConfiguration() {
+        return realmService.getBootstrapRealmConfiguration();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    /**
+     * Replace the {place-holders} with the respective value provided
+     * @param text string
+     * @param userParameters - map of user parameters
+     * @return replaced text for the email {title or body}
+     */
+    public static String replacePlaceHolders(String text, Map<String, String> userParameters) {
+        if (userParameters != null) {
+            for (Map.Entry<String, String> entry : userParameters.entrySet()) {
+                String key = entry.getKey();
+                text = text.replaceAll("\\{" + key + "\\}", Matcher.quoteReplacement(entry.getValue()));
+            }
+        }
+        return text;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..0b1b170
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/pom.xml
@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.gapp.registration.ui</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Carbon - Google Apps Registration UI</name>
+    <description>Provides Google Apps Provisioning via Marketplace</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.json.wso2</groupId>
+            <artifactId>json</artifactId>
+            <version>1.0.0.wso2v1</version>
+        </dependency>
+	<dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+            <version>2.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common.stub</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.rampart.wso2</groupId>
+            <artifactId>rampart-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.security.wso2</groupId>
+            <artifactId>wss4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.tenant.register.gapp.stub</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <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.wso2.carbon.gapp.registration.ui.*
+                         </Export-Package>
+                         <Import-Package>
+                             !org.wso2.carbon.gapp.registration.ui.*,
+                             javax.xml.namespace.*;version="0.0.0",
+                             *;resolution:=optional
+                         </Import-Package>
+                         <Carbon-Component>UIBundle</Carbon-Component>
+                     </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GAppRegistrationUIConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GAppRegistrationUIConstants.java b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GAppRegistrationUIConstants.java
new file mode 100644
index 0000000..d3a6f49
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.gapp.registration.ui/2.1.0/src/main/java/org/wso2/carbon/gapp/registration/ui/GAppRegistrationUIConstants.java
@@ -0,0 +1,6 @@
+package org.wso2.carbon.gapp.registration.ui;
+
+public class GAppRegistrationUIConstants {
+    
+    public static final String AUTH_SESSION_ATTRIBUTE = "gapp.setup.authentication";
+}


[21/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
new file mode 100644
index 0000000..346b3ca
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MultitenancyPackage extends Item {
+    public static final String SUBSCRIPTION_SUB_ITEM_NAME = "subscription";
+    public static final String BW_OVERUSE_SUB_ITEM_NAME = "bwOveruse";
+    public static final String STORAGE_OVERUSE_SUB_ITEM_NAME = "storageOveruse";
+    public static final String CARTRIDGE_OVERUSE_SUB_ITEM_NAME = "cartridgeOveruse";
+
+    private int usersLimit;
+    private Cash subscriptionCharge;
+    private Cash chargePerUser;
+    //private int resourceVolumeLimit;
+    //private int bandwidthLimit;
+    //private Cash bandwidthOveruseCharge;
+    private List<MultitenancyPackageSubItem> subItems;
+
+    public MultitenancyPackage() {
+        subItems = new ArrayList<MultitenancyPackageSubItem>();
+        // adding subscription sub item
+        MultitenancyPackageSubItem subscriptionSubItem = new MultitenancyPackageSubItem();
+        subscriptionSubItem.setName(SUBSCRIPTION_SUB_ITEM_NAME);
+        subscriptionSubItem.setDescription("Subscription for package");
+        subscriptionSubItem.setParent(this);
+        subItems.add(subscriptionSubItem);
+
+        // adding bandwidth overuse sub item
+        MultitenancyPackageSubItem bandwdithOverUseSubItem = new MultitenancyPackageSubItem();
+        bandwdithOverUseSubItem.setName(BW_OVERUSE_SUB_ITEM_NAME);
+        bandwdithOverUseSubItem.setDescription("Bandwidth overuse");
+        bandwdithOverUseSubItem.setParent(this);
+        subItems.add(bandwdithOverUseSubItem);
+
+        // adding storage overuse sub item
+        MultitenancyPackageSubItem storageOverUseSubItem = new MultitenancyPackageSubItem();
+        storageOverUseSubItem.setName(STORAGE_OVERUSE_SUB_ITEM_NAME);
+        storageOverUseSubItem.setDescription("Storage overuse");
+        storageOverUseSubItem.setParent(this);
+        subItems.add(storageOverUseSubItem);
+
+        // adding cartridge overuse sub item
+        MultitenancyPackageSubItem cartridgeOverUseSubItem = new MultitenancyPackageSubItem();
+        cartridgeOverUseSubItem.setName(CARTRIDGE_OVERUSE_SUB_ITEM_NAME);
+        cartridgeOverUseSubItem.setDescription("Cartridge overuse");
+        cartridgeOverUseSubItem.setParent(this);
+        subItems.add(cartridgeOverUseSubItem);
+
+    }
+
+    public MultitenancyPackage(MultitenancyPackage staticMtPackage, boolean isSubscriptionActive) {
+        usersLimit = staticMtPackage.getUsersLimit();
+        chargePerUser = staticMtPackage.getChargePerUser();
+        subscriptionCharge = staticMtPackage.getSubscriptionCharge();
+        super.setResourceVolumeLimit(staticMtPackage.getResourceVolumeLimit());
+        super.setResourceVolumeOveruseCharge(staticMtPackage.getResourceVolumeOveruseCharge());
+        super.setBandwidthLimit(staticMtPackage.getBandwidthLimit());
+        super.setBandwidthOveruseCharge(staticMtPackage.getBandwidthOveruseCharge());
+        super.setCartridgeCPUHourLimit(staticMtPackage.getCartridgeCPUHourLimit());
+        super.setCartridgeCPUOveruseCharge(staticMtPackage.getCartridgeCPUOveruseCharge());
+        setId(staticMtPackage.getId());
+        setName(staticMtPackage.getName());
+        setCost(staticMtPackage.getCost());
+        setDescription(staticMtPackage.getDescription());
+
+        subItems = new ArrayList<MultitenancyPackageSubItem>();
+        for (Item subItem : staticMtPackage.getChildren()) {
+            //Storage overuse and Bandwidth overuse sub items will be added only to active subscription
+            if(isSubscriptionActive || (!isSubscriptionActive && SUBSCRIPTION_SUB_ITEM_NAME.equals(subItem.getName()))){
+
+                MultitenancyPackageSubItem subscriptionSubItem = new MultitenancyPackageSubItem();
+                subscriptionSubItem.setId(subItem.getId());
+                subscriptionSubItem.setName(subItem.getName());
+                subscriptionSubItem.setDescription(subItem.getDescription());
+                subscriptionSubItem.setParent(this);
+                subItems.add(subscriptionSubItem);
+            }
+        }
+    }
+
+    public int getUsersLimit() {
+        return usersLimit;
+    }
+
+    public void setUsersLimit(int usersLimit) {
+        this.usersLimit = usersLimit;
+    }
+
+    public Cash getChargePerUser() {
+        return chargePerUser;
+    }
+
+    public void setChargePerUser(Cash chargePerUser) {
+        this.chargePerUser = chargePerUser;
+    }
+
+    public Cash getSubscriptionCharge() {
+        return subscriptionCharge;
+    }
+
+    public void setSubscriptionCharge(Cash subscriptionCharge) {
+        this.subscriptionCharge = subscriptionCharge;
+    }
+
+    /*public int getResourceVolumeLimit() {
+        return resourceVolumeLimit;
+    }
+
+    public void setResourceVolumeLimit(int resourceVolumeLimit) {
+        this.resourceVolumeLimit = resourceVolumeLimit;
+    }
+    */
+    /*public int getBandwidthLimit() {
+        return bandwidthLimit;
+    }
+
+    public void setBandwidthLimit(int bandwidthLimit) {
+        this.bandwidthLimit = bandwidthLimit;
+    }
+
+    public Cash getBandwidthOveruseCharge() {
+        return bandwidthOveruseCharge;
+    }
+
+    public void setBandwidthOveruseCharge(Cash bandwidthOveruseCharge) {
+        this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+    }*/
+
+    @Override
+    public List<? extends Item> getChildren() {
+        return subItems;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
new file mode 100644
index 0000000..7245a2a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Item;
+
+public class MultitenancyPackageSubItem extends Item {
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
new file mode 100644
index 0000000..187c261
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.billing.mgt.api.MultitenancyBillingInfo;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyCustomer;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyPackage;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.usage.beans.TenantUsage;
+
+import java.util.*;
+
+/**
+ * Gets subscriptions and feeds them to the Billing Engine context
+ */
+public class MultitenancySubscriptionFeedingHandler implements BillingHandler {
+    private static final Log log = LogFactory.getLog(MultitenancySubscriptionFeedingHandler.class);
+
+    private Map<Integer, MultitenancyPackage> multitenancyPackagesMap = new HashMap<Integer, MultitenancyPackage>();
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        DataAccessObject dataAccessObject = Util.getBillingManager().getDataAccessObject();
+        MultitenancyBillingInfo billingInfo = Util.getMultitenancyBillingInfo();
+
+        // here we are initializing the packages
+        List<MultitenancyPackage> multitenancyPackages = billingInfo.getMultitenancyPackages();
+        try {
+            dataAccessObject.beginTransaction();
+            for (MultitenancyPackage multitenancyPackage : multitenancyPackages) {
+                // check the package existence in the database; If not available, insert it
+                int itemId = dataAccessObject.getItemIdWithName(multitenancyPackage.getName());
+                if (itemId == DataAccessObject.INVALID) {
+                    itemId = dataAccessObject.addItem(multitenancyPackage);
+                }
+                multitenancyPackage.setId(itemId);
+                multitenancyPackagesMap.put(itemId, multitenancyPackage);
+                // and add all the sub items too
+                for (Item subItem : multitenancyPackage.getChildren()) {
+                    int subItemId = dataAccessObject.getItemId(subItem.getName(), itemId);
+                    if (subItemId == DataAccessObject.INVALID) {
+                        subItemId = dataAccessObject.addItem(subItem);
+                    }
+                    subItem.setId(subItemId);
+                }
+            }
+            dataAccessObject.commitTransaction();
+        }catch (Exception e){
+            dataAccessObject.rollbackTransaction();
+            log.error(e.getMessage());
+            throw new BillingException(e.getMessage(), e);
+        }
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        feedSubscriptions(handlerContext);
+    }
+
+    private void feedSubscriptions(BillingEngineContext handlerContext) throws BillingException {
+        // get the subscriptions of the customer.
+        Customer customer = handlerContext.getCustomer();
+        List<Subscription> subscriptions = getSubscriptions(null, customer); //if the customer is null
+                                                                               // this will get subscriptions
+                                                                              // of all customers
+
+        //Filtering out the subscription entries of customers who has not activated their accounts
+        //This will avoid an invoice being generated for such customers
+        Date endDate = new Date();
+
+        Iterator iterator = subscriptions.iterator();
+        while(iterator.hasNext()){
+            Subscription subscription = (Subscription) iterator.next();
+            if(!subscription.isActive() && subscription.getActiveUntil().after(endDate)){
+                iterator.remove();
+            }
+        }
+
+        // prepare the handler context
+        handlerContext.setSubscriptions(subscriptions);
+        String infoMsg = "Subscription feeding phase completed. ";
+        if (subscriptions!=null){
+            infoMsg += subscriptions.size() + " subscriptions fed. ";
+        }else{
+            infoMsg += "0 subscriptions fed. ";
+        }
+        log.info(infoMsg);
+        // resetting the single customer back from the fed data
+        // this is applicable in the interim invoice scenario
+        //If this is not done, the customer object in the BillingEngine context will have
+        //a null invoice
+        if (customer != null && subscriptions != null && subscriptions.size() > 0) {
+            Subscription subscription = subscriptions.get(0);
+            handlerContext.setCustomer(subscription.getCustomer());
+        }
+    }
+
+    /**
+     *
+     * @param itemId
+     * @param isSubscriptionActive subitems for bw_overuse and storage_overuse
+     * will be added only for the active subscription
+     * @return
+     */
+    private Item getItem(int itemId, boolean isSubscriptionActive) {
+        return new MultitenancyPackage(multitenancyPackagesMap.get(itemId), isSubscriptionActive);
+    }
+
+    /**
+     * Retrieving tenant info and filling the customer object
+     * @param customerId
+     * @return
+     * @throws BillingException
+     */
+    private Customer getCustomer(int customerId) throws BillingException {
+        MultitenancyCustomer customer = new MultitenancyCustomer();
+        CustomerUtils.fillCustomerData(customerId, customer);
+        customer.setTenantId(customerId);
+
+        fillTenantUsage(customer);
+        return customer;
+    }
+
+    /**
+     * Fill usage data of the customer
+     * @param customer
+     * @throws BillingException
+     */
+    private void fillTenantUsage(MultitenancyCustomer customer) throws BillingException {
+        // first get the current month string
+        Calendar calendar = Calendar.getInstance();
+        String monthString = CommonUtil.getMonthString(calendar);
+        try {
+            int tenantId = customer.getTenantId();
+            TenantUsage usage =
+                    Util.getTenantUsageRetriever().getTenantUsage(tenantId, monthString);
+
+            long currentDataCapacity = usage.getRegistryContentCapacity();
+            long historyDataCapacity = usage.getRegistryContentHistoryCapacity();
+            customer.setCurrentStorage(currentDataCapacity);
+            customer.setHistoryStorage(historyDataCapacity);
+            customer.setTotalStorage(currentDataCapacity + historyDataCapacity);
+
+            long incomingBW = usage.getTotalIncomingBandwidth();
+            long outgoingBW = usage.getTotalOutgoingBandwidth();
+            customer.setIncomingBandwidth(incomingBW);
+            customer.setOutgoingBandwidth(outgoingBW);
+            customer.setTotalBandwidth(incomingBW + outgoingBW);
+
+            //Getting the cartridge hours and setting it to the customer
+            customer.setTotalCartridgeCPUHours(usage.getTotalCartridgeHours().getCartridgeHours());
+
+            log.debug("Customer: " + customer.getTenantId() + " - Data Capacity: " + customer.getTotalStorage());
+
+            customer.setNumberOfUsers(usage.getNumberOfUsers());
+        } catch (Exception e) {
+            String msg = "Error in getting the tenant usage for customer name: " 
+                    + customer.getName() + ".";
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    /**
+     * Gets subscriptions of customer(s)
+     * @param filter currently there is a filter "multitenancy" defined in the billing-config.xml
+     * This will be removed in the future trunk
+     * @param customer if the customer is null it gets subscriptions of all customers
+     * @return
+     * @throws BillingException
+     */
+    private List<Subscription> getSubscriptions(String filter,
+                                                Customer customer)throws BillingException {
+        DataAccessObject dataAccessObject = Util.getBillingManager().getDataAccessObject();
+        List<Subscription> subscriptions = null;
+        Map<Integer, Customer> customersCache = new HashMap<Integer, Customer>();
+        try {
+            dataAccessObject.beginTransaction();
+            if (customer == null) {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptions(filter);
+            } else {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptionsForCustomer(filter, customer);
+            }
+            if(subscriptions!=null && subscriptions.size()>0){
+                for (Subscription subscription : subscriptions) {
+                    Customer dummyCustomer = subscription.getCustomer();
+                    int customerId = dummyCustomer.getId();
+                    Customer correctCustomer = customersCache.get(customerId);
+                    if (correctCustomer == null) {
+                        correctCustomer = getCustomer(customerId);
+                        customersCache.put(customerId, correctCustomer);
+                    }
+                    subscription.setCustomer(correctCustomer);
+
+                    Item dummyItem = subscription.getItem();
+                    Item correctItem = getItem(dummyItem.getId(), subscription.isActive());
+                    subscription.setItem(correctItem);
+                }
+            }
+            dataAccessObject.commitTransaction();
+        }catch (Exception e){
+            dataAccessObject.rollbackTransaction();
+            String msg = "Error occurred while getting subscriptions";
+            if(customer != null) {
+                msg = msg + " for customer: " + customer.getName();
+            }
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
new file mode 100644
index 0000000..d30e3f9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
@@ -0,0 +1,109 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.usage.api.TenantUsageRetriever;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="org.wso2.carbon.billing.mgt"
+ * immediate="true"
+ * @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="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1"
+ * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="billingManager.service"
+ * interface="org.wso2.carbon.billing.core.BillingManager" cardinality="1..1"
+ * policy="dynamic" bind="setBillingManager" unbind="unsetBillingManager"
+ * @scr.reference name="tenant.usage.retriever.service"
+ * interface="org.wso2.carbon.usage.api.TenantUsageRetriever" cardinality="1..1"
+ * policy="dynamic" bind="setTenantUsageRetriever" unbind="unsetTenantUsageRetriever"
+ */
+public class MultitenancyBillingServiceComponent {
+    private static Log log = LogFactory.getLog(MultitenancyBillingServiceComponent.class);
+    private static ConfigurationContextService contextService;
+
+    protected void activate(ComponentContext context) {
+        try {
+            Util.registerSubscriptionFeedingHandlers(context.getBundleContext());
+            Util.scheduleBilling();
+            Util.registerBillingInfo(context.getBundleContext());
+            Util.initDataAccessManager();
+            Util.initializeThrottling(context.getBundleContext());
+            Util.registerTenantBillingService(context.getBundleContext());
+            log.debug("******* Multitenancy Billing bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Multitenancy Billing bundle failed activating ****", e);
+        }
+    }
+
+    @SuppressWarnings("unused")
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Multitenancy Billing is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    public void setBillingManager(BillingManager billingManager) {
+        log.debug("Receiving billingManager service");
+        Util.setBillingManager(billingManager);
+    }
+
+    @SuppressWarnings("unused")
+    public void unsetBillingManager(BillingManager billingManager) {
+        log.debug("Unsetting billingManager service");
+        Util.setBillingManager(null);
+    }
+
+    public void setTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        log.debug("Setting Tenant Usage Retriever service");
+        Util.setTenantUsageRetriever(tenantUsageRetriever);
+    }
+
+    @SuppressWarnings("unused")
+    public void unsetTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        log.debug("Unsetting Tenant Usage Retriever service");
+        Util.setBillingManager(null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
new file mode 100644
index 0000000..0298c4d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.DataAccessManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+import java.util.List;
+
+/**
+ * This service allows other components to access billing related data
+ * without going through a billing manager
+ */
+public class BillingDataAccessService extends AbstractAdmin {
+    private static Log log = LogFactory.getLog(BillingDataAccessService.class);
+
+    /**
+     * Add a new subscription to the BC_SUBSCRIPTION table
+     * @param subscription  object with subscription info
+     * @return the subscription id of the added subscription
+     * @throws Exception Exception
+     */
+    public int addSubscription(Subscription subscription) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.addSubscription(subscription);
+    }
+
+    /**
+     * Delete a particular tenants subscription and all related data
+     * @param tenantId id of the tenant whose billing details should be deleted
+     * @throws Exception thorwn if an error is occured while deleting data
+     */
+    public void deleteBillingData(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        dataAccessManager.deleteBillingData(tenantId);
+    }
+
+    /**
+     * Finds the customer with a given tenant domain
+     * @param customerName  is the tenant domain
+     * @return  a customer object
+     * @throws Exception Exception
+     */
+    public Customer getCustomerWithName(String customerName) throws Exception {
+
+        //This is invoked by tenants only. Therefore securing this by checking 
+        //whether the string passed is actually the domain of current tenant
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int currentTenantId = userRegistry.getTenantId();
+
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        String currentTenantDomain = tenantManager.getDomain(currentTenantId);
+
+        if(!customerName.equals(currentTenantDomain)){
+            String msg = "Tenant: " + currentTenantDomain + " is trying to get customer object of tenant: " +
+                    customerName + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        Customer customer = null;
+        List<Customer> customers = dataAccessManager.getCustomersWithName(customerName);
+        if (customers.size() > 0) {
+            customer = customers.get(0);
+        }
+        return customer;
+    }
+
+    /**
+     * Get a subscription with a given id
+     * @param subscriptionId subscription id
+     * @return a subscription object
+     * @throws Exception Exception
+     */
+    public Subscription getSubscription(int subscriptionId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getSubscription(subscriptionId);
+    }
+
+
+    /**
+     * Method called by super-tenant to get the active subscription of a tenant
+     * @param tenantId Tenant Id
+     * @return subscription details
+     * @throws Exception Exception
+     */
+    public Subscription getActiveSubscriptionOfCustomerBySuperTenant(int tenantId) throws Exception{
+        return getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+    /**
+     * Method called by tenant to get the active subscription
+     * @return subscription details
+     * @throws Exception Exception
+     */
+    public Subscription getActiveSubscriptionOfCustomerByTenant() throws Exception{
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int tenantId = userRegistry.getTenantId();
+
+        return getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+
+    /**
+     * Gets the item id for a given item name and a parent id
+     * For example "subscription" item id of Demo subscription
+     * @param name  e.g. "subscription", "bwOveruse", "storageOveruse"
+     * @param parentId there is a parent item in BC_ITEM
+     * @return  the item id from the BC_ITEM table
+     * @throws Exception Exception
+     */
+    public int getItemIdWithName(String name, int parentId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getItemIdWithName(name, parentId);
+    }
+
+    /**
+     * This is used by the tenants 
+     * @param subscriptionPlan new Usage plan name that user expect to go
+     * @return whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionByTenant(String subscriptionPlan) throws Exception {
+
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int tenantId = userRegistry.getTenantId();
+
+        return changeSubscription(tenantId, subscriptionPlan);
+
+    }
+
+    /**
+     * This is used by the super tenant
+     * @param customerId    this is the tenant id
+     * @param subscriptionPlan  new usage plan name
+     * @return  whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionBySuperTenant(int customerId, String subscriptionPlan) throws Exception {
+
+        return changeSubscription(customerId, subscriptionPlan);
+    }
+
+    /**
+     * Gets the inactive subscriptions of a customer ordered by ACTIVE_SINCE time
+     * in the descending order (i.e. latest ones first)
+     * @param customerId this is the tenant id
+     * @return  an array of subscriptions
+     * @throws Exception Exception
+     */
+    public Subscription[] getInactiveSubscriptionsOfCustomer(int customerId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        List<Subscription> subscriptions = dataAccessManager.getInactiveSubscriptionsOfCustomer(customerId);
+        Subscription[] subscriptionArray;
+        if (subscriptions != null && subscriptions.size() > 0) {
+            subscriptionArray = subscriptions.toArray(new Subscription[subscriptions.size()]);
+        } else {
+            subscriptionArray = new Subscription[0];
+        }
+        return subscriptionArray;
+    }
+
+    /**
+     * Activate a subscription with a given id
+     * @param subscriptionId is the id of subscription which needs to be activated
+     * @return  true or false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean activateSubscription(int subscriptionId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.activateSubscription(subscriptionId);
+    }
+
+    /**
+     * Method called by tenants when deactivating the active subscriptions
+     * @return true | false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean deactivateActiveSubscriptionByTenant() throws Exception{
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        int currentTenantId = registry.getTenantId();
+
+        return deactivateActiveSubscription(currentTenantId);
+    }
+
+
+    /**
+     * Method called by super-tenant
+     * @param tenantId Tenant Id
+     * @return true | false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean deactivateActiveSubscriptionBySuperTenant(int tenantId) throws Exception{
+        return deactivateActiveSubscription(tenantId);
+    }
+    
+
+
+    /**
+     * This is the private method called by tenant or super tenant operations when
+     * changing(updating) the subscription plan
+     * @param tenantId Tenant ID
+     * @param subscriptionPlan new usage plan (subscription plan) name
+     * @return true or false based on whether the operation was successful
+     * @throws Exception Exception
+     */
+    private boolean changeSubscription(int tenantId, String subscriptionPlan) throws Exception {
+
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        if (dataAccessManager.changeSubscription(tenantId, subscriptionPlan)) {
+            try {
+                Util.executeThrottlingRules(tenantId);
+            }
+            catch (Exception e) {
+                log.error("Error occurred executing throttling rules after updating the subscription " +
+                        "to " + subscriptionPlan + ". " + e.toString());
+            }
+            //send mail
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Gets the active subscription of a customer. There can be only one active
+     * subscription for a customer at a given time
+     * @param tenantId Tenant Id
+     * @return  a subscription object
+     * @throws Exception Exception
+     */
+    private Subscription getActiveSubscriptionOfCustomer(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+    /**
+     * Deactivates the active subscription of a customer
+     * @param tenantId is the customer id (both have the same meaning)
+     * @return true or false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    private boolean deactivateActiveSubscription(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.deactivateActiveSubscription(tenantId);
+    }
+
+    /**
+     * This method is used to update the usage plan when updating the from Demo to a paying plan
+     * @param subscriptionPlan new Usage plan name that user expect to go
+     * @param tenantDomain the domain of the tenant that should be updated 
+     * @return whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionForTenant(String subscriptionPlan, String tenantDomain) throws Exception {
+        int tenantId = Util.getRealmService().getTenantManager().getTenantId(tenantDomain);
+        return changeSubscription(tenantId, subscriptionPlan);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
new file mode 100644
index 0000000..261f705
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
@@ -0,0 +1,606 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
+import org.wso2.carbon.billing.core.beans.PaginatedBalanceInfoBean;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.mgt.beans.*;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class BillingService extends AbstractAdmin {
+
+    private static final Log log = LogFactory.getLog(BillingService.class);
+
+    /**
+     * Gets the available billing periods of the available invoices for the
+     * current customer. Tenant id is taken from registry
+     * @return  an array of BillingPeriod objects
+     * @throws Exception Exception
+     */
+    public BillingPeriod[] getAvailableBillingPeriods() throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getAvailableBillingPeriods(registry);
+    }
+
+    /**
+     * Gets the available billigs dates of a given tenant
+     * @param tenantDomain is the tenant domain
+     * @return an array of BillingPeriods
+     * @throws Exception if an error occurs during the process
+     */
+    public BillingPeriod[] getAvailableBillingPeriodsBySuperTenant(String tenantDomain) throws Exception{
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        
+        List<Customer> customers = billingEngine.getCustomersWithName(tenantDomain);
+        if(customers.size()>0){
+            return getBillingPeriodsFromInvoices(billingEngine.getInvoices(customers.get(0)));
+        }else{
+            return new BillingPeriod[0];
+        }
+    }
+
+    /**
+     * Gets the invoice with a given invoice id
+     * @param invoiceId is the id of the invoice expected
+     * @return  a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    public MultitenancyInvoice getPastInvoice(int invoiceId) throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getPastInvoiceById(registry, invoiceId);
+    }
+
+    /**
+     * Gets the current invoice (interim invoice) of the current customer.
+     * Tenant id is taken from the registry
+     * @return a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    public MultitenancyInvoice getCurrentInvoice() throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getCurrentInvoiceOfCustomer(registry);
+    }
+
+    /**
+     * Adds a payment record to the BC_PAYMENT table. Sends a notification email
+     * after adding the record
+     * @param payment is the Payment object which contains the payment record details
+     * @param amount is the paid amount (had to pass this as a string)
+     * @return  the payment id for the added record
+     * @throws Exception if an error occurs during the operation
+     */
+    public int addPayment(Payment payment, String amount) throws Exception {
+        int paymentId = addPaymentRecord(payment, amount);
+        if(paymentId>0){
+            payment.setId(paymentId);
+            sendPaymentReceivedEmail(payment);
+        }
+        return paymentId;
+    }
+
+    /**
+     * Adds a payment record to the BC_REGISTRATION_PAYMENT table. Sends a notification email
+     * after adding the record
+     *
+     * @param payment   the Payment object which contains the payment record details
+     * @param amount    the registration fee paid
+     * @param usagePlan the registered usage plan
+     * @return the payment id for the added record
+     * @throws Exception thrown if an error occurs while adding the record
+     */
+    public int addRegistrationPayment(Payment payment, String amount, String usagePlan)
+            throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Cash cashAmount = new Cash(amount);
+        payment.setAmount(cashAmount);
+        int paymentId = billingEngine.addRegistrationPayment(payment, usagePlan);
+        if (paymentId > 0) {
+            payment.setId(paymentId);
+            sendRegistrationPaymentReceivedEmail(payment);
+        }
+        return paymentId;
+    }
+
+    /**
+     * Adds a payment record for invoice adjustment purposes
+     * @param payment is the Payment object which contains the adjustment details
+     * @param amount is the adjustment amount (had to pass this as a string)
+     * @return the payment id for the added adjustment record
+     * @throws Exception if an error occurs during the operation
+     */
+    public int makeAdjustment(Payment payment, String amount) throws Exception {
+        return addPaymentRecord(payment, amount);
+    }
+    
+    private int addPaymentRecord(Payment payment, String amount) throws Exception{
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Cash cashAmount = new Cash(amount);
+        payment.setAmount(cashAmount);
+        if(payment.getInvoice()!=null){
+            payment.setSubscriptions(billingEngine.getInvoiceSubscriptions(payment.getInvoice().getId()));
+        }
+        int paymentId = billingEngine.addPayment(payment);
+        return paymentId;
+    }
+
+    /**
+     * Gets the paginated BalanceInfoBean to be shown for the super tenant in the paginated mode
+     * @param pageNumber is the expected page number
+     * @return a PaginatedBalanceInfoBean object
+     * @throws Exception Exception
+     */
+    public PaginatedBalanceInfoBean getPaginatedBalances(int pageNumber) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalances(null); //no tenant domain
+        PaginatedBalanceInfoBean paginatedBalanceBean = new PaginatedBalanceInfoBean();
+        DataPaginator.doPaging(pageNumber, balanceBeans, paginatedBalanceBean);
+
+        return paginatedBalanceBean;
+    }
+
+    /**
+     * Gets OutstandingBalanceInfo bean(s).
+     * @param tenantDomain  is the domain of the expected tenant which the super-tenant
+     * wants to view the balance. If this is null, balance info of all the tenants will be shown
+     * @return  an array of OutstandingBalanceInfoBeans
+     * @throws Exception Exception
+     */
+    public OutstandingBalanceInfoBean[] getOutstandingBalance(String tenantDomain) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalanceInfoBeans(tenantDomain);
+        return balanceBeans.toArray(new OutstandingBalanceInfoBean[balanceBeans.size()]);
+    }
+
+    /**
+     * Adds a discount entry
+     * @param discount is the discount object which contains discount information
+     * @param tenantDomain is passed to get the tenant id and set to the discount object
+     * @return true or false based on the result of the operation
+     * @throws Exception if an error occurs during the operation
+     */
+    public boolean addDiscount (Discount discount, String tenantDomain) throws Exception {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        int tenantId = tenantManager.getTenantId(tenantDomain);
+        if(tenantId== MultitenantConstants.INVALID_TENANT_ID){
+            throw new Exception("Invalid tenant domain submitted for a discount");
+        }
+        discount.setTenantId(tenantId);
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        boolean added = billingEngine.addDiscount(discount);
+        if(added){
+            log.info("Discount entry added for tenant: " + discount.getTenantId());
+        }
+        return added;
+    }
+    
+    /**
+     * Gets the past invoice for a given invoice id
+     * @param registry  is the GovernanceUserRegistry
+     * @param invoiceId is the expected invoice id
+     * @return  a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    private MultitenancyInvoice getPastInvoiceById(UserRegistry registry,
+                                               int invoiceId) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        Invoice invoice = billingEngine.getInvoice(invoiceId);
+        if (invoice == null) {
+            return null;
+        }
+        
+        Customer customer = getCurrentCustomer(registry, billingEngine);
+        if (customer == null || customer.getId() != invoice.getCustomer().getId()) {
+            String msg = "Trying to looking at an invoice of another customer, customer: " +
+                            (customer == null ? "unknown" : customer.getId()) + ", invoice: " +
+                            invoice.getId() + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        
+        MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+        multitenancyInvoice.setInvoiceId(invoice.getId());
+        multitenancyInvoice.setBillingDate(invoice.getDate());
+        multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+        multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+        multitenancyInvoice.setStartDate(invoice.getStartDate());
+        multitenancyInvoice.setEndDate(invoice.getEndDate());
+        multitenancyInvoice.setTotalCost(invoice.getTotalCost().serializeToString());
+        multitenancyInvoice.setTotalPayments(invoice.getTotalPayment().serializeToString());
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        MultitenancySubscription[] multitenancySubscriptions =
+                new MultitenancySubscription[subscriptions.size()];
+        for (int i = 0; i < subscriptions.size(); i++) {
+            Subscription subscription = subscriptions.get(i);
+            MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+            multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+            multitenancySubscription.setActiveSince(subscription.getActiveSince());
+            multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+            multitenancySubscription.setActive(subscription.isActive());
+
+            // now iterating the items
+            List<Item> billedItems = billingEngine.getBilledItems(subscription);
+            BilledEntry[] itemEntries = new BilledEntry[billedItems.size()];
+            for (int j = 0; j < billedItems.size(); j++) {
+                Item billedItem = billedItems.get(j);
+                if (billedItem.getName().equals(multitenancySubscription.getSubscribedPackage())) {
+                    // ignoring the parent item..
+                    continue;
+                }
+                BilledEntry itemEntry = new BilledEntry();
+                itemEntry.setName(billedItem.getDescription());
+                itemEntry.setCost(billedItem.getCost().serializeToString());
+                itemEntries[j] = itemEntry;
+            }
+            multitenancySubscription.setBilledEntries(itemEntries);
+            multitenancySubscriptions[i] = multitenancySubscription;
+        }
+
+        multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+        // getting the purchase orders
+        List<Payment> payments = invoice.getPayments();
+        if (payments != null) {
+            MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+                    new MultitenancyPurchaseOrder[payments.size()];
+
+            for (int i = 0; i < payments.size(); i++) {
+                Payment payment = payments.get(i);
+                MultitenancyPurchaseOrder multitenancyPurchaseOrder =
+                        new MultitenancyPurchaseOrder();
+
+                multitenancyPurchaseOrder.setId(payment.getId());
+                multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+                multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+                multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+                multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+            }
+            multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+        }
+
+        return multitenancyInvoice;
+    }
+
+    /**
+     * Gets the interim invoice of the current customer
+     * @param registry is the GovernanceUserRegistry
+     * @return an MultiTenancyInvoice object
+     * @throws Exception Exception
+     */
+    private MultitenancyInvoice getCurrentInvoiceOfCustomer(UserRegistry registry) throws Exception {
+        // we have to generate the invoice for this.
+        
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngineViewer =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Customer customer = getCurrentCustomer(registry, billingEngineViewer);
+        if (customer == null) {
+            // no customer => no invoices
+            return null;
+        }
+        
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        billingEngineContext.setCustomer(customer);
+        billingEngineViewer.generateBill(billingEngineContext);
+
+        // reloading the customer with new updates
+        customer = billingEngineContext.getCustomer();
+        Invoice invoice = customer.getActiveInvoice();
+
+        // convert it and return
+        if (invoice == null) {
+            return null;
+        }
+
+        if (customer.getId() != invoice.getCustomer().getId()) {
+            String msg = "Trying to looking at an invoice of another customer, customer: " +
+                            customer.getId() + ", invoice: " + invoice.getId() + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        
+        MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+        multitenancyInvoice.setBillingDate(invoice.getDate());
+        multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+        multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+        multitenancyInvoice.setEndDate(invoice.getEndDate());
+        multitenancyInvoice.setInvoiceId(invoice.getId());
+        multitenancyInvoice.setStartDate(invoice.getStartDate());
+        
+        // getting the purchase orders
+        List<Payment> payments = invoice.getPayments();
+        MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+                new MultitenancyPurchaseOrder[payments.size()];
+        for (int i = 0; i < payments.size(); i++) {
+            Payment payment = payments.get(i);
+            MultitenancyPurchaseOrder multitenancyPurchaseOrder = new MultitenancyPurchaseOrder();
+            multitenancyPurchaseOrder.setId(payment.getId());
+            multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+            multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+            multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+            multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+        }
+        multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        MultitenancySubscription[] multitenancySubscriptions =
+                new MultitenancySubscription[subscriptions.size()];
+        for (int i = 0; i < subscriptions.size(); i++) {
+            Subscription subscription = subscriptions.get(i);
+            MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+            multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+            multitenancySubscription.setActiveSince(subscription.getActiveSince());
+            multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+            multitenancySubscription.setActive(subscription.isActive());
+
+            BilledEntry[] itemEntries;
+            List<? extends Item> subItems = subscription.getItem().getChildren();
+            if(subItems!=null){
+                itemEntries = new BilledEntry[subItems.size()];
+                for(int j=0; j<subItems.size(); j++){
+                    BilledEntry billedEntry = new BilledEntry();
+                    Item billedItem = subItems.get(j);
+                    billedEntry.setName(billedItem.getDescription()); //description
+                    if(billedItem.getCost()!=null){
+                        billedEntry.setCost(billedItem.getCost().toString());   //cost
+                    }else{
+                        billedEntry.setCost(new Cash("$0").toString());
+                    }
+                    itemEntries[j] = billedEntry;
+                }
+            }else{
+                itemEntries = new BilledEntry[0];
+            }
+
+
+            multitenancySubscription.setBilledEntries(itemEntries);
+            multitenancySubscriptions[i] = multitenancySubscription;
+        }
+        multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+        Cash totalCost = invoice.getTotalCost();
+        if (totalCost == null) {
+            totalCost = new Cash("$0");
+        }
+        multitenancyInvoice.setTotalCost(totalCost.serializeToString());
+        
+        Cash totalPaymentCash = invoice.getTotalPayment();
+        if (totalPaymentCash == null) {
+            totalPaymentCash = new Cash("$0");
+        }
+        multitenancyInvoice.setTotalPayments(totalPaymentCash.serializeToString());
+
+        return multitenancyInvoice;
+    }
+
+    /**
+     * Gets the tenant is and then fills the customer details
+     * @param userRegistry to get the tenant id
+     * @param billingEngine to fill the customer details
+     * @return   a customer object
+     * @throws Exception Exception
+     */
+    private Customer getCurrentCustomer(UserRegistry userRegistry,
+                                        BillingEngine billingEngine) throws Exception {
+        int currentTenantId = userRegistry.getTenantId();
+        TenantManager tenantManger = Util.getRealmService().getTenantManager();
+        Tenant currentTenant = (Tenant) tenantManger.getTenant(currentTenantId);
+
+        List<Customer> customers = billingEngine.getCustomersWithName(currentTenant.getDomain());
+        if (customers == null || customers.isEmpty()) {
+            return null;
+        }
+        return customers.get(0);
+    }
+
+    private BillingPeriod[] getAvailableBillingPeriods(UserRegistry registry) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        
+        Customer customer = getCurrentCustomer(registry, billingEngine);
+        if (customer == null) {
+            return new BillingPeriod[0];
+        }
+        
+        List<Invoice> invoices = billingEngine.getInvoices(customer);
+        if (invoices == null || invoices.size() == 0) {
+            return new BillingPeriod[0];
+        }
+        
+        return getBillingPeriodsFromInvoices(invoices);
+    }
+
+    /**
+     * Get the billing period details when given the invoices
+     * @param invoices is list of invoices
+     * @return an array of billing periods
+     */
+    private BillingPeriod[] getBillingPeriodsFromInvoices(List<Invoice> invoices){
+        BillingPeriod[] billingPeriods = new BillingPeriod[invoices.size()];
+        int index = 0;
+        for (Invoice invoice : invoices) {
+            BillingPeriod billingPeriod = new BillingPeriod();
+            billingPeriod.setInvoiceId(invoice.getId());
+            billingPeriod.setStartDate(invoice.getStartDate());
+            billingPeriod.setEndDate(invoice.getEndDate());
+            billingPeriod.setInvoiceDate(invoice.getDate());
+            billingPeriods[index++] = billingPeriod;
+        }
+        return billingPeriods;
+    }
+
+    /**
+     * Sends the payment received email to the customer
+     * @param payment is the payment object with the payment details 
+     * @throws Exception Exception
+     */
+    private void sendPaymentReceivedEmail(Payment payment) throws Exception{
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        if(payment.getInvoice()!=null){
+            Invoice invoice = billingEngine.getInvoice(payment.getInvoice().getId());
+            if(invoice!=null){
+                Customer customer = invoice.getCustomer();
+                if(customer!=null){
+                    Map<String, String> mailParameters = new HashMap<String, String>();
+                    mailParameters.put("date",
+                            new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+                    mailParameters.put("transaction-id", payment.getDescription());
+                    mailParameters.put("amount", payment.getAmount().toString());
+                    mailParameters.put("invoice-id", String.valueOf(payment.getInvoice().getId()));
+
+                    try{
+                        String customerName =
+                                ClaimsMgtUtil.getFirstName(Util.getRealmService(), customer.getId());
+                        if(customerName!=null){
+                            mailParameters.put("customer-name", customerName);
+                        }else{
+                            mailParameters.put("customer-name", "");
+                        }
+
+                    }catch(Exception e){
+                        log.error("Could not get tenant information for tenant: " +
+                                customer.getName() + "\n" + e.getMessage());
+                        mailParameters.put("customer-name", "");
+                    }
+
+                    //sending the mail to the customer
+                    billingEngine.sendPaymentReceivedEmail(
+                            customer.getEmail(),
+                            BillingConstants.PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+                            mailParameters);
+
+                    String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+                    //customer's first name is not important to finance team. Therefore it is
+                    //being replace with the domain name
+                    mailParameters.put("customer-name", customer.getName());
+                    billingEngine.sendPaymentReceivedEmail(
+                            financeEmail,
+                            BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+                            mailParameters
+                    );
+                }else{
+                    String msg = "Cannot send email to customer. Customer details not available";
+                    log.error(msg);
+                    throw new Exception(msg);
+                }
+            }else{
+                String msg = "Cannot send email to customer. Invoice details not available";
+                log.error(msg);
+                throw new Exception(msg);
+            }
+        }else{
+            String msg = "Cannot send email to customer. Invoice Id is not available";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+
+    private void sendRegistrationPaymentReceivedEmail(Payment payment) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        String tenantDomain = payment.getDescription().split(" ")[0];
+        int tenantId = Util.getTenantManager().getTenantId(tenantDomain);
+        Tenant tenant = (Tenant) Util.getTenantManager().getTenant(tenantId);
+
+        Map<String, String> mailParameters = new HashMap<String, String>();
+        mailParameters.put("date", new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+        mailParameters.put("transaction-id", payment.getDescription().split(" ")[1]);
+        mailParameters.put("amount", payment.getAmount().toString());
+        mailParameters.put("invoice-id", "Registration - " + tenantDomain);
+        mailParameters.put("tenant-domain", tenantDomain);
+
+        String customerName = null;
+        String customerEmail = tenant.getEmail();
+        try {
+            customerName = ClaimsMgtUtil.getFirstName(Util.getRealmService(), tenantId);
+            if (customerName != null) {
+                mailParameters.put("customer-name", customerName);
+            } else {
+                mailParameters.put("customer-name", "");
+            }
+
+        } catch (Exception e) {
+            log.error("Could not get tenant information for tenant: " +
+                      customerName + "\n" + e.getMessage());
+            mailParameters.put("customer-name", "");
+        }
+
+        //sending the mail to the customer
+        billingEngine.sendPaymentReceivedEmail(
+                customerEmail,
+                BillingConstants.REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+                mailParameters);
+
+        String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+        //customer's first name is not important to finance team. Therefore it is
+        //being replace with the domain name
+        mailParameters.put("customer-name", customerName);
+        billingEngine.sendPaymentReceivedEmail(
+                financeEmail,
+                BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+                mailParameters
+        );
+
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
new file mode 100644
index 0000000..7c354e4
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
@@ -0,0 +1,173 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.billing.core.*;
+import org.wso2.carbon.billing.mgt.api.DefaultTenantBilling;
+import org.wso2.carbon.billing.mgt.api.MultitenancyBillingInfo;
+import org.wso2.carbon.billing.mgt.handlers.MultitenancySubscriptionFeedingHandler;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.usage.api.TenantUsageRetriever;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.throttling.agent.ThrottlingAgent;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+public class Util {
+    private static BillingManager billingManager = null;
+    private static DataAccessManager dataAccessManager = null;
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static TenantUsageRetriever tenantUsageRetriever;
+    private static MultitenancyBillingInfo billingInfo;
+
+    public static ConfigurationContextService getContextService() {
+        return contextService;
+    }
+
+    public static void setContextService(ConfigurationContextService contextService) {
+        Util.contextService = contextService;
+    }
+
+    private static ServiceTracker throttlingRuleInvokerTracker = null;
+    private static BundleContext bundleContext;
+    private static Log log = LogFactory.getLog(Util.class);
+    private static ConfigurationContextService contextService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static void setTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        Util.tenantUsageRetriever = tenantUsageRetriever;
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static TenantUsageRetriever getTenantUsageRetriever() {
+        return tenantUsageRetriever;
+    }
+
+    public static TenantManager getTenantManager() {
+        if (realmService == null) {
+            return null;
+        }
+        return realmService.getTenantManager();
+    }
+
+    public static BillingManager getBillingManager() {
+        return billingManager;
+    }
+
+    public static void setBillingManager(BillingManager billingManager) {
+        Util.billingManager = billingManager;
+    }
+
+    public static void registerSubscriptionFeedingHandlers(BundleContext bundleContext) {
+        bundleContext.registerService(BillingHandler.class.getName(),
+                new MultitenancySubscriptionFeedingHandler(), null);
+    }
+    
+    public static void registerTenantBillingService(BundleContext bundleContext) {
+        bundleContext.registerService(TenantBillingService.class.getName(),
+                new DefaultTenantBilling(), null);
+    }
+
+    public static void scheduleBilling() throws BillingException {
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_SCHEDULED_TASK_ID);
+        if (billingEngine != null) {
+            billingEngine.scheduleBilling();
+        } else {
+            log.info("No billing engine for scheduled tasks");
+        }
+
+    }
+
+    public static void registerBillingInfo(BundleContext bundleContext) throws Exception {
+        billingInfo = new MultitenancyBillingInfo();
+        bundleContext.registerService(MultitenancyBillingInfo.class.getName(), billingInfo, null);
+    }
+
+    public static MultitenancyBillingInfo getMultitenancyBillingInfo() {
+        return billingInfo;
+    }
+
+    public static DataAccessManager getDataAccessManager() {
+        return dataAccessManager;
+    }
+
+    public static void setDataAccessManager(DataAccessManager dataAccessManager) {
+        Util.dataAccessManager = dataAccessManager;
+    }
+
+    public static void initDataAccessManager() {
+        DataAccessManager dataAccessManager = new DataAccessManager(
+                billingManager.getBillingConfiguration().getDataSource());
+        Util.dataAccessManager = dataAccessManager;
+    }
+
+    /**
+     * This method used to create service tracker that tracks throttlingAgent service which
+     * registered when throttling agent starts
+     *
+     * @param bundleContext bundle context that belongs to component
+     */
+    public static void initializeThrottling(BundleContext bundleContext) {
+        throttlingRuleInvokerTracker = new ServiceTracker(bundleContext, ThrottlingAgent.class.getName(),
+                null);
+        throttlingRuleInvokerTracker.open();
+    }
+
+    /**
+     * This method updates the throttling rules for given tenant and update the cache at manager
+     *
+     * @param tenantId Tenant Id of the tenant that need to update throttling rules at manager
+     */
+    public static void executeThrottlingRules(int tenantId) {
+        try {
+            ThrottlingAgent embeddedRuleInvoker =
+                    (ThrottlingAgent) throttlingRuleInvokerTracker.getService();
+            if (embeddedRuleInvoker != null) {
+                embeddedRuleInvoker.executeThrottlingRules(tenantId);
+            }
+        } catch (Exception e) {
+            log.error("Error in executing throttling rules in manager" + e.toString());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..71e6e35
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+  ~
+  ~  Licensed under the Apache License, Version 2.0 (the "License");
+  ~  you may not use this file except in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~       http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing, software
+  ~  distributed under the License is distributed on an "AS IS" BASIS,
+  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~  See the License for the specific language governing permissions and
+  ~  limitations under the License.
+  -->
+
+<component xmlns="http://products.wso2.org/carbon">
+    <ManagementPermissions>
+        <ManagementPermission>
+            <DisplayName>Billing</DisplayName>
+            <ResourceId>/permission/admin/billing</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>View Invoice</DisplayName>
+            <ResourceId>/permission/admin/billing/invoice</ResourceId>
+        </ManagementPermission>
+    </ManagementPermissions>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..3aaf3de
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<!--
+		! ! Copyright 2006 The Apache Software Foundation. ! ! Licensed under
+		the Apache License, Version 2.0 (the "License"); ! you may not use
+		this file except in compliance with the License. ! You may obtain a
+		copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0
+		! ! Unless required by applicable law or agreed to in writing,
+		software ! distributed under the License is distributed on an "AS IS"
+		BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+		or implied. ! See the License for the specific language governing
+		permissions and ! limitations under the License. !
+	-->
+<serviceGroup>
+
+	<service name="MultitenancyBillingService" scope="transportsession">
+		<transports>
+			<transport>https</transport>
+		</transports>
+
+		<parameter name="ServiceClass" locked="false">
+			org.wso2.carbon.billing.mgt.services.BillingService
+        </parameter>
+
+        <parameter name="adminService" locked="true">true</parameter>
+
+        <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+        <operation name="getPaginatedBalances">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getOutstandingBalance">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getAvailableBillingPeriodsBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="makeAdjustment">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="addRegistrationPayment">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+  	</service>
+
+    <service name="BillingDataAccessService" scope="transportsession">
+        <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+		<transports>
+			<transport>https</transport>
+		</transports>
+
+		<parameter name="ServiceClass" locked="false">
+			org.wso2.carbon.billing.mgt.services.BillingDataAccessService
+        </parameter>
+
+        <parameter name="adminService" locked="true">true</parameter>
+
+        <operation name="changeSubscriptionBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="deactivateActiveSubscriptionBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getActiveSubscriptionOfCustomerBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="addSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getInactiveSubscriptionsOfCustomer">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="activateSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+        
+        <operation name="changeSubscriptionForTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+  	</service>
+
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/pom.xml b/components/stratos/billing/pom.xml
new file mode 100644
index 0000000..ade5567
--- /dev/null
+++ b/components/stratos/billing/pom.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>billing-parent</artifactId>
+    <packaging>pom</packaging>
+    <name>WSO2 Stratos - Billing Parent Module</name>
+    <description>WSO2 Stratos Billing Parent Module</description>
+    <url>http://wso2.org</url>
+
+    <modules>
+        <module>org.wso2.carbon.billing.core/2.1.0</module>
+        <module>org.wso2.carbon.billing.mgt/2.1.0</module>
+        <module>org.wso2.carbon.billing.mgt.ui/2.1.0</module>
+    </modules>
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/pom.xml b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/pom.xml
new file mode 100644
index 0000000..1327c11
--- /dev/null
+++ b/components/stratos/cartridge-agent/org.wso2.carbon.cartridge.agent/2.1.3/pom.xml
@@ -0,0 +1,115 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- # Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. 
+	# # Licensed under the Apache License, Version 2.0 (the "License"); # you 
+	may not use this file except in compliance with the License. # You may obtain 
+	a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # 
+	# Unless required by applicable law or agreed to in writing, software # distributed 
+	under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES 
+	OR CONDITIONS OF ANY KIND, either express or implied. # See the License for 
+	the specific language governing permissions and # limitations under the License. -->
+<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.wso2.carbon</groupId>
+		<artifactId>cartridge-agent-parent</artifactId>
+		<version>2.1.0</version>
+                <relativePath>../../pom.xml</relativePath>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.wso2.carbon.cartridge.agent</artifactId>
+        <packaging>bundle</packaging>
+        <version>2.1.3</version>
+	<name>WSO2 Cartridge Agent - agent</name>
+
+	<dependencies>
+		<dependency>
+		<groupId>org.wso2.carbon</groupId>
+		<artifactId>org.wso2.carbon.cartridge.messages</artifactId>
+                <version>2.1.1</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.axis2.wso2</groupId>
+			<artifactId>axis2</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.ws.commons.axiom.wso2</groupId>
+			<artifactId>axiom</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>commons-logging</groupId>
+			<artifactId>commons-logging</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
+			<version>4.1.1</version>
+		</dependency>
+        <dependency>
+            <groupId>org.eclipse.osgi</groupId>
+            <artifactId>org.eclipse.osgi</artifactId>
+            <version>3.5.0.v20090311-1300</version>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.osgi</groupId>
+            <artifactId>org.eclipse.osgi.services</artifactId>
+            <version>3.3.0.v20110513</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.adc.instanceinfo.mgt.stub</artifactId>
+            <version>4.1.1</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>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Private-Package>
+                            org.wso2.carbon.cartridge.agent.internal.*,
+                            !org.wso2.carbon.cartridge.agent.service.*
+                        </Private-Package>
+                        <Export-Package>
+                            org.wso2.carbon.cartridge.agent.service.*,
+                            org.wso2.carbon.cartridge.agent.client.*,
+                            org.wso2.carbon.cartridge.agent.registrant.*,
+                            org.wso2.carbon.cartridge.agent.exception.*,
+                            org.wso2.carbon.cartridge.agent.*
+                        </Export-Package>
+                        <Import-Package>
+                            org.apache.axis2.*; version="${axis2.osgi.version.range}",
+                            org.apache.axiom.*;
+                            version="${axiom.osgi.version.range}",
+                            org.apache.neethi.*;
+                            version="${neethi.osgi.version.range.service-mgt}",
+                            javax.xml.stream.*; version="1.0.1",
+                            javax.wsdl.*; version="1.6.2",
+                            org.osgi.framework.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>


[50/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
new file mode 100644
index 0000000..5c3a54e
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/pom.xml
@@ -0,0 +1,200 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+        <artifactId>loadbalancer-components</artifactId>
+        <version>4.1.0</version>
+        <relativePath>../../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.autoscaler.service</artifactId>
+    <packaging>aar</packaging>
+    <name>WSO2 Carbon - Autoscaler Service</name>
+    <url>http://wso2.org</url>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>1.7.1</version>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <artifactSet>
+                                <includes>
+                                    <include>org.jclouds:*</include>
+                                    <include>org.jclouds.*:*</include>
+                                </includes>
+                            </artifactSet>
+                            <filtering>true</filtering>
+                            <filters>
+                                <filter>
+                                    <artifact>org.jclouds*:*</artifact>
+                                    <includes>
+                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
+                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
+                                    </includes>
+                                </filter>
+                            </filters>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
+                                </transformer>
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.axis2</groupId>
+                <artifactId>axis2-aar-maven-plugin</artifactId>
+                <version>1.4</version>
+                <extensions>true</extensions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.wso2.carbon.autoscaler.service
+                        </Export-Package>
+                        <Private-Package>
+                            org.wso2.carbon.autoscaler.service.*, !org.wso2.carbon.autoscaler.service
+                        </Private-Package>
+                        <Import-Package>
+                        	  !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
+                            org.jclouds*;version="${jclouds.version}",
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.lb.common</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.securevault</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <!--dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>${synapse.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-commons</artifactId>
+            <version>${synapse.version}</version>
+        </dependency--> 
+	
+        <!--  Jclouds dependencies -->
+         <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-allcompute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-compute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-bouncycastle</artifactId>
+           <version>${jclouds.version}</version>
+           <exclusions>
+              <exclusion>
+                 <groupId>org.bouncycastle</groupId>
+                 <artifactId>bcprov-jdk16</artifactId>
+              </exclusion>
+           </exclusions>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-sshj</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-log4j</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-enterprise</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <!--dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.provider</groupId>
+           <artifactId>aws-ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-nova</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency-->
+       
+    </dependencies>
+    
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
new file mode 100644
index 0000000..05269d6
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/IAutoscalerService.java
@@ -0,0 +1,111 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service;
+
+import org.wso2.carbon.lb.common.conf.util.Constants;
+
+/**
+ * This Interface provides a way for a component, to communicate with an underline
+ * Infrastructure which are supported by <i>JClouds</i>.
+ * 
+ */
+public interface IAutoscalerService {
+    
+    /**
+     * Initialize the service.
+     * @param isSpi if this service is to be used by SPI, this parameter should be set to
+     * true. When this is true, you should specify an image id, each time you
+     * are starting an instance i.e. you should use {@link #startSpiInstance(String, String)}
+     * method, instead of using {@link #startInstance(String)}.
+     * @return
+     */
+    public boolean initAutoscaler(boolean isSpi);
+
+    
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. This method is non-blocking, means we do not
+     * wait till the instance is started up. Also note that the instance that is starting up
+     * belongs to the group whose name is derived from its service domain, replacing <i>.</i>
+     * by a hyphen (<i>-</i>). 
+     * @param domainName service clustering domain of the instance to be started up.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is 
+     * {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether the starting up is successful or not.
+     */
+    public boolean startInstance(String domainName, String sudDomainName);
+    
+    /**
+     * Calling this method will result in an instance startup, which is belong
+     * to the provided service domain. This method will return the public IP address of
+     * the instance that is started. Thus, this method is blocking, since we need to 
+     * return the IP Address and for that we have to wait till the instance started up.
+     * @param domainName should be in following format.
+     * <code>${service-domain}\t\${tenant-id}</code>.
+     * @param imageId starting instance will be an instance of this image. Image id should
+     * be a valid one.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is 
+     * {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return public IP address of the instance in String format. If instance failed to 
+     * start, this will return an empty String.
+     */
+    public String startSpiInstance(String domainName, String subDomainName, String imageId);
+    
+   
+    /**
+     * Calling this method will result in termination of an instance which is belong
+     * to the provided service domain.
+     * @param domainName service domain of the instance to be terminated.
+     * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+     * @return whether an instance terminated successfully or not.
+     */
+	public boolean terminateInstance(String domainName, String subDomainName);
+	
+	/**
+	 * Calling this method will result in termination of the lastly spawned instance which is
+	 * belong to the provided service domain.
+	 * @param domainName service domain of the instance to be terminated.
+	 * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+	 * @return whether the termination is successful or not.
+	 */
+	public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName);
+	
+	/**
+     * Calling this method will result in termination of an instance which has the
+     * provided public IP address.
+     * @param publicIp public IP address of the instance to be terminated.
+     * @return whether the instance terminated successfully or not.
+     */
+    public boolean terminateSpiInstance(String publicIp);
+	
+	/**
+	 * Calling this method will result in returning the pending instances
+	 * count of a particular domain.
+	 * @param domainName service domain
+	 * @param sudDomainName service clustering sub domain of the instance to be started up.
+     * If this is null, the default value will be used. Default value is {@link Constants}.DEFAULT_SUB_DOMAIN.
+	 * @return number of pending instances for this domain. If no instances of this 
+	 * domain is present, this will return zero.
+	 */
+	public int getPendingInstanceCount(String domainName, String subDomainName);
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
new file mode 100644
index 0000000..4b6818a
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/AutoscalerServiceException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.exception;
+
+public class AutoscalerServiceException extends RuntimeException {
+    
+    private static final long serialVersionUID = -6326227079367867222L;
+
+    public AutoscalerServiceException(String msg) {
+        super(msg);
+    }
+    
+    public AutoscalerServiceException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
new file mode 100644
index 0000000..377a641
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/DeserializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.exception;
+
+public class DeserializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -2426068347954381831L;
+
+    public DeserializationException(String msg) {
+        super(msg);
+    }
+    
+    public DeserializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
new file mode 100644
index 0000000..4065417
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/MalformedConfigurationFileException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.exception;
+
+public class MalformedConfigurationFileException extends RuntimeException {
+
+    private static final long serialVersionUID = -1662095377704279326L;
+    
+    public MalformedConfigurationFileException(String msg) {
+        super(msg);
+    }
+    
+    public MalformedConfigurationFileException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
new file mode 100644
index 0000000..0888a3c
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/NoInstanceFoundException.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.autoscaler.service.exception;
+
+/**
+ * This will throw when no instance is found
+ */
+public class NoInstanceFoundException extends Exception {
+
+    /**
+     * For serializing requirement
+     */
+    private static final long serialVersionUID = -435060299292679892L;
+
+
+    public NoInstanceFoundException(String msg) {
+        super(msg);
+    }
+    
+    public NoInstanceFoundException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
new file mode 100644
index 0000000..06ff6d2
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/exception/SerializationException.java
@@ -0,0 +1,32 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.exception;
+
+public class SerializationException extends RuntimeException {
+    
+    private static final long serialVersionUID = -3701458642228072331L;
+
+    public SerializationException(String msg) {
+        super(msg);
+    }
+    
+    public SerializationException(String msg, Exception ex) {
+        super(msg, ex);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
new file mode 100644
index 0000000..f77eb52
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/impl/AutoscalerServiceImpl.java
@@ -0,0 +1,1388 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.autoscaler.service.impl;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.RunNodesException;
+import org.jclouds.compute.domain.ComputeMetadata;
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadata.Status;
+import org.jclouds.compute.domain.Template;
+import org.jclouds.compute.domain.TemplateBuilder;
+import org.jclouds.compute.domain.internal.NodeMetadataImpl;
+import org.jclouds.compute.options.TemplateOptions;
+import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
+import org.wso2.carbon.autoscaler.service.IAutoscalerService;
+import org.wso2.carbon.autoscaler.service.exception.AutoscalerServiceException;
+import org.wso2.carbon.autoscaler.service.exception.DeserializationException;
+import org.wso2.carbon.autoscaler.service.exception.SerializationException;
+import org.wso2.carbon.autoscaler.service.io.Deserializer;
+import org.wso2.carbon.autoscaler.service.io.Serializer;
+import org.wso2.carbon.autoscaler.service.jcloud.ComputeServiceBuilder;
+import org.wso2.carbon.autoscaler.service.util.AutoscalerConstant;
+import org.wso2.carbon.autoscaler.service.util.IaasContext;
+import org.wso2.carbon.autoscaler.service.util.IaasProvider;
+import org.wso2.carbon.autoscaler.service.util.InstanceContext;
+import org.wso2.carbon.autoscaler.service.util.ServiceTemplate;
+import org.wso2.carbon.autoscaler.service.xml.ElasticScalerConfigFileReader;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Autoscaler Service is responsible for starting up new server instances, terminating already
+ * started instances, providing pending instance count.
+ * 
+ */
+public class AutoscalerServiceImpl implements IAutoscalerService {
+
+	
+	private static final Log log = LogFactory.getLog(AutoscalerServiceImpl.class);
+
+    /**
+     * pointer to Carbon Home directory.
+     */
+    private static final String CARBON_HOME = CarbonUtils.getCarbonHome();
+
+    /**
+     * pointer to Carbon Temp directory.
+     */
+    private static final String CARBON_TEMP = CarbonUtils.getTmpDir();
+
+    /**
+     * Tenant id Delimiter
+     */
+	private static final String TENANT_ID_DELIMITER = "/t/";
+
+    /**
+     * This directory will be used to store serialized objects.
+     */
+    private String serializationDir;
+
+    /**
+     * List of all <code>IaaSProviders</code> specified in the config file.
+     */
+    private List<IaasProvider> iaasProviders;
+
+    /**
+     * List of all <code>ServiceTemplate</code> objects.
+     */
+    private List<ServiceTemplate> serviceTemps;
+
+    /**
+     * We keep an enum which contains all supported IaaSes.
+     */
+    public enum Iaases {
+        ec2, openstack
+    };
+
+    /**
+     * List which keeps <code>IaasContext</code> objects.
+     */
+    private List<IaasContext> iaasContextList = new ArrayList<IaasContext>();
+
+    /**
+     * We keep track of the IaaS where the last instance of a domain and a sub domain combination is spawned.
+     * This is required when there are multiple <code>IaasProvider</code>s defined.
+     * Key - domain
+     * Value - a map which has a Key - sub domain and Value - name of the {@link IaasProvider}.
+     */
+    private Map<String, Map<String, String>> lastlyUsedIaasMap = new HashMap<String, Map<String, String>>();
+
+    /**
+     * To track whether the {@link #initAutoscaler(boolean)} method has been called.
+     */
+    boolean isInitialized = false;
+
+    @Override
+    public boolean initAutoscaler(boolean isSpi) {
+
+        if (!isInitialized) {
+
+            log.debug("InitAutoscaler has started ...  IsSPI : " + isSpi);
+
+            // load configuration file
+            ElasticScalerConfigFileReader configReader = new ElasticScalerConfigFileReader();
+
+            // read serialization directory from config file if specified, else will use the
+            // default.
+            if ("".equals(serializationDir = configReader.getSerializationDir())) {
+                serializationDir = CARBON_TEMP;
+
+                log.debug("Directory to be used to serialize objects: " + serializationDir);
+            }
+
+            // let's deserialize and load the serialized objects.
+            deserialize();
+
+            // from config file, we grab the details unique to IaaS providers.
+            iaasProviders = configReader.getIaasProvidersList();
+
+            // from config file, we grab the details related to each service domain.
+            serviceTemps = configReader.getTemplates();
+
+            // we iterate through each IaaSProvider which is loaded from the config file.
+            for (IaasProvider iaas : iaasProviders) {
+
+                // build the JClouds specific ComputeService object
+                ComputeService computeService = ComputeServiceBuilder.buildComputeService(iaas);
+                IaasContext entity;
+
+                // let's see whether there's a serialized entity
+                entity = findIaasContext(iaas.getType());
+
+                if (entity != null) {
+
+                    log.debug("Serializable object is loaded for IaaS " + iaas.getType());
+
+                    // ComputeService isn't serializable, hence we need to set it in the
+                    // deserialized
+                    // object.
+                    entity.setComputeService(computeService);
+                }
+
+                // build JClouds Template objects according to different IaaSes
+                if (iaas.getType().equalsIgnoreCase(Iaases.ec2.toString())) {
+
+                    // initiate the IaasContext object, if it is null.
+                    entity =
+                             (entity == null) ? (entity =
+                                                          new IaasContext(Iaases.ec2,
+                                                                          computeService)) : entity;
+
+                    // we should build the templates only if this is not SPI stuff
+                    if (!isSpi) {
+                        // Build the Template
+                        buildEC2Templates(entity, iaas.getTemplate(), isSpi);
+
+                    } else {
+                        // add to data structure
+                        iaasContextList.add(entity);
+                    }
+
+                } else if (iaas.getType().equalsIgnoreCase(Iaases.openstack.toString())) {
+
+                    // initiate the IaasContext object, if it is null.
+                    entity =
+                             (entity == null) ? (entity =
+                                                          new IaasContext(Iaases.openstack,
+                                                                          computeService)) : entity;
+
+                    // we should build the templates only if this is not SPI stuff
+                    if (!isSpi) {
+                        // Build the Template
+                        buildLXCTemplates(entity, iaas.getTemplate(), isSpi, null);
+
+                    } else {
+                        // add to data structure
+                        iaasContextList.add(entity);
+                    }
+
+                } else {
+                    // unsupported IaaS detected. We only complain, since there could be other
+                    // IaaSes.
+                    String msg =
+                                 "Unsupported IaasProvider is specified in the config file: " +
+                                         iaas.getType() + ". Supported IaasProviders are " +
+                                         print(Iaases.values());
+                    log.warn(msg);
+                    continue;
+                }
+
+                // populate scale up order
+                fillInScaleUpOrder();
+
+                // populate scale down order
+                fillInScaleDownOrder();
+
+                // serialize the objects
+                serialize();
+            }
+
+            // we couldn't locate any valid IaaS providers from config file, thus shouldn't proceed.
+            if (iaasContextList.size() == 0) {
+                String msg = "No valid IaaS provider specified in the config file!";
+                log.error(msg);
+                throw new AutoscalerServiceException(msg);
+            }
+
+            // initialization completed.
+            isInitialized = true;
+
+            log.info("Autoscaler service initialized successfully!!");
+
+            return true;
+        }
+        
+        log.debug("Autoscaler Service is already initialized!");
+        return false;
+    }
+
+    
+    @Override
+    public boolean startInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+
+        ComputeService computeService;
+        Template template;
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        log.info("Starting new instance of domain : " + domainName+" and sub domain : "+subDomainName);
+
+        // sort the IaasContext entities according to scale up order
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_UP_SORT)));
+
+        // traverse through IaasContext object instances in scale up order
+        for (IaasContext iaasCtxt : iaasContextList) {
+
+            // get the ComputeService
+            computeService = iaasCtxt.getComputeService();
+
+            // from the list grab the Template corresponds to this domain
+            template = iaasCtxt.getTemplate(domainName, subDomainName);
+            
+            if(template == null){
+                String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
+                        ". Reason : Template is null. You have not specify a matching service " +
+                        "element in the configuration file of Autoscaler.\n Hence, will try to " +
+                        "start in another IaaS if available.";
+                log.error(msg);
+                continue;
+            }
+
+            // generate the group id from domain name and sub domain name.
+            // Should have lower-case ASCII letters, numbers, or dashes.
+            String str = domainName.concat("-"+subDomainName);
+            String group = str.replaceAll("[^a-z0-9-]", "");
+
+            try {
+                // create and start a node
+                Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(group,
+                                                                                      1,
+                                                                                      template);
+
+                NodeMetadata node = nodes.iterator().next();
+
+//                // add the details of the started node to maps
+//                iaasCtxt.addNodeIdToDomainMap(node.getId(), domainName);
+                
+                String ip="";
+
+                // set public Ip, if it's available
+                if (node.getPublicAddresses().size() > 0) {
+                    ip = node.getPublicAddresses().iterator().next();
+//                    iaasCtxt.addPublicIpToDomainMap(publicIp, domainName);
+//                    iaasCtxt.addPublicIpToNodeIdMap(publicIp, node.getId());
+                } else if(node.getPrivateAddresses().size() > 0) { // set private IPs if no public IP s are returned
+                	ip = node.getPrivateAddresses().iterator().next();
+//                    iaasCtxt.addPublicIpToDomainMap(privateIp, domainName);
+//                    iaasCtxt.addPublicIpToNodeIdMap(privateIp, node.getId());
+                } else{
+                    log.debug("Public IP of the node : "+node.getId()+" cannot be found.");
+                }
+                
+        
+                if (iaasCtxt.getInstanceContext(domainName, subDomainName) == null) {
+                    String msg = "Failed to start an instance in " + iaasCtxt.getName().toString() +
+                            ". Reason : InstanceContext is null. Hence, will try to start in another IaaS if available.";
+                    log.error(msg);
+                    continue;
+                }
+                
+                if(node.getId() == null){
+                    String msg = "Node id of the starting instance is null.\n"+ node.toString();
+                    log.fatal(msg);
+                    throw new AutoscalerServiceException(msg);
+                }
+
+                // add run time data to InstanceContext
+                iaasCtxt.addNodeDetails(domainName, subDomainName, node.getId(), ip);
+                
+                // since we modified the IaasContext instance, let's replace it.
+                replaceIaasContext(iaasCtxt);
+
+                // update the lastlyUsedIaasMap
+                addToLastlyUsedIaasMap(domainName, subDomainName, iaasCtxt.getName().toString());
+//                lastlyUsedIaasMap.put(domainName, iaasCtxt.getName().toString());
+
+                if (log.isDebugEnabled()) {
+                    log.debug("Node details: \n" + node.toString() +
+                              "\n***************\n");
+                }
+
+            } catch (RunNodesException e) {
+                log.warn("Failed to start an instance in " + iaasCtxt.getName().toString() +
+                         ". Hence, will try to start in another IaaS if available.", e);
+                continue;
+            }
+
+            log.info("Instance is successfully starting up in IaaS " + iaasCtxt.getName()
+                                                                               .toString() + " ...");
+
+            // serialize the objects
+            serialize();
+
+            return true;
+        }
+
+        log.info("Failed to start instance, in any available IaaS.");
+
+        return false;
+
+    }
+
+    private String checkSubDomain(String subDomainName) {
+        // if sub domain is null, we assume it as default one.
+        if (subDomainName == null || "null".equalsIgnoreCase(subDomainName)) {
+            subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+            log.debug("Sub domain is null, hence using the default value : " + subDomainName);
+        }
+        
+        return subDomainName;
+    }
+
+
+    private void addToLastlyUsedIaasMap(String domainName, String subDomainName, String iaasName) {
+
+        Map<String, String> map;
+        
+        if(lastlyUsedIaasMap.get(domainName) == null){
+            map = new HashMap<String, String>();
+            
+        } else{
+            map = lastlyUsedIaasMap.get(domainName);
+        }
+        
+        map.put(subDomainName, iaasName);
+        lastlyUsedIaasMap.put(domainName, map);
+        
+    }
+
+
+    @Override
+    public String startSpiInstance(String domainName, String subDomainName, String imageId) {
+
+        log.debug("Starting an SPI instance ... | domain: " + domainName + " | sub domain: " +
+        subDomainName + " | ImageId: " + imageId);
+        
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(true);
+        
+        String tenantId = null;
+        String spiDomainName = null;       
+        
+        if(domainName != null) {
+        	// domainName will have the pattern <domainName>/t/<tenantId>
+        	String[] arr = domainName.split(TENANT_ID_DELIMITER);
+        	if(arr.length != 2) {
+        		String msg = "Domain name does not match with the expected pattern. Expected " +
+        				"pattern is <domainName>/t/<tenantId>";
+        		log.error(msg);
+        		throw new AutoscalerServiceException(msg);
+        	}
+        	spiDomainName = arr[0];
+        	tenantId = arr[1];
+        }
+        
+        IaasContext entry;
+
+        // FIXME: Build the Templates, for now we're doing a hack here. I don't know whether
+        // there's a proper fix.
+        // handle openstack case
+        if (imageId.startsWith("nova") && ((entry = findIaasContext(Iaases.openstack)) != null)) {
+
+            buildLXCTemplates(entry, imageId, true, tenantId);
+
+        } else if (((entry = findIaasContext(Iaases.ec2)) != null)) {
+
+            buildEC2Templates(entry, imageId, true);
+
+        } else {
+            String msg = "Invalid image id: " + imageId;
+            log.error(msg);
+            throw new AutoscalerServiceException(msg);
+        }
+
+        // let's start the instance
+        if (startInstance(spiDomainName, subDomainName)) {
+
+            // if it's successful, get the public IP of the started instance.
+            // FIXME remove --> String publicIP =
+            // findIaasContext(iaas).getLastMatchingPublicIp(domainName);
+            String publicIP = entry.getLastMatchingPublicIp(spiDomainName, subDomainName);
+
+            // if public IP is null, return an empty string, else return public IP.
+            return (publicIP == null) ? "" : publicIP;
+
+        }
+
+        return "";
+
+    }
+
+	@Override
+    public boolean terminateInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+	    initAutoscaler(false);
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        log.info("Starting to terminate an instance of domain : " + domainName + " and sub domain : "+subDomainName);
+
+        // sort the IaasContext entities according to scale down order.
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
+
+        // traverse in scale down order
+        for (IaasContext iaasTemp : iaasContextList) {
+
+            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
+                         ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+            String nodeId = null;
+
+            // grab the node ids related to the given domain and traverse
+            for (String id : iaasTemp.getNodeIds(domainName, subDomainName)) {
+                if (id != null) {
+                    nodeId = id;
+                    break;
+                }
+            }
+
+            // if no matching node id can be found.
+            if (nodeId == null) {
+
+                log.warn(msg + " : Reason- No matching instance found for domain: " +
+                         domainName + " and sub domain: "+subDomainName+
+                         ".");
+                continue;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+
+        }
+
+        log.info("Termination of an instance which is belong to domain '" + domainName +
+                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching " +
+                 		"running instance found in any available IaaS.");
+
+        return false;
+
+    }
+
+    @Override
+    public boolean terminateLastlySpawnedInstance(String domainName, String subDomainName) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+        
+        subDomainName = checkSubDomain(subDomainName);
+
+        // see whether there is a matching IaaS, where we spawn an instance belongs to given domain.
+        if (lastlyUsedIaasMap.containsKey(domainName)) {
+
+            // grab the name of the IaaS
+            String iaas = lastlyUsedIaasMap.get(domainName).get(subDomainName);
+
+            // find the corresponding IaasContext
+            IaasContext iaasTemp = findIaasContext(iaas);
+
+            String msg = "Failed to terminate the lastly spawned instance of '" + domainName +
+                         "' service domain.";
+
+            if (iaasTemp == null) {
+                log.error(msg + " : Reason- Iaas' data cannot be located!");
+                return false;
+            }
+
+            // find the instance spawned at last of this IaasContext
+            String nodeId = iaasTemp.getLastMatchingNode(domainName, subDomainName);
+
+            if (nodeId == null) {
+                log.error(msg + " : Reason- No matching instance found for domain: " +
+                        domainName + " and sub domain: "+subDomainName+
+                        ".");
+                return false;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+
+        }
+
+        log.info("Termination of an instance which is belong to domain '" + domainName +
+                 "' and sub domain '"+subDomainName+"' , failed!\n Reason: No matching instance found.");
+
+        return false;
+    }
+
+    @Override
+    public boolean terminateSpiInstance(String publicIp) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(true);
+
+        // sort the IaasContext entities according to scale down order.
+        Collections.sort(iaasContextList,
+                         IaasContextComparator.ascending(IaasContextComparator.getComparator(IaasContextComparator.SCALE_DOWN_SORT)));
+
+        // traverse in scale down order
+        for (IaasContext iaasTemp : iaasContextList) {
+
+            String msg = "Failed to terminate an instance in " + iaasTemp.getName().toString() +
+                         "" +
+                         ". Hence, will try to terminate an instance in another IaaS if possible.";
+
+            // grab the node maps with the given public IP address
+            String nodeId = iaasTemp.getNodeWithPublicIp(publicIp);
+
+            if (nodeId == null) {
+                log.warn(msg + " : Reason- No matching instance found for public ip '" +
+                         publicIp +
+                         "'.");
+                continue;
+            }
+
+            // terminate it!
+            terminate(iaasTemp, nodeId);
+
+            return true;
+        }
+
+        log.info("Termination of an instance which has the public IP '" + publicIp + "', failed!");
+
+        return false;
+    }
+
+    @Override
+    public int getPendingInstanceCount(String domainName, String subDomain) {
+
+        // initialize the service, if it's not already initialized.
+        initAutoscaler(false);
+        
+        subDomain = checkSubDomain(subDomain);
+
+        int pendingInstanceCount = 0;
+
+        // traverse through IaasContexts
+        for (IaasContext entry : iaasContextList) {
+
+            ComputeService computeService = entry.getComputeService();
+
+            // get list of node Ids which are belong to the requested domain
+            List<String> nodeIds = entry.getNodeIds(domainName, subDomain);
+            
+            if(nodeIds.isEmpty()){
+                log.debug("Zero nodes spawned in the IaaS "+entry.getName()+
+                          " of domain: "+domainName+" and sub domain: "+subDomain);
+                continue;
+            }
+
+            // get all the nodes spawned by this IaasContext
+            Set<? extends ComputeMetadata> set = computeService.listNodes();
+
+            Iterator<? extends ComputeMetadata> iterator = set.iterator();
+
+            // traverse through all nodes of this ComputeService object
+            while (iterator.hasNext()) {
+                NodeMetadataImpl nodeMetadata = (NodeMetadataImpl) iterator.next();
+
+                // if this node belongs to the requested domain
+                if (nodeIds.contains(nodeMetadata.getId())) {
+
+                    // get the status of the node
+                    Status nodeStatus = nodeMetadata.getStatus();
+
+                    // count nodes that are in pending state
+                    if (nodeStatus.toString().equalsIgnoreCase("PENDING")) {
+                        pendingInstanceCount++;
+                    }
+                }
+
+            }
+        }
+
+        log.info("Pending instance count of domain '" + domainName + "' and sub domain '"+
+        subDomain+"' is " + pendingInstanceCount);
+
+        return pendingInstanceCount;
+
+    }
+
+    /**
+     * Returns matching IaasContext for the given {@link Iaases} entry.
+     */
+    private IaasContext findIaasContext(Enum<Iaases> iaas) {
+
+        for (IaasContext entry : iaasContextList) {
+            if (entry.getName().equals(iaas)) {
+                return entry;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Returns matching IaasContext for the given iaas type.
+     */
+    private IaasContext findIaasContext(String iaasType) {
+
+        for (IaasContext entry : iaasContextList) {
+            if (entry.getName().toString().equals(iaasType)) {
+                return entry;	
+            }
+        }
+
+        return null;
+    }
+
+    private void fillInScaleDownOrder() {
+
+        for (IaasProvider iaas : iaasProviders) {
+            if (findIaasContext(iaas.getType()) != null) {
+                findIaasContext(iaas.getType()).setScaleDownOrder(iaas.getScaleDownOrder());
+            }
+        }
+
+    }
+
+    private void fillInScaleUpOrder() {
+
+        for (IaasProvider iaas : iaasProviders) {
+            if (findIaasContext(iaas.getType()) != null) {
+                findIaasContext(iaas.getType()).setScaleUpOrder(iaas.getScaleUpOrder());
+            }
+        }
+
+    }
+
+    private byte[] getUserData(String payloadFileName, String tenantId) {
+ 
+    	byte[] bytes = null;
+    	File outputFile = null;
+    	String tempfilename = UUID.randomUUID().toString();
+        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");
+            }
+            if(tenantId != null) {
+            	// Tenant Id is available. This is an spi scenario. Edit the payload content
+            	editPayload(tenantId,file,tempfilename);
+            	outputFile = new File(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfilename+".zip");
+            } else {
+            	outputFile = file;
+            }
+            bytes = getBytesFromFile(outputFile);
+
+        } catch (IOException e) {
+            handleException("Cannot read data from payload file " + payloadFileName, e);
+        }
+        
+        // Remove temporary payload file
+        if (tenantId != null) {
+            outputFile.delete();
+        }
+        
+        return bytes;
+    }
+
+    
+    private void editPayload(String tenantName, File file, String tempfileName) {
+		
+    	unzipFile(file, tempfileName);
+    	editContent(tenantName, file, tempfileName);
+    	zipPayloadFile(tempfileName);    	
+	}
+
+    
+    /**
+	 * unzips the payload file
+	 * 
+	 * @param file
+     * @param tempfileName 
+	 */
+	private void unzipFile(File file, String tempfileName) {
+		
+		int buffer = 2048;
+		BufferedOutputStream dest = null;
+		ZipInputStream zis = null;
+		
+		try {
+			FileInputStream fis = new FileInputStream(file);
+			zis = new ZipInputStream(new BufferedInputStream(fis));
+			ZipEntry entry;
+			
+			while ((entry = zis.getNextEntry()) != null) {
+
+				log.debug("Extracting: " + entry);
+				
+				int count;
+				byte data[] = new byte[buffer];
+				String outputFilename = tempfileName + File.separator + entry.getName();
+				createDirIfNeeded(tempfileName, entry);
+
+				// write the files to the disk
+				if (!entry.isDirectory()) {
+					FileOutputStream fos = new FileOutputStream(outputFilename);
+					dest = new BufferedOutputStream(fos, buffer);
+					while ((count = zis.read(data, 0, buffer)) != -1) {
+						dest.write(data, 0, count);
+					}
+					dest.flush();
+					dest.close();
+				}
+			}
+			
+		} catch (Exception e) {
+			log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
+			throw new AutoscalerServiceException(e.getMessage(), e);
+		} finally {
+			closeStream(zis);			
+			closeStream(dest);
+		}
+	}
+
+
+	private void closeStream(Closeable stream) {
+		if (stream != null) {
+			try {
+				stream.close();
+			} catch (IOException e) {
+				log.error(" Exception is occurred when closing stream. Reason :" + e.getMessage());
+			}
+		}
+	}
+
+	/**
+	 * 
+	 * Modify contents (tenantName) of the debian_cron_script.sh file
+	 * 
+	 * @param tenantName
+	 * @param file
+	 */
+	private void editContent(String tenantName, File file, String tempfileName) {
+
+		File f = new File(CARBON_HOME + File.separator + tempfileName
+				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator
+				+ AutoscalerConstant.PARAMS_FILE_NAME);
+
+		FileInputStream fs = null;
+		InputStreamReader in = null;
+		BufferedReader br = null;
+
+		StringBuffer sb = new StringBuffer();
+
+		String textinLine;
+
+		try {
+			fs = new FileInputStream(f);
+			in = new InputStreamReader(fs);
+			br = new BufferedReader(in);
+
+			while (true) {
+				
+				textinLine=br.readLine();
+	            if(textinLine==null)
+	                break;
+	            sb.append(editLine(textinLine, tenantName));
+			}
+		} catch (Exception e) {
+			log.error("Exception is occurred in editing payload content. Reason: "+e.getMessage());
+			throw new AutoscalerServiceException(e.getMessage(), e);
+		} finally {
+			closeStream(fs);
+			closeStream(in);
+			closeStream(br);
+		}
+
+		writeChangesBackToFile(f, sb);
+	}
+
+
+	private String editLine(String textinLine, String tenantName) {
+		
+		// Format of the line will be <IP>=<IPvalue>,<Path>=<PathValue>..
+		
+		StringBuffer outputBuffer = new StringBuffer();
+		Map<String, String> paramMap = new HashMap<String, String>();
+		String[] params = textinLine.split(AutoscalerConstant.ENTRY_SEPARATOR);
+
+		for (int i = 0; i < params.length; i++) {
+
+			// split the params one by one
+			String param = params[i];
+			String[] values = param.split(AutoscalerConstant.VALUE_SEPARATOR);
+			
+			if(values.length != 2) {
+				throw new AutoscalerServiceException("Incorrect format in parameters file");
+			}
+			
+			String key = values[0];
+			String value = values[1];
+
+			String updatedValue = value;
+
+			if (AutoscalerConstant.TENANT_KEY.equals(key)) {
+				updatedValue = tenantName;
+			} else if (AutoscalerConstant.APP_PATH_KEY.equals(key)) {
+				updatedValue = getAppPathForTenant(tenantName,value);
+			} 
+			paramMap.put(key, updatedValue);
+		}
+
+		// Loop through the map and put values into a string
+		reOrganizeContent(outputBuffer, paramMap);
+
+		// cleanup output buffer
+		if (outputBuffer.substring(0, 1).equals(AutoscalerConstant.ENTRY_SEPARATOR)) {
+			outputBuffer.delete(0, 1);
+		}
+
+		return outputBuffer.toString();
+	}
+
+
+	private void reOrganizeContent(StringBuffer outputBuffer, Map<String, String> paramMap) {
+		
+		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
+			outputBuffer.append(AutoscalerConstant.ENTRY_SEPARATOR).append(entry.getKey()).append(AutoscalerConstant.VALUE_SEPARATOR)
+																		.append(entry.getValue());
+		}
+	}
+
+
+	private String getAppPathForTenant(String tenantName, String appPath) {
+		// Assumes app path is /opt/wso2-app/repository/
+		StringBuffer updatedAppPath = new StringBuffer();
+		if(tenantName.equals(AutoscalerConstant.SUPER_TENANT_ID)){ 
+			updatedAppPath.append(appPath).append("deployment").append(File.separator).append("server")
+															   .append(File.separator).append("phpapps");
+		}else{
+			updatedAppPath.append(appPath).append(tenantName).append(File.separator).append("phpapps");
+		}
+		return updatedAppPath.toString();
+	}
+
+
+	private void writeChangesBackToFile(File f, StringBuffer sb) {
+		FileWriter fstream = null;
+		BufferedWriter outobj = null;
+		
+		try {
+			fstream = new FileWriter(f);
+			outobj = new BufferedWriter(fstream);
+			outobj.write(sb.toString());
+		} catch (Exception e) {
+			throw new RuntimeException(e);
+		} finally {
+			closeStream(outobj);
+		}
+	}
+	
+	/**
+	 * 
+	 * Compress the modified files back into payload.zip
+	 * @param tempfileName 
+	 * 
+	 */
+	private void zipPayloadFile(String tempfileName) {
+		
+		int buffer = 2048;
+		BufferedInputStream origin = null;
+		ZipOutputStream out = null;
+		
+		try {
+	         
+	         FileOutputStream dest = new 
+	           FileOutputStream(CARBON_HOME + File.separator + AutoscalerConstant.RESOURCES_DIR + File.separator + tempfileName+".zip");
+	         out = new ZipOutputStream(new BufferedOutputStream(dest));
+	         byte data[] = new byte[buffer];
+	         
+	         File f = new File(CARBON_HOME + File.separator + tempfileName + File.separator + AutoscalerConstant.PAYLOAD_DIR);
+	         String files[] = f.list();
+
+	         for (int i=0; i<files.length; i++) {
+	            FileInputStream fi = new FileInputStream(CARBON_HOME + File.separator + tempfileName
+		 				+ File.separator + AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
+	            origin = new BufferedInputStream(fi, buffer);
+	            ZipEntry entry = new ZipEntry(AutoscalerConstant.PAYLOAD_DIR + File.separator + files[i]);
+	            out.putNextEntry(entry);
+	            
+	            int count;
+	            while((count = origin.read(data, 0, buffer)) != -1) {
+	               out.write(data, 0, count);
+	            }
+	            origin.close();
+	         }
+	         
+	         // delete temp files
+	         deleteDir(f);
+	         File fl = new File(CARBON_HOME + File.separator + tempfileName);
+	         fl.delete();
+	         
+	      } catch(Exception e) {
+	    	  log.error("Exception is occurred in zipping payload file after modification. Reason:" + e.getMessage());
+	    	  throw new AutoscalerServiceException(e.getMessage(),e);
+	      } finally {
+	    	  closeStream(origin);	    	  
+	    	  closeStream(out);
+	      }
+	}	
+
+	private static boolean deleteDir(File dir) {
+	    if (dir.isDirectory()) {
+	        String[] children = dir.list();
+	        for (int i=0; i<children.length; i++) {
+	            boolean success = deleteDir(new File(dir, children[i]));
+	            if (!success) {
+	                return false;
+	            }
+	        }
+	    }
+
+	    // The directory is now empty so delete it
+	    return dir.delete();
+	}
+
+	private void createDirIfNeeded(String destDirectory, ZipEntry entry) {
+		
+		String name = entry.getName();
+
+        if(name.contains("/"))
+        {
+            log.debug("directory will need to be created");
+
+            int index = name.lastIndexOf("/");
+            String dirSequence = name.substring(0, index);
+
+            File newDirs = new File(destDirectory + File.separator + dirSequence);
+
+            //create the directory
+            newDirs.mkdirs();
+        }
+		
+	}
+
+
+	/**
+     * 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.
+     */
+    private 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;
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     */
+    private void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+    /**
+     * handles the exception
+     * 
+     * @param msg
+     *            exception message
+     * @param e
+     *            exception
+     */
+    private static void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new SynapseException(msg, e);
+    }
+
+
+    /**
+     * This will replace an existing entry in iaasEntities list, if there's such.
+     * If not this will add the replacement value to the list.
+     * 
+     * @param replacement
+     *            IaasContext entry to be added.
+     */
+    private void replaceIaasContext(IaasContext replacement) {
+        for (IaasContext entry : iaasContextList) {
+            if (entry.equals(replacement)) {
+                int idx = iaasContextList.indexOf(entry);
+                iaasContextList.remove(idx);
+                iaasContextList.add(idx, replacement);
+                return;
+            }
+        }
+        iaasContextList.add(replacement);
+
+    }
+
+    /**
+     * Builds the LXC Template object.
+     */
+    private void buildLXCTemplates(IaasContext entity, String imageId, boolean blockUntilRunning, String tenantId) {
+
+        if (entity.getComputeService() == null) {
+            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
+        }
+
+//        // if domain to template map is null
+//        if (entity.getDomainToTemplateMap() == null) {
+//            // we initialize it
+//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
+//        }
+
+        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
+        templateBuilder.imageId(imageId);
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once!
+        for (org.wso2.carbon.autoscaler.service.util.ServiceTemplate temp : serviceTemps) {
+
+            String instanceType;
+
+            // set instance type 
+            if (((instanceType = temp.getProperty("instanceType." + Iaases.openstack.toString())) != null) ) {
+
+                templateBuilder.hardwareId(instanceType);
+            }
+
+            Template template = templateBuilder.build();
+
+            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .securityGroupNames(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
+
+            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
+                template.getOptions()
+                        .as(NovaTemplateOptions.class)
+                        .userData(getUserData(CARBON_HOME + File.separator +
+                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), tenantId));
+            }
+
+            template.getOptions()
+                    .as(NovaTemplateOptions.class)
+                    .keyPairName(temp.getProperty("keyPair"));
+
+            // add to the data structure
+            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
+                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
+                                                              temp.getSubDomainName(), template));
+            }
+            else{
+                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
+            }
+
+        }
+
+        // since we modified the Context, we need to replace
+        replaceIaasContext(entity);
+    }
+
+    /**
+     * Builds EC2 Template object
+     * 
+     */
+    private void buildEC2Templates(IaasContext entity, String imageId, boolean blockUntilRunning) {
+
+        if (entity.getComputeService() == null) {
+            throw new AutoscalerServiceException("Compute service is null for IaaS provider: " + entity.getName());
+        }
+
+//        // if domain to template map is null
+//        if (entity.getDomainToTemplateMap() == null) {
+//            // we initialize it
+//            entity.setDomainToTemplateMap(new HashMap<String, Template>());
+//        }
+
+        TemplateBuilder templateBuilder = entity.getComputeService().templateBuilder();
+
+        // set image id specified
+        templateBuilder.imageId(imageId);
+
+        // to avoid creation of template objects in each and every time, we create all
+        // at once! FIXME we could use caching and lazy loading
+        for (org.wso2.carbon.autoscaler.service.util.ServiceTemplate temp : serviceTemps) {
+
+            if (temp.getProperty("instanceType." + Iaases.ec2.toString()) != null) {
+                // set instance type eg: m1.large
+                templateBuilder.hardwareId(temp.getProperty("instanceType." + Iaases.ec2.toString()));
+            }
+
+            // build the Template
+            Template template = templateBuilder.build();
+
+            // make it non blocking
+            template.getOptions().as(TemplateOptions.class).blockUntilRunning(blockUntilRunning);
+
+            // set EC2 specific options
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .placementGroup(temp.getProperty("availabilityZone"));
+
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .securityGroups(temp.getProperty("securityGroups").split(AutoscalerConstant.ENTRY_SEPARATOR));
+
+            if (temp.getProperty(AutoscalerConstant.PAYLOAD_DIR) != null) {
+                template.getOptions()
+                        .as(AWSEC2TemplateOptions.class)
+                        .userData(getUserData(CARBON_HOME + File.separator +
+                                              temp.getProperty(AutoscalerConstant.PAYLOAD_DIR), null));
+            }
+
+            template.getOptions()
+                    .as(AWSEC2TemplateOptions.class)
+                    .keyPair(temp.getProperty("keyPair"));
+
+            // add to the data structure
+            if (entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()) == null) {
+                entity.addInstanceContext(new InstanceContext(temp.getDomainName(),
+                                                              temp.getSubDomainName(), template));
+            }
+            else{
+                entity.getInstanceContext(temp.getDomainName(), temp.getSubDomainName()).setTemplate(template);
+            }
+
+        }
+
+        // since we modified the Context, we need to replace
+        replaceIaasContext(entity);
+
+    }
+
+    private String print(Iaases[] values) {
+        String str = "";
+        for (Iaases iaases : values) {
+            str = iaases.name() + ", ";
+        }
+        str = str.trim();
+        return str.endsWith(AutoscalerConstant.ENTRY_SEPARATOR) ? str.substring(0, str.length() - 1) : str;
+    }
+
+    @SuppressWarnings("unchecked")
+    private void deserialize() {
+
+        String path;
+
+        try {
+            path = serializationDir + File.separator +
+                   AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE;
+
+            Object obj = Deserializer.deserialize(path);
+            if (obj != null) {
+                iaasContextList = (List<IaasContext>) obj;
+                log.debug("Deserialization was successful from file: " + path);
+            }
+
+            path = serializationDir + File.separator +
+                   AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE;
+
+            obj = Deserializer.deserialize(path);
+
+            if (obj != null) {
+                lastlyUsedIaasMap = (Map<String, Map<String, String>>) obj;
+                log.debug("Deserialization was successful from file: " + path);
+            }
+
+        } catch (Exception e) {
+            String msg = "Deserialization of objects failed!";
+            log.fatal(msg, e);
+            throw new DeserializationException(msg, e);
+        }
+
+    }
+
+    /**
+     * Does all the serialization stuff!
+     */
+    private void serialize() {
+
+        try {
+            Serializer.serialize(iaasContextList,
+                                 serializationDir + File.separator +
+                                         AutoscalerConstant.IAAS_CONTEXT_LIST_SERIALIZING_FILE);
+
+            Serializer.serialize(lastlyUsedIaasMap,
+                                 serializationDir + File.separator +
+                                         AutoscalerConstant.LASTLY_USED_IAAS_MAP_SERIALIZING_FILE);
+
+        } catch (IOException e) {
+            String msg = "Serialization of objects failed!";
+            log.fatal(msg, e);
+            throw new SerializationException(msg, e);
+        }
+    }
+
+    /**
+     * A helper method to terminate an instance.
+     */
+    private void terminate(IaasContext iaasTemp, String nodeId) {
+
+        // this is just to be safe
+        if (iaasTemp.getComputeService() == null) {
+            String msg = "Unexpeced error occured! IaasContext's ComputeService is null!";
+            log.error(msg);
+            throw new AutoscalerServiceException(msg);
+        }
+
+        // destroy the node
+        iaasTemp.getComputeService().destroyNode(nodeId);
+
+        // remove the node id from the Context
+        iaasTemp.removeNodeId(nodeId);
+
+        // replace this IaasContext instance, as it reflects the new changes.
+        replaceIaasContext(iaasTemp);
+
+        // serialize the objects
+        serialize();
+
+        log.info("Node with Id: '" + nodeId + "' is terminated!");
+    }
+
+    /**
+     * Comparator to compare IaasContexts on different attributes.
+     */
+    public enum IaasContextComparator implements Comparator<IaasContext> {
+        SCALE_UP_SORT {
+            public int compare(IaasContext o1, IaasContext o2) {
+                return Integer.valueOf(o1.getScaleUpOrder()).compareTo(o2.getScaleUpOrder());
+            }
+        },
+        SCALE_DOWN_SORT {
+            public int compare(IaasContext o1, IaasContext o2) {
+                return Integer.valueOf(o1.getScaleDownOrder()).compareTo(o2.getScaleDownOrder());
+            }
+        };
+
+        public static Comparator<IaasContext> ascending(final Comparator<IaasContext> other) {
+            return new Comparator<IaasContext>() {
+                public int compare(IaasContext o1, IaasContext o2) {
+                    return other.compare(o1, o2);
+                }
+            };
+        }
+
+        public static Comparator<IaasContext>
+                getComparator(final IaasContextComparator... multipleOptions) {
+            return new Comparator<IaasContext>() {
+                public int compare(IaasContext o1, IaasContext o2) {
+                    for (IaasContextComparator option : multipleOptions) {
+                        int result = option.compare(o1, o2);
+                        if (result != 0) {
+                            return result;
+                        }
+                    }
+                    return 0;
+                }
+            };
+        }
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
new file mode 100644
index 0000000..5053e30
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/internal/AutoscalerServiceDSComponent.java
@@ -0,0 +1,29 @@
+package org.wso2.carbon.autoscaler.service.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.autoscaler.service.IAutoscalerService;
+import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl;
+
+/**
+ * Registering Autoscaler Service.
+ * @scr.component name="org.wso2.carbon.autoscaler.service" immediate="true"
+ */
+public class AutoscalerServiceDSComponent {
+
+    private static final Log log = LogFactory.getLog(AutoscalerServiceDSComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            BundleContext bundleContext = context.getBundleContext();
+            bundleContext.registerService(IAutoscalerService.class.getName(),
+                                          new AutoscalerServiceImpl(), null);
+
+            log.debug("******* Autoscaler Service bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Autoscaler Service bundle is failed to activate ****", e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
new file mode 100644
index 0000000..5c0110e
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Deserializer.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.autoscaler.service.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Deserializer {
+    
+    private static final Log log = LogFactory.getLog(Deserializer.class);
+
+    /**
+     * We deserialize only if the path to the serialized object file is exists.
+     * @param filePath path to the serialized object file
+     * @return the object obtained after deserialization or null if file isn't valid.
+     * @throws Exception
+     */
+    public static Object deserialize(String filePath) throws Exception {
+
+        ObjectInputStream objIn = null; 
+        Object obj = null;
+        
+        if(!new File(filePath).isFile()){
+            return obj;
+        }
+        
+        try {
+
+            objIn = new ObjectInputStream(new FileInputStream(filePath));
+            obj = objIn.readObject();
+
+        } catch (IOException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } catch (ClassNotFoundException e) {
+            log.error("Failed to deserialize the file at "+filePath , e);
+            throw e;
+            
+        } finally{
+            objIn.close();
+        }
+        
+        return obj;
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
new file mode 100644
index 0000000..31dd1eb
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/io/Serializer.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.autoscaler.service.io;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class Serializer {
+    
+    private static final Log log = LogFactory.getLog(Serializer.class);
+
+    public static void serialize(Object serializableObj, String filePath) throws IOException {
+
+        File outFile = new File(filePath);
+        ObjectOutput ObjOut = null;
+        
+        try {
+
+            if(outFile.createNewFile()){
+                log.debug("Serialization file is created at "+filePath);
+            } else{
+                log.debug("Serialization file is already existing at "+filePath);
+            }
+            
+            ObjOut = new ObjectOutputStream(new FileOutputStream(outFile));
+            ObjOut.writeObject(serializableObj);
+
+        } catch (IOException e) {
+            log.error("Failed to serialize the object "+serializableObj.toString()
+                      + " to file "+filePath , e);
+            throw e;
+            
+        } finally{
+            ObjOut.close();
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
new file mode 100644
index 0000000..5818ca1
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/jcloud/ComputeServiceBuilder.java
@@ -0,0 +1,64 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.jcloud;
+
+import java.util.Map;
+import java.util.Properties;
+
+import org.jclouds.ContextBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.ComputeServiceContext;
+import org.jclouds.enterprise.config.EnterpriseConfigurationModule;
+import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
+import org.jclouds.sshj.config.SshjSshClientModule;
+import org.wso2.carbon.autoscaler.service.util.IaasProvider;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.inject.Module;
+
+/**
+ * This class is responsible for creating a JClouds specific ComputeService object instances.
+ */
+public class ComputeServiceBuilder {
+    
+    public static ComputeService buildComputeService(IaasProvider iaas) {
+
+        Properties properties = new Properties();
+
+        // load properties
+        for (Map.Entry<String, String> entry : iaas.getProperties().entrySet()) {
+            properties.put(entry.getKey(), entry.getValue());
+        }
+
+        // set modules
+        Iterable<Module> modules =
+            ImmutableSet.<Module> of(new SshjSshClientModule(), new SLF4JLoggingModule(),
+                                     new EnterpriseConfigurationModule());
+
+        // build context
+        ContextBuilder builder =
+            ContextBuilder.newBuilder(iaas.getProvider())
+                          .credentials(iaas.getIdentity(), iaas.getCredential()).modules(modules)
+                          .overrides(properties);
+
+        // return the compute service object
+        return builder.buildView(ComputeServiceContext.class).getComputeService();
+    }
+    
+    
+}


[17/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/pom.xml b/components/stratos/org.wso2.carbon.activation/2.1.2/pom.xml
new file mode 100644
index 0000000..b499811
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/pom.xml
@@ -0,0 +1,94 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.activation</artifactId>
+    <version>2.1.2</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Activation</name>
+
+    <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>
+                        <Axis2Module>${project.artifactId}-${project.version}</Axis2Module>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.wso2.carbon.activation.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.stratos.common.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
new file mode 100644
index 0000000..e3fb386
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
@@ -0,0 +1,152 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.internal;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.activation.service.ActivationService;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+
+/**
+ * The Declarative Service Component for the Service Activation Module for Tenants.
+ *
+ * @scr.component name="org.wso2.carbon.metering" immediate="true"
+ * @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="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="0..1" policy="dynamic"  bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ */
+@SuppressWarnings({"JavaDoc", "unused"})
+public class ActivationServiceComponent {
+
+    private static final Log log = LogFactory.getLog(ActivationServiceComponent.class);
+
+    private static ServiceRegistration registration = null;
+
+    /**
+     * Activates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void activate(ComponentContext context) {
+        try {
+            ActivationManager.startCacheCleaner();
+            if (registration == null) {
+                registration = context.getBundleContext().registerService(
+                        ActivationService.class.getName(), new ActivationService(), null);
+            }
+            log.debug("******* Stratos Activation bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Stratos Activation bundle failed activating ****", e);
+        }
+    }
+
+    /**
+     * Deactivates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void deactivate(ComponentContext context) {
+        registration.unregister();
+        registration = null;
+        ActivationManager.stopCacheCleaner();
+        log.debug("******* Stratos Activation bundle is deactivated ******* ");
+    }
+
+    /**
+     * Method to set the registry service used. This will be used when accessing the registry. This
+     * method is called when the OSGi Registry Service is available.
+     *
+     * @param registryService the registry service.
+     */
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    /**
+     * This method is called when the current registry service becomes un-available.
+     *
+     * @param registryService the current registry service instance, to be used for any
+     *                        cleaning-up.
+     */
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    /**
+     * Method to set the realm service used. This will be used when accessing the user realm. This
+     * method is called when the OSGi Realm Service is available.
+     *
+     * @param realmService the realm service.
+     */
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    /**
+     * This method is called when the current realm service becomes un-available.
+     *
+     * @param realmService the current realm service instance, to be used for any cleaning-up.
+     */
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    /**
+     * Method to set the configuration context service used. This method is called when the OSGi
+     * ConfigurationContext Service is available.
+     *
+     * @param contextService the configuration context service.
+     */
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        try {
+            if (contextService.getServerConfigContext() != null &&
+                    contextService.getServerConfigContext().getAxisConfiguration() != null) {
+                contextService.getServerConfigContext().getAxisConfiguration().engageModule(
+                        "activation");
+            } else {
+                log.error("Failed to engage Activation Module.");
+            }
+        } catch (AxisFault e) {
+            log.error("Failed to engage Activation Module", e);
+        }
+    }
+
+    /**
+     * This method is called when the current configuration context service becomes un-available.
+     *
+     * @param contextService the current configuration context service instance, to be used for any
+     *                       cleaning-up.
+     */
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
new file mode 100644
index 0000000..b2171cf
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
@@ -0,0 +1,161 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.module;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.soap.SOAPBody;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.Handler;
+import org.apache.axis2.handlers.AbstractHandler;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+public class ActivationHandler extends AbstractHandler implements Handler {
+
+    private static final Log log = LogFactory.getLog(ActivationHandler.class);
+
+    private String name = "ActivationHandler";
+
+    /**
+     * {@inheritDoc}
+     */
+    public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
+        String serviceName = Util.getServiceName();
+        //TODO - tenant id and domain should retrieve from thread local carbon context
+        //If service is api manager then we will pass activation handler check
+        if(serviceName.equalsIgnoreCase("WSO2 API Manager")) {
+            return InvocationResponse.CONTINUE;
+        }
+        if(log.isDebugEnabled()){
+            log.debug("Starting Activation Handler invocation. Incoming Message: " +
+                    messageContext.getEnvelope().toString());
+        }
+
+        AxisService service = messageContext.getAxisService();
+        int tenantId = getTenantId(messageContext);
+        if (service != null && "ActivationService".equals(service.getName())) {
+            log.debug("Granted access to the Activation Service");
+            if (tenantId > 0) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+            }
+            return InvocationResponse.CONTINUE;
+        }
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            log.debug("Granted access for super tenant");
+            return InvocationResponse.CONTINUE;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            if (ActivationManager.getActivation(tenantId)) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            } else {
+                if (log.isWarnEnabled()) {
+                    log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+                }
+                return InvocationResponse.ABORT;
+            }
+        }
+
+        try {
+            if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+                log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+                ActivationManager.setActivation(tenantId, true);
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            }
+        } catch (Exception e) {
+            throw new AxisFault("Failed to determine Activation status.", e);
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return InvocationResponse.ABORT;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Method to set the name of the activation handler.
+     *
+     * @param name the name.
+     */
+    @SuppressWarnings("unused")
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    private String getTenantDomain(MessageContext messageContext) {
+        //Ideally this should take from thread local carbon context change this temporary
+        return PrivilegedCarbonContext.getCurrentContext(messageContext).getTenantDomain();
+    }
+
+    private int getTenantId(MessageContext messageContext) {
+        //Ideally this should take from thread local carbon context change this temporary
+        PrivilegedCarbonContext carbonContext =
+                PrivilegedCarbonContext.getCurrentContext(messageContext);
+        int tenantId = carbonContext.getTenantId();
+        if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return tenantId;
+        }
+        String domain = carbonContext.getTenantDomain();
+        if (domain == null) {
+            SOAPBody soapBody = messageContext.getEnvelope().getBody();
+            if (soapBody != null && soapBody.getFirstElement() != null) {
+                OMElement usernameElem = soapBody.getFirstElement().getFirstChildWithName(
+                        new QName(ServerConstants.AUTHENTICATION_SERVICE_NS,
+                                ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
+                if (usernameElem != null) {
+                    String userName = usernameElem.getText();
+                    domain = MultitenantUtils.getTenantDomain(userName);
+                }
+            }
+        }
+        if (domain != null) {
+            try {
+                tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
+            } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                log.error("An error occurred while obtaining the tenant id.", e);
+            }
+        }
+        return tenantId;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
new file mode 100644
index 0000000..9cfbee5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.module;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.modules.Module;
+import org.apache.neethi.Assertion;
+import org.apache.neethi.Policy;
+
+/**
+ * Module used to engage the activation handler.
+ */
+public class ActivationModule implements Module {
+
+    /**
+     * {@inheritDoc}
+     */
+    public void init(ConfigurationContext configurationContext, AxisModule axisModule)
+            throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void engageNotify(AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean canSupportAssertion(Assertion assertion) {
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void shutdown(ConfigurationContext configurationContext) throws AxisFault {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/service/ActivationService.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
new file mode 100644
index 0000000..e16f2fb
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
@@ -0,0 +1,85 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+import org.wso2.carbon.stratos.common.config.CloudServiceConfigParser;
+import org.wso2.carbon.stratos.common.config.CloudServicesDescConfig;
+import org.wso2.carbon.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Admin Service to handle activation of cloud services used by tenants.
+ */
+public class ActivationService {
+
+    private static final Log log = LogFactory.getLog(ActivationService.class);
+
+    /**
+     * Method to update an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @throws Exception if the operation failed.
+     */
+    public static void updateActivation(int tenantId) throws Exception {
+        if (tenantId != 0) {
+            String serviceName = Util.getServiceName();
+            boolean isActive = CloudServicesUtil.isCloudServiceActive(serviceName, tenantId);
+            CloudServicesDescConfig cloudServicesDesc =
+                                                        CloudServiceConfigParser.loadCloudServicesConfiguration();
+            CloudServicesUtil.setCloudServiceActive(!isActive,
+                                                    serviceName,
+                                                    tenantId,
+                                                    cloudServicesDesc.getCloudServiceConfigs()
+                                                                     .get(serviceName));
+            ActivationManager.setActivation(tenantId, !isActive);
+        }
+    }
+
+    /**
+     * Method to determine whether a service is active for the given tenant.
+     *
+     * @param tenantId tenantId the tenant identifier.
+     *
+     * @return whether the service is active.
+     * @throws Exception if the operation failed.
+     */
+    public boolean isActive(int tenantId) throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return true;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            return ActivationManager.getActivation(tenantId);
+        }
+        String serviceName = Util.getServiceName();
+        if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+            log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+            ActivationManager.setActivation(tenantId, true);
+            return true;
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
new file mode 100644
index 0000000..41153a8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
@@ -0,0 +1,96 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.utils;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Manages Activations of Services for Tenants.
+ */
+public class ActivationManager {
+
+    private static final ConcurrentHashMap<Integer, Boolean> activations =
+            new ConcurrentHashMap<Integer, Boolean>();
+    private static Timer timer = null;
+
+    /**
+     * Starts cleaning up cached activation records at periodic intervals.
+     */
+    public static void startCacheCleaner() {
+        TimerTask faultyServiceRectifier = new CacheCleaner();
+        timer = new Timer();
+        // Retry in 1 minute
+        long retryIn = 1000 * 60;
+        timer.schedule(faultyServiceRectifier, 0, retryIn);
+    }
+
+    /**
+     * Stops cleaning up cached activation records.
+     */
+    public static void stopCacheCleaner() {
+        timer.cancel();
+        timer = null;
+    }
+
+    /**
+     * Method to set an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     * @param status   true if the service is active or false if not.
+     */
+    public static void setActivation(int tenantId, boolean status) {
+        ActivationManager.activations.put(tenantId, status);
+    }
+
+    /**
+     * Method to check whether an activation record exists for the given tenant.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if a record exists.
+     */
+    public static boolean activationRecorded(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null;
+    }
+
+    /**
+     * Method to retrieve an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if the service is active or false if not.
+     */
+    public static boolean getActivation(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null &&
+                ActivationManager.activations.get(tenantId);
+    }
+
+    private static class CacheCleaner extends TimerTask {
+
+        /**
+         * {@inheritDoc}
+         */
+        public void run() {
+            ActivationManager.activations.clear();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/Util.java b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/Util.java
new file mode 100644
index 0000000..9f01045
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/java/org/wso2/carbon/activation/utils/Util.java
@@ -0,0 +1,138 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+/**
+ * Utilities for the Service Activation Module for Tenants.
+ */
+public class Util {
+
+    private static RegistryService registryService = null;
+    private static RealmService realmService = null;
+    private static String serviceName = null;
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static boolean cloudServiceInfoPathSanityChecked = false;
+
+    /**
+     * Stores an instance of the Registry Service that can be used to access the registry.
+     *
+     * @param service the Registry Service instance.
+     */
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Registry Service instance.
+     *
+     * @return the Registry Service instance if it has been stored or null if not.
+     */
+    @SuppressWarnings("unused")
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    /**
+     * Stores an instance of the Realm Service that can be used to access the user realm.
+     *
+     * @param service the Realm Service instance.
+     */
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Realm Service instance.
+     *
+     * @return the Realm Service instance if it has been stored or null if not.
+     */
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    private static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+//    /**
+//     * Method to determine whether the given cloud service is active.
+//     *
+//     * @param cloudServiceName the name of the cloud service.
+//     * @param tenantId         the tenant identifier.
+//     * @param systemRegistry   the super tenant's governance system registry
+//     *
+//     * @return true if the service is active or false if not.
+//     * @throws Exception if the operation failed.
+//     */
+//    public static boolean isCloudServiceActive(String cloudServiceName,
+//                                               int tenantId, UserRegistry systemRegistry)
+//            throws Exception {
+//        // The cloud manager is always active
+//        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+//            return true;
+//        }
+//
+//        if(!cloudServiceInfoPathSanityChecked) {
+//            if(!systemRegistry.resourceExists(StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH)) {
+//                throw new RuntimeException("Cloud services list resource " +
+//                                           StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH + " does not exist");
+//            }
+//            cloudServiceInfoPathSanityChecked = true;
+//        }
+//
+//        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+//                RegistryConstants.PATH_SEPARATOR + tenantId +
+//                RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+//        Resource cloudServiceInfoResource;
+//        if (systemRegistry.resourceExists(cloudServiceInfoPath)) {
+//            cloudServiceInfoResource = systemRegistry.get(cloudServiceInfoPath);
+//            String isActiveStr =
+//                cloudServiceInfoResource.getProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+//            return Boolean.toString(true).equals(isActiveStr);
+//        }
+//        return false;
+//    }
+//
+
+    /**
+     * Method to obtain the name of the cloud service in which this module is running.
+     *
+     * @return the name of the service as defined in the server configuration.
+     */
+    public static String getServiceName() {
+        if (serviceName == null) {
+            serviceName = ServerConfiguration.getInstance().getFirstProperty("Name");
+        }
+        return serviceName;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/module.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/module.xml b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/module.xml
new file mode 100644
index 0000000..b92b725
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/module.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<module name="activation" class="org.wso2.carbon.activation.module.ActivationModule">
+   <InFlow>
+        <handler name="InFlowActivationHandler"
+                 class="org.wso2.carbon.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFlow>
+
+   <InFaultFlow>
+        <handler name="FaultInFlowActivationHandler"
+                 class="org.wso2.carbon.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFaultFlow>
+  <parameter name="adminModule" locked="true">true</parameter>
+</module>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..dde74d7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.2/src/main/resources/META-INF/services.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ !
+ ! WSO2 Inc. licenses this file to you under the Apache License,
+ ! Version 2.0 (the "License"); you may not use this file except
+ ! in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ ! http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing,
+ ! software distributed under the License is distributed on an
+ ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ! KIND, either express or implied.  See the License for the
+ ! specific language governing permissions and limitations
+ ! under the License.
+ !-->
+<serviceGroup>
+    <service name="ActivationService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.activation.service.ActivationService
+        </parameter>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/pom.xml b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/pom.xml
new file mode 100644
index 0000000..5e9d0e5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/pom.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
+	Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); 
+	~ you may not use this file except in compliance with the License. ~ You 
+	may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, software ~ 
+	distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the 
+	License for the specific language governing permissions and ~ limitations 
+	under the License. -->
+<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.wso2.carbon</groupId>
+	    <artifactId>stratos-components</artifactId>
+            <version>2.1.0</version>
+	    <relativePath>../../pom.xml</relativePath>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.wso2.carbon.cartridge.mgt.ui</artifactId>
+        <version>2.1.3</version>
+	<packaging>bundle</packaging>
+	<name>WSO2 Carbon - Cartridge Management UI</name>
+	<description>Cartridge management UI bundle</description>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.ui</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.utils</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.mgt.stub</artifactId>
+			<version>4.1.3</version>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.reponotification.service.stub</artifactId>
+			<version>4.1.1</version>
+		</dependency>
+		<dependency>
+               <groupId>com.google.code.gson</groupId>
+               <artifactId>gson</artifactId>
+               <version>2.1</version>
+           </dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<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.wso2.carbon.cartridge.mgt.ui.internal,
+							org.wso2.carbon.cartridge.mgt.ui.*;version="2.1.3"
+                        </Export-Package>
+						<Bundle-Activator>
+							org.wso2.carbon.cartridge.mgt.ui.internal.CartridgeManagementUIActivator
+                        </Bundle-Activator>
+						<Private-Package>org.wso2.carbon.cartridge.mgt.ui.internal</Private-Package>
+						<Carbon-Component>UIBundle</Carbon-Component>
+						<Import-Package>
+							!org.wso2.carbon.cartridge.mgt.ui.*,
+							org.wso2.carbon.adc.mgt.stub.*;version="1.0.0",
+							*;resolution:=optional
+                        </Import-Package>
+					</instructions>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeAdminClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeAdminClient.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeAdminClient.java
new file mode 100644
index 0000000..8d85694
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeAdminClient.java
@@ -0,0 +1,275 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed under the Apache License, Version 2.0 (the "License");             
+ * you may not use this file except in compliance with the License.            
+ * You may obtain a copy of the License at                                     
+ *                                                                             
+ *      http://www.apache.org/licenses/LICENSE-2.0                             
+ *                                                                             
+ * Unless required by applicable law or agreed to in writing, software         
+ * distributed under the License is distributed on an "AS IS" BASIS,           
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    
+ * See the License for the specific language governing permissions and         
+ * limitations under the License.                                              
+ */
+package org.wso2.carbon.cartridge.mgt.ui;
+
+import java.rmi.RemoteException;
+import java.text.MessageFormat;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.mgt.dto.xsd.CartridgeWrapper;
+import org.wso2.carbon.adc.mgt.dto.xsd.PolicyDefinition;
+import org.wso2.carbon.adc.mgt.dto.xsd.RepositoryInformation;
+import org.wso2.carbon.adc.mgt.dto.xsd.SubscriptionInfo;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceADCExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceAlreadySubscribedExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceDomainMappingExistsExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceDuplicateCartridgeAliasExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceInvalidCartridgeAliasExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceInvalidRepositoryExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceNotSubscribedExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServicePolicyExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryRequiredExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceRepositoryTransportExceptionException;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceStub;
+import org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceUnregisteredCartridgeExceptionException;
+
+/**
+ * Client which communicates with the Application Management service of ADC
+ */
+public class CartridgeAdminClient {
+    public static final String BUNDLE = "org.wso2.carbon.cartridge.mgt.ui.i18n.Resources";
+    public static final int MILLISECONDS_PER_MINUTE = 60 * 1000;
+    private static final Log log = LogFactory.getLog(CartridgeAdminClient.class);
+    private ResourceBundle bundle;
+    public ApplicationManagementServiceStub stub;
+
+	public CartridgeAdminClient(String cookie, String backendServerURL, ConfigurationContext configCtx, Locale locale) throws AxisFault {
+		if (log.isDebugEnabled()) {
+			log.debug("Creating CartridgeAdminClient for " + backendServerURL);
+		}
+		if (cookie == null || cookie.trim().length() == 0) {
+			if (log.isDebugEnabled()) {
+				log.debug("Cookie not found. Cannot create CartridgeAdminClient for " + backendServerURL);
+			}
+			throw new RuntimeException("Session has expired");
+		}
+		String serviceURL = backendServerURL + "ApplicationManagementService";
+		bundle = ResourceBundle.getBundle(BUNDLE, locale);
+
+		stub = new ApplicationManagementServiceStub(configCtx, serviceURL);
+		ServiceClient client = stub._getServiceClient();
+		Options option = client.getOptions();
+		option.setManageSession(true);
+		option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+		option.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
+	}
+
+	public CartridgeWrapper getPagedAvailableCartridges(String cartridgeSearchString, int pageNumber, boolean multiTenant) {
+		try {
+			return stub.getPagedAvailableCartridges(cartridgeSearchString, pageNumber, multiTenant);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.available.cartridges", e);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		}
+		return null;
+	}
+    
+	public CartridgeWrapper getPagedSubscribedCartridges(String cartridgeSearchString, int pageNumber) {
+		try {
+			return stub.getPagedSubscribedCartridges(cartridgeSearchString, pageNumber);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.list.subscribed.cartridges", e);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		}
+		return null;
+	}
+
+	public String addDomainMapping(String mappedDomain, String cartridgeAlias) {
+		String host = null;
+		try {
+			host = stub.addDomainMapping(mappedDomain, cartridgeAlias);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.mapdomain", e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, cartridgeAlias);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		} catch (ApplicationManagementServiceDomainMappingExistsExceptionException e) {
+			handleException("domainmapping.exists.error", e, mappedDomain, cartridgeAlias);
+		}
+
+		return host;
+	}
+	
+	public void removeDomainMapping(String cartridgeAlias) {
+		try {
+			stub.removeDomainMapping(cartridgeAlias);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.removedomain", e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, cartridgeAlias);
+		}
+	}
+	
+	public void synchronizeRepository(String cartridgeAlias) {
+		try {
+			stub.synchronizeRepository(cartridgeAlias);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.syncrepo", e);
+		} catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+			handleException("notsubscribed.error", e, cartridgeAlias);
+		}
+	}
+	
+	public RepositoryInformation testRepositoryConnection(String repoURL, String repoUsername, String repoPassword, boolean privateRepo) {
+		try {
+			return stub.testRepositoryConnection(repoURL, repoUsername, repoPassword, privateRepo);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.testrepo", e);
+		} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+			handleException("repository.required", e);
+		} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+			handleException("repository.transport.error", e, repoURL);
+		} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+			handleException("repository.credentials.required", e, repoURL);
+		} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+			handleException("repository.invalid.error", e, repoURL);
+		}
+		return null;
+	}
+	
+    public void unsubscribe(String alias) {
+        try {
+            stub.unsubscribe(alias);
+        } catch (RemoteException e) {
+        	handleException("remote.error", e);
+        } catch (ApplicationManagementServiceADCExceptionException e) {
+        	handleException("cannot.unsubscribe", e);
+        } catch (ApplicationManagementServiceNotSubscribedExceptionException e) {
+        	handleException("notsubscribed.error", e, alias);
+		}
+    }
+
+    public PolicyDefinition[] getPolicyDefinitions() {
+        try {
+            return stub.getPolicyDefinitions();
+        } catch (RemoteException e) {
+            handleException("remote.error", e);
+        }
+        return null;
+    }
+    
+    public boolean isFeatureEnabled(String feature) {
+        try {
+            return stub.isFeatureEnabled(feature);
+        } catch (RemoteException e) {
+            handleException("remote.error", e);
+        }
+        return false;
+    }
+
+    public SubscriptionInfo subscribeToCartridge(String cartridgeType,
+                                       String cartridgeAlias,
+                                       String policy,
+                                       String repositoryUrl,
+                                       boolean privateRepo,
+                                       String repoUserName,
+                                       String repoPassword,
+                                       String otherCartridgeType,
+                                       String otherCartridgeAlias) {
+    	
+		if (log.isInfoEnabled()) {
+			log.info("Subscribing to a Cartridge: " + cartridgeType + ", Alias: " + cartridgeAlias);
+		}
+		
+		if (otherCartridgeAlias != null && otherCartridgeAlias.trim().length() > 0) {
+			// currently passing empty strings for repo user name and
+			// passwords
+			try {
+				stub.subscribe(otherCartridgeType, otherCartridgeAlias, policy, null, false, "", "", null, null);
+			} catch (RemoteException e) {
+				handleException("remote.error", e);
+			} catch (ApplicationManagementServiceADCExceptionException e) {
+				handleException("cannot.subscribe", e);
+			} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+				handleException("repository.required", e);
+			} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+				handleException("cartridge.notregistered", e, otherCartridgeType);
+			} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+				handleException("cartridge.invalid.alias", e, otherCartridgeAlias);
+			} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+				handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+						.getCartridgeType());
+			} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+				handleException("cartridge.alias.duplicate", e, otherCartridgeAlias);
+			} catch (ApplicationManagementServicePolicyExceptionException e) {
+				handleException("policy.error", e);
+			} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+				handleException("repository.transport.error", e, repositoryUrl);
+			} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+				handleException("repository.credentials.required", e, repositoryUrl);
+			} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+				handleException("repository.invalid.error", e, repositoryUrl);
+			}
+		}
+		
+		try {
+			return stub.subscribe(cartridgeType, cartridgeAlias, policy, repositoryUrl, privateRepo, repoUserName,
+					repoPassword, otherCartridgeType, otherCartridgeAlias);
+		} catch (RemoteException e) {
+			handleException("remote.error", e);
+		} catch (ApplicationManagementServiceADCExceptionException e) {
+			handleException("cannot.subscribe", e);
+		} catch (ApplicationManagementServiceRepositoryRequiredExceptionException e) {
+			handleException("repository.required", e);
+		} catch (ApplicationManagementServiceUnregisteredCartridgeExceptionException e) {
+			handleException("cartridge.notregistered", e, cartridgeType);
+		} catch (ApplicationManagementServiceInvalidCartridgeAliasExceptionException e) {
+			handleException("cartridge.invalid.alias", e, cartridgeAlias);
+		} catch (ApplicationManagementServiceAlreadySubscribedExceptionException e) {
+			handleException("cartridge.already.subscribed", e, e.getFaultMessage().getAlreadySubscribedException()
+					.getCartridgeType());
+		} catch (ApplicationManagementServiceDuplicateCartridgeAliasExceptionException e) {
+			handleException("cartridge.alias.duplicate", e, cartridgeAlias);
+		} catch (ApplicationManagementServicePolicyExceptionException e) {
+			handleException("policy.error", e);
+		} catch (ApplicationManagementServiceRepositoryTransportExceptionException e) {
+			handleException("repository.transport.error", e, repositoryUrl);
+		} catch (ApplicationManagementServiceRepositoryCredentialsRequiredExceptionException e) {
+			handleException("repository.credentials.required", e, repositoryUrl);
+		} catch (ApplicationManagementServiceInvalidRepositoryExceptionException e) {
+			handleException("repository.invalid.error", e, repositoryUrl);
+		}
+		return null;
+    }
+
+    private void handleException(String msgKey, Exception e, Object... args) {
+        String msg = bundle.getString(msgKey);
+        if (args != null) {
+        	msg = MessageFormat.format(msg, args);
+        }
+        log.error(msg, e);
+        throw new RuntimeException(msg, e);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeConstans.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeConstans.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/CartridgeConstans.java
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Payload.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Payload.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Payload.java
new file mode 100644
index 0000000..2c4a7b5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Payload.java
@@ -0,0 +1,14 @@
+package org.wso2.carbon.cartridge.mgt.ui;
+
+public class Payload {
+	private Repository repository;
+
+	public Repository getRepository() {
+		return repository;
+	}
+
+	public void setRepository(Repository repository) {
+		this.repository = repository;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationClient.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationClient.java
new file mode 100644
index 0000000..756daa8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationClient.java
@@ -0,0 +1,52 @@
+package org.wso2.carbon.cartridge.mgt.ui;
+
+import java.rmi.RemoteException;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.reponotification.stub.RepoNotificationServiceException;
+import org.wso2.carbon.adc.reponotification.stub.RepoNotificationServiceStub;
+
+public class RepoNotificationClient {
+
+	private ResourceBundle bundle;
+	public RepoNotificationServiceStub stub;
+	public static final String BUNDLE = "org.wso2.carbon.cartridge.mgt.ui.i18n.Resources";
+	private static final Log log = LogFactory.getLog(RepoNotificationClient.class);
+
+	public RepoNotificationClient(String cookie, String backendServerURL,
+			ConfigurationContext configCtx, Locale locale) throws AxisFault {
+		String serviceURL = backendServerURL + "RepoNotificationService";
+		bundle = ResourceBundle.getBundle(BUNDLE, locale);
+
+		stub = new RepoNotificationServiceStub(configCtx, serviceURL);
+		ServiceClient client = stub._getServiceClient();
+		Options option = client.getOptions();
+		option.setManageSession(true);
+		option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+		option.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
+	}
+
+	public void synchronize(String repositoryURL) throws AxisFault {
+		try {
+			stub.synchronize(repositoryURL);
+		} catch (RemoteException e) {
+			handleException("cannot.unsubscribe", e);
+		} catch (RepoNotificationServiceException e) {
+			handleException("cannot.unsubscribe", e);
+		}
+	}
+
+	private void handleException(String msgKey, Exception e) throws AxisFault {
+		String msg = bundle.getString(msgKey);
+		log.error(msg, e);
+		throw new AxisFault(msg, e);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationServlet.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationServlet.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationServlet.java
new file mode 100644
index 0000000..817d5ad
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/RepoNotificationServlet.java
@@ -0,0 +1,57 @@
+package org.wso2.carbon.cartridge.mgt.ui;
+
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+
+import com.google.gson.Gson;
+
+public class RepoNotificationServlet extends HttpServlet {
+
+	private static final long serialVersionUID = 4315990619456849911L;
+	private static final Log log = LogFactory
+			.getLog(RepoNotificationServlet.class);
+
+	public RepoNotificationServlet() {
+	}
+
+	@Override
+	public void doPost(HttpServletRequest request, HttpServletResponse response) {
+		String payload = request.getParameter("payload");
+		log.info(" repository payload received ");
+
+		String repositoryURL;
+
+		Gson gson = new Gson();
+		Payload p = gson.fromJson(payload, Payload.class);
+		repositoryURL = p.getRepository().getUrl();
+		try {
+			String backendServerURL = CarbonUIUtil.getServerURL(
+					getServletContext(), request.getSession());
+			ConfigurationContext configContext = (ConfigurationContext) getServletContext()
+					.getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+			String cookie = (String) request.getSession().getAttribute(
+					ServerConstants.ADMIN_SERVICE_COOKIE);
+			new RepoNotificationClient(cookie, backendServerURL, configContext,
+					request.getLocale()).synchronize(repositoryURL);
+		} catch (Exception e) {
+			log.error("Exception is occurred in synchronize, Reason : "
+					+ e.getMessage());
+		}
+
+	}
+
+	@Override
+	protected void doGet(HttpServletRequest req, HttpServletResponse res) {
+
+		this.doPost(req, res);
+	}
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Repository.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Repository.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Repository.java
new file mode 100644
index 0000000..dec2a74
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/Repository.java
@@ -0,0 +1,14 @@
+package org.wso2.carbon.cartridge.mgt.ui;
+
+public class Repository {
+	private String url;
+
+	public String getUrl() {
+		return url;
+	}
+
+	public void setUrl(String url) {
+		this.url = url;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/internal/CartridgeManagementUIActivator.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/internal/CartridgeManagementUIActivator.java b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/internal/CartridgeManagementUIActivator.java
new file mode 100644
index 0000000..cbdb497
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/java/org/wso2/carbon/cartridge/mgt/ui/internal/CartridgeManagementUIActivator.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.cartridge.mgt.ui.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.wso2.carbon.utils.CarbonUtils;
+
+/**
+ * Activator for the Cartridge Management Bundle
+ */
+public class CartridgeManagementUIActivator implements BundleActivator {
+
+	private static final Log log = LogFactory.getLog(CartridgeManagementUIActivator.class);
+
+	public void start(final BundleContext bundleContext) {
+
+		if (!CarbonUtils.isRunningInStandaloneMode()) {
+			// uninstall this component
+			Thread th = new Thread() {
+				public void run() {
+					try {
+						bundleContext.getBundle().uninstall();
+					} catch (Throwable e) {
+						log.warn("Error occurred while uninstalling cartridge-mgt UI bundle", e);
+					}
+				}
+			};
+			try {
+				th.join();
+			} catch (InterruptedException ignored) {
+			}
+			th.start();
+		}
+	}
+
+	public void stop(BundleContext bundleContext) {
+		// No implementation required for this method
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..b9a87bd
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/META-INF/component.xml
@@ -0,0 +1,93 @@
+<!-- ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
+	Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, 
+	~ Version 2.0 (the "License"); you may not use this file except ~ in compliance 
+	with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, ~ software 
+	distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the 
+	License for the ~ specific language governing permissions and limitations 
+	~ under the License. -->
+<component xmlns="http://products.wso2.org/carbon">
+	<menus>
+		<menu>
+			<id>available_cartridges_menu</id>
+			<i18n-key>cartridge.available.services.menu</i18n-key>
+			<i18n-bundle>org.wso2.carbon.cartridge.mgt.ui.i18n.Resources</i18n-bundle>
+			<parent-menu>manage_menu</parent-menu>
+			<link>#</link>
+			<region>region1</region>
+			<order>1</order>
+			<icon>../cartridge-mgt/images/cartridge.png</icon>
+			<style-class>home</style-class>
+			<require-permission>/permission/admin/manage/cartridges</require-permission>
+			<require-not-super-tenant>true</require-not-super-tenant>
+		</menu>
+		<menu>
+			<id>available_multitenant_cartridges</id>
+			<i18n-key>cartridges.available.multitenant</i18n-key>
+			<i18n-bundle>org.wso2.carbon.cartridge.mgt.ui.i18n.Resources</i18n-bundle>
+			<parent-menu>available_cartridges_menu</parent-menu>
+			<link>../cartridge-mgt/available_cartridges.jsp</link>
+			<region>region1</region>
+			<order>2</order>
+			<icon>../cartridge-mgt/images/list.gif</icon>
+			<style-class>home</style-class>
+			<require-permission>/permission/admin/manage/cartridges</require-permission>
+			<require-not-super-tenant>true</require-not-super-tenant>
+		</menu>
+		<menu>
+			<id>available_singletenant_cartridges</id>
+			<i18n-key>cartridges.available.singletenant</i18n-key>
+			<i18n-bundle>org.wso2.carbon.cartridge.mgt.ui.i18n.Resources</i18n-bundle>
+			<parent-menu>available_cartridges_menu</parent-menu>
+			<link>../cartridge-mgt/available_cartridges.jsp</link>
+			<region>region1</region>
+			<order>3</order>
+			<icon>../cartridge-mgt/images/list.gif</icon>
+			<style-class>home</style-class>
+			<require-permission>/permission/admin/manage/cartridges</require-permission>
+			<require-not-super-tenant>true</require-not-super-tenant>
+		</menu>
+		<menu>
+			<id>subscribed_cartridges_menu</id>
+			<i18n-key>cartridge.subscribed.services.menu</i18n-key>
+			<i18n-bundle>org.wso2.carbon.cartridge.mgt.ui.i18n.Resources</i18n-bundle>
+			<parent-menu>manage_menu</parent-menu>
+			<link>#</link>
+			<region>region1</region>
+			<order>4</order>
+			<icon>../cartridge-mgt/images/cartridge.png</icon>
+			<style-class>home</style-class>
+			<require-permission>/permission/admin/manage/cartridges</require-permission>
+			<require-not-super-tenant>true</require-not-super-tenant>
+		</menu>
+		<menu>
+			<id>subscribed_cartridges</id>
+			<i18n-key>cartridges.subscribed.list</i18n-key>
+			<i18n-bundle>org.wso2.carbon.cartridge.mgt.ui.i18n.Resources</i18n-bundle>
+			<parent-menu>subscribed_cartridges_menu</parent-menu>
+			<link>../cartridge-mgt/subscribed_cartridges.jsp</link>
+			<region>region1</region>
+			<order>5</order>
+			<icon>../cartridge-mgt/images/list.gif</icon>
+			<style-class>home</style-class>
+			<require-permission>/permission/admin/manage/cartridges</require-permission>
+			<require-not-super-tenant>true</require-not-super-tenant>
+		</menu>
+	</menus>
+	<servlets>
+		<servlet id="RepoNotificationServlet">
+			<servlet-name>RepoNotificationServlet</servlet-name>
+			<url-pattern>/repo_notification</url-pattern>
+			<display-name>Repository Notification Servlet</display-name>
+			<servlet-class>org.wso2.carbon.cartridge.mgt.ui.RepoNotificationServlet</servlet-class>
+		</servlet>
+	</servlets>
+	<framework-configuration>
+		<bypass>
+			<authentication>
+				<link>/repo_notification</link>
+			</authentication>
+		</bypass>
+	</framework-configuration>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/org/wso2/carbon/cartridge/mgt/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/org/wso2/carbon/cartridge/mgt/ui/i18n/Resources.properties b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/org/wso2/carbon/cartridge/mgt/ui/i18n/Resources.properties
new file mode 100644
index 0000000..d8d8ed1
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/org/wso2/carbon/cartridge/mgt/ui/i18n/Resources.properties
@@ -0,0 +1,96 @@
+list=List
+
+remote.error=Error connecting to back-end service.
+notsubscribed.error=You have not subscribed to {0}
+
+cartridge.information=Cartridge Information
+cartridge.connect.information=Connect Cartridge Information
+cartridge.available.services.menu=Available Cartridges
+cartridge.subscribed.services.menu=Subscribed Cartridges
+cartridges=Cartridges
+cartridges.available.multitenant=Multi-Tenant Cartridges
+cartridges.available.singletenant=Single-Tenant Cartridges
+cartridges.subscribed.list=List Cartridges
+cartrigdes.available.header=Available Cartridges
+cartrigdes.subscribed.header=Subscribed Cartridges
+cartridge.display.name=Cartridge Name
+cartridge.version=Version
+cartridge.description=Description
+cartridge.tenancymodel=Tenancy Model
+search.cartrigdes=Search Cartridges
+subscribe.new.cartridge=Subscribe to a New Cartridge
+subscribe.to=Subscribe to {0} Cartridge
+subscribed.cartridges=Subscribed cartridges
+no.subscribed.cartridges=There are no Subscribed cartridges
+no.cartridges.found=No Cartridges Found
+already.subscribed=Already Subscribed
+
+cartridge.notregistered=Cartridge {0} is not registered
+cartridge.invalid.alias=The provided cartridge alias is not valid. The alias can contain only lowercase characters and numbers.
+cartridge.already.subscribed=You have already subscribed for cartridge type {0}
+cartridge.alias.duplicate=Duplicate cartridge alias {0}
+
+policy.error=Could not load policy.
+
+ip=IP
+mapdomain.information=Map Domain Information
+mapdomain.to=Map Domain to Alias
+mapdomain=Map Domain
+removedomain=Remove Domain
+mappeddomain=Mapped Domain
+cannot.mapdomain=Map Domain failed
+cannot.removedomain=Mapped Domain removal failed
+domainmapping.exists.error=Provided domain mapping {0} already exists
+
+syncrepo=Synchronize
+cannot.syncrepo=Synchronization failed
+
+repository.information=Git Repository Information
+repository.required=An external repository required
+repository.credentials.required=Username and Password are required for the repository: {0}
+repository.transport.error=Error connecting to the repository: {0}
+repository.invalid.error=Invalid repository: {0}
+
+select.cartridge.file=Select the file to upload
+invalid.cartridge.file=Selected file is invalid
+cartridge.app=Cartridge Application
+upload.application=Upload Applications
+app.archiveapp=Upload new applications
+upload=Upload
+cancel=Cancel
+subscribe=Subscribe
+unsubscribe=Unsubscribe
+url=Access URL(s)
+repo.url=Repository URL
+upload.apps=Upload Apps
+policy=Policy
+
+type=Type
+status=Status
+instance.count=Running Instances
+alias=Alias
+action=Action
+search=Search
+
+username=Username
+password=Password
+
+next=next
+prev=prev
+
+appmgt.add.app.menu=Add
+appmgt.listservices.menu=List
+appmgt.services.menu=Cartridge Applications
+select.cartridge=Select a Cartridge
+no.selected.cartridge=Please select a cartridge
+cartridge=Cartridge
+
+successfully.subscribed=Successfully subscribed.
+
+cartridge.unsubscribe.prompt=Are you sure you want to unsubscribe?
+
+cannot.testrepo=An error occurred when testing repository connection.
+cannot.list.available.cartridges=An error occurred when getting available cartridges.
+cannot.list.subscribed.cartridges=An error occurred when getting subscribed cartridges.
+cannot.unsubscribe=Unsubscribe unsuccessful
+cannot.subscribe=Subscribe unsuccessful

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/available_cartridges.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/available_cartridges.jsp b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/available_cartridges.jsp
new file mode 100644
index 0000000..ae7b24c
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/available_cartridges.jsp
@@ -0,0 +1,186 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ page import="org.apache.axis2.context.ConfigurationContext"%>
+<%@ page import="org.wso2.carbon.CarbonConstants"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIMessage"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page import="org.wso2.carbon.utils.ServerConstants"%>
+<%@ page import="org.wso2.carbon.cartridge.mgt.ui.CartridgeAdminClient"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.Cartridge"%>
+<%@ page import="org.wso2.carbon.adc.mgt.dto.xsd.CartridgeWrapper"%>
+<%@ page import="org.wso2.carbon.adc.mgt.stub.ApplicationManagementServiceADCExceptionException"%>
+<%@ page import="java.text.SimpleDateFormat"%>
+<%@ page import="java.util.ResourceBundle"%>
+<%@ page import="java.util.ArrayList"%>
+
+<jsp:include page="../dialog/display_messages.jsp" />
+
+<%
+	response.setHeader("Cache-Control", "no-cache");
+
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext =
+            (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    CartridgeAdminClient client;
+    Cartridge[] cartridges = null;
+    
+    String item = request.getParameter("item");
+    boolean multiTenant = "available_multitenant_cartridges".equals(item);
+
+    int numberOfPages = 0;
+    String pageNumber = request.getParameter("pageNumber");
+    if (pageNumber == null) {
+        pageNumber = "0";
+    }
+    int pageNumberInt = 0;
+    try {
+        pageNumberInt = Integer.parseInt(pageNumber);
+    } catch (NumberFormatException ignored) {
+    }
+
+    String cartridgeSearchString = request.getParameter("cartridgeSearchString");
+    if (cartridgeSearchString == null) {
+        cartridgeSearchString = "";
+    }
+
+    try {
+        client = new CartridgeAdminClient(cookie, backendServerURL, configContext, request.getLocale());
+        CartridgeWrapper cartridgeWrapper = client.getPagedAvailableCartridges(cartridgeSearchString, pageNumberInt, multiTenant);
+        if (cartridgeWrapper != null) {
+        	numberOfPages = cartridgeWrapper.getNumberOfPages();
+        	cartridges = cartridgeWrapper.getCartridges();
+        }
+    } catch (Exception e) {
+        response.setStatus(500);
+        CarbonUIMessage uiMsg = new CarbonUIMessage(CarbonUIMessage.ERROR, e.getMessage(), e);
+        session.setAttribute(CarbonUIMessage.ID, uiMsg);
+%>
+<jsp:include page="../admin/error.jsp" />
+<%
+	return;
+    }
+    
+    ResourceBundle bundle = ResourceBundle.getBundle(CartridgeAdminClient.BUNDLE, request.getLocale());
+%>
+
+<fmt:bundle basename="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources">
+	<carbon:breadcrumb label="cartrigdes.available.header" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources"
+		topPage="false" request="<%=request%>" />
+
+	<script type="text/javascript">
+		function searchCartridges() {
+			document.searchForm.submit();
+		}
+	</script>
+
+	<div id="middle">
+		<h2>
+			<fmt:message key="cartrigdes.available.header" />
+		</h2>
+
+		<div id="workArea">
+			<form action="available_cartridges.jsp" name="searchForm">
+				<table class="styledLeft">
+					<tr>
+						<td>
+							<table style="border: 0;">
+								<tbody>
+									<tr style="border: 0;">
+										<td style="border: 0;"><fmt:message key="search.cartrigdes" /> <input type="text"
+											name="cartridgeSearchString" value="<%=cartridgeSearchString != null ? cartridgeSearchString : ""%>" />&nbsp;
+										</td>
+										<td style="border: 0;"><a class="icon-link" href="#" style="background-image: url(images/search.gif);"
+											onclick="searchCartridges(); return false;" alt="<fmt:message key="search"/>"> </a></td>
+									</tr>
+								</tbody>
+							</table>
+						</td>
+					</tr>
+				</table>
+				<input type="hidden" name="item" value="<%=item%>" />
+			</form>
+
+			<p>&nbsp;</p>
+			<%
+				if (cartridges != null) {
+					String parameters = "cartridgeSearchString=" + cartridgeSearchString + "&item=" + item;
+			%>
+
+			<carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>" page="available_cartridges.jsp"
+				pageNumberParameterName="pageNumber" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources" prevKey="prev"
+				nextKey="next" parameters="<%=parameters%>" />
+			<p>&nbsp;</p>
+
+			<form name="cartridgesForm" method="post">
+				<input type="hidden" name="pageNumber" value="<%=pageNumber%>" />
+				<table class="styledLeft" id="cartridgesTable" style="width: 100%">
+					<thead>
+						<tr>
+							<th style="width: 15%"><fmt:message key="cartridge.display.name" /></th>
+							<th style="width: 80px"><fmt:message key="cartridge.version" /></th>
+							<th><fmt:message key="cartridge.description" /></th>
+							<th style="width: 15%"><fmt:message key="action" /></th>
+						</tr>
+					</thead>
+					<tbody>
+
+						<%
+							for (Cartridge cartridge : cartridges) {
+								boolean subscribed = "SUBSCRIBED".equals(cartridge.getStatus());
+						%>
+
+						<tr>
+							<td><%=(cartridge.getDisplayName() != null ? cartridge.getDisplayName() : "")%></td>
+							<td><%=(cartridge.getVersion() != null ? cartridge.getVersion() : "")%></td>
+							<td><%=(cartridge.getDescription() != null ? cartridge.getDescription() : "")%></td>
+							<td>
+							<% if (!subscribed) { %>
+								<a href="./subscribe.jsp?cartridgeType=<%=cartridge.getCartridgeType()%>&cartridgeProvider=<%=cartridge.getProvider()%>&multiTenant=<%=cartridge.getMultiTenant()%>&item=<%=item%>"
+									style="background-image: url(images/subscribe.gif);" class="icon-link"> <fmt:message key="subscribe" /></a>
+							<% } else { %>
+								<fmt:message key="already.subscribed" />
+							<% } %>
+							</td>
+						</tr>
+						<%
+							}
+						%>
+					</tbody>
+				</table>
+			</form>
+			<p>&nbsp;</p>
+			<carbon:paginator pageNumber="<%=pageNumberInt%>" numberOfPages="<%=numberOfPages%>" page="available_cartridges.jsp"
+				pageNumberParameterName="pageNumber" resourceBundle="org.wso2.carbon.cartridge.mgt.ui.i18n.Resources" prevKey="prev"
+				nextKey="next" parameters="<%=parameters%>" />
+			<%
+				} else {
+			%>
+			<b><fmt:message key="no.cartridges.found" /></b>
+			<%
+				}
+			%>
+		</div>
+	</div>
+	<script type="text/javascript">
+		alternateTableRows('cartridgesTable', 'tableEvenRow', 'tableOddRow');
+	</script>
+</fmt:bundle>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/docs/userguide.html b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/docs/userguide.html
new file mode 100644
index 0000000..326738d
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/docs/userguide.html
@@ -0,0 +1,41 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Cartridge Management - User Guide</title>
+<link href="../../admin/css/documentation.css" rel="stylesheet"
+	type="text/css" media="all" />
+</head>
+
+<body>
+
+
+	<h1>Cartridge Management</h1>
+
+
+	<p>
+		Please refer WSO2 Stratos 2.0 Wiki <a
+			href="http://docs.wso2.org/wiki/display/Stratos200/GUI+User+Guide">GUI
+			User Guide</a> for more information.
+	</p>
+
+
+</body>
+
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/ajax-loading.gif
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/ajax-loading.gif b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/ajax-loading.gif
new file mode 100644
index 0000000..168d273
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/ajax-loading.gif differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/cartridge.png
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/cartridge.png b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/cartridge.png
new file mode 100644
index 0000000..3cef1d5
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/cartridge.png differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/list.gif
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/list.gif b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/list.gif
new file mode 100644
index 0000000..638d8ab
Binary files /dev/null and b/components/stratos/org.wso2.carbon.cartridge.mgt.ui/2.1.3/src/main/resources/web/cartridge-mgt/images/list.gif differ


[22/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
new file mode 100644
index 0000000..261f705
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
@@ -0,0 +1,606 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
+import org.wso2.carbon.billing.core.beans.PaginatedBalanceInfoBean;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.mgt.beans.*;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class BillingService extends AbstractAdmin {
+
+    private static final Log log = LogFactory.getLog(BillingService.class);
+
+    /**
+     * Gets the available billing periods of the available invoices for the
+     * current customer. Tenant id is taken from registry
+     * @return  an array of BillingPeriod objects
+     * @throws Exception Exception
+     */
+    public BillingPeriod[] getAvailableBillingPeriods() throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getAvailableBillingPeriods(registry);
+    }
+
+    /**
+     * Gets the available billigs dates of a given tenant
+     * @param tenantDomain is the tenant domain
+     * @return an array of BillingPeriods
+     * @throws Exception if an error occurs during the process
+     */
+    public BillingPeriod[] getAvailableBillingPeriodsBySuperTenant(String tenantDomain) throws Exception{
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        
+        List<Customer> customers = billingEngine.getCustomersWithName(tenantDomain);
+        if(customers.size()>0){
+            return getBillingPeriodsFromInvoices(billingEngine.getInvoices(customers.get(0)));
+        }else{
+            return new BillingPeriod[0];
+        }
+    }
+
+    /**
+     * Gets the invoice with a given invoice id
+     * @param invoiceId is the id of the invoice expected
+     * @return  a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    public MultitenancyInvoice getPastInvoice(int invoiceId) throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getPastInvoiceById(registry, invoiceId);
+    }
+
+    /**
+     * Gets the current invoice (interim invoice) of the current customer.
+     * Tenant id is taken from the registry
+     * @return a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    public MultitenancyInvoice getCurrentInvoice() throws Exception {
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        return getCurrentInvoiceOfCustomer(registry);
+    }
+
+    /**
+     * Adds a payment record to the BC_PAYMENT table. Sends a notification email
+     * after adding the record
+     * @param payment is the Payment object which contains the payment record details
+     * @param amount is the paid amount (had to pass this as a string)
+     * @return  the payment id for the added record
+     * @throws Exception if an error occurs during the operation
+     */
+    public int addPayment(Payment payment, String amount) throws Exception {
+        int paymentId = addPaymentRecord(payment, amount);
+        if(paymentId>0){
+            payment.setId(paymentId);
+            sendPaymentReceivedEmail(payment);
+        }
+        return paymentId;
+    }
+
+    /**
+     * Adds a payment record to the BC_REGISTRATION_PAYMENT table. Sends a notification email
+     * after adding the record
+     *
+     * @param payment   the Payment object which contains the payment record details
+     * @param amount    the registration fee paid
+     * @param usagePlan the registered usage plan
+     * @return the payment id for the added record
+     * @throws Exception thrown if an error occurs while adding the record
+     */
+    public int addRegistrationPayment(Payment payment, String amount, String usagePlan)
+            throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Cash cashAmount = new Cash(amount);
+        payment.setAmount(cashAmount);
+        int paymentId = billingEngine.addRegistrationPayment(payment, usagePlan);
+        if (paymentId > 0) {
+            payment.setId(paymentId);
+            sendRegistrationPaymentReceivedEmail(payment);
+        }
+        return paymentId;
+    }
+
+    /**
+     * Adds a payment record for invoice adjustment purposes
+     * @param payment is the Payment object which contains the adjustment details
+     * @param amount is the adjustment amount (had to pass this as a string)
+     * @return the payment id for the added adjustment record
+     * @throws Exception if an error occurs during the operation
+     */
+    public int makeAdjustment(Payment payment, String amount) throws Exception {
+        return addPaymentRecord(payment, amount);
+    }
+    
+    private int addPaymentRecord(Payment payment, String amount) throws Exception{
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Cash cashAmount = new Cash(amount);
+        payment.setAmount(cashAmount);
+        if(payment.getInvoice()!=null){
+            payment.setSubscriptions(billingEngine.getInvoiceSubscriptions(payment.getInvoice().getId()));
+        }
+        int paymentId = billingEngine.addPayment(payment);
+        return paymentId;
+    }
+
+    /**
+     * Gets the paginated BalanceInfoBean to be shown for the super tenant in the paginated mode
+     * @param pageNumber is the expected page number
+     * @return a PaginatedBalanceInfoBean object
+     * @throws Exception Exception
+     */
+    public PaginatedBalanceInfoBean getPaginatedBalances(int pageNumber) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalances(null); //no tenant domain
+        PaginatedBalanceInfoBean paginatedBalanceBean = new PaginatedBalanceInfoBean();
+        DataPaginator.doPaging(pageNumber, balanceBeans, paginatedBalanceBean);
+
+        return paginatedBalanceBean;
+    }
+
+    /**
+     * Gets OutstandingBalanceInfo bean(s).
+     * @param tenantDomain  is the domain of the expected tenant which the super-tenant
+     * wants to view the balance. If this is null, balance info of all the tenants will be shown
+     * @return  an array of OutstandingBalanceInfoBeans
+     * @throws Exception Exception
+     */
+    public OutstandingBalanceInfoBean[] getOutstandingBalance(String tenantDomain) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalanceInfoBeans(tenantDomain);
+        return balanceBeans.toArray(new OutstandingBalanceInfoBean[balanceBeans.size()]);
+    }
+
+    /**
+     * Adds a discount entry
+     * @param discount is the discount object which contains discount information
+     * @param tenantDomain is passed to get the tenant id and set to the discount object
+     * @return true or false based on the result of the operation
+     * @throws Exception if an error occurs during the operation
+     */
+    public boolean addDiscount (Discount discount, String tenantDomain) throws Exception {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        int tenantId = tenantManager.getTenantId(tenantDomain);
+        if(tenantId== MultitenantConstants.INVALID_TENANT_ID){
+            throw new Exception("Invalid tenant domain submitted for a discount");
+        }
+        discount.setTenantId(tenantId);
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        boolean added = billingEngine.addDiscount(discount);
+        if(added){
+            log.info("Discount entry added for tenant: " + discount.getTenantId());
+        }
+        return added;
+    }
+    
+    /**
+     * Gets the past invoice for a given invoice id
+     * @param registry  is the GovernanceUserRegistry
+     * @param invoiceId is the expected invoice id
+     * @return  a MultitenancyInvoice object
+     * @throws Exception Exception
+     */
+    private MultitenancyInvoice getPastInvoiceById(UserRegistry registry,
+                                               int invoiceId) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        Invoice invoice = billingEngine.getInvoice(invoiceId);
+        if (invoice == null) {
+            return null;
+        }
+        
+        Customer customer = getCurrentCustomer(registry, billingEngine);
+        if (customer == null || customer.getId() != invoice.getCustomer().getId()) {
+            String msg = "Trying to looking at an invoice of another customer, customer: " +
+                            (customer == null ? "unknown" : customer.getId()) + ", invoice: " +
+                            invoice.getId() + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        
+        MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+        multitenancyInvoice.setInvoiceId(invoice.getId());
+        multitenancyInvoice.setBillingDate(invoice.getDate());
+        multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+        multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+        multitenancyInvoice.setStartDate(invoice.getStartDate());
+        multitenancyInvoice.setEndDate(invoice.getEndDate());
+        multitenancyInvoice.setTotalCost(invoice.getTotalCost().serializeToString());
+        multitenancyInvoice.setTotalPayments(invoice.getTotalPayment().serializeToString());
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        MultitenancySubscription[] multitenancySubscriptions =
+                new MultitenancySubscription[subscriptions.size()];
+        for (int i = 0; i < subscriptions.size(); i++) {
+            Subscription subscription = subscriptions.get(i);
+            MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+            multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+            multitenancySubscription.setActiveSince(subscription.getActiveSince());
+            multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+            multitenancySubscription.setActive(subscription.isActive());
+
+            // now iterating the items
+            List<Item> billedItems = billingEngine.getBilledItems(subscription);
+            BilledEntry[] itemEntries = new BilledEntry[billedItems.size()];
+            for (int j = 0; j < billedItems.size(); j++) {
+                Item billedItem = billedItems.get(j);
+                if (billedItem.getName().equals(multitenancySubscription.getSubscribedPackage())) {
+                    // ignoring the parent item..
+                    continue;
+                }
+                BilledEntry itemEntry = new BilledEntry();
+                itemEntry.setName(billedItem.getDescription());
+                itemEntry.setCost(billedItem.getCost().serializeToString());
+                itemEntries[j] = itemEntry;
+            }
+            multitenancySubscription.setBilledEntries(itemEntries);
+            multitenancySubscriptions[i] = multitenancySubscription;
+        }
+
+        multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+        // getting the purchase orders
+        List<Payment> payments = invoice.getPayments();
+        if (payments != null) {
+            MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+                    new MultitenancyPurchaseOrder[payments.size()];
+
+            for (int i = 0; i < payments.size(); i++) {
+                Payment payment = payments.get(i);
+                MultitenancyPurchaseOrder multitenancyPurchaseOrder =
+                        new MultitenancyPurchaseOrder();
+
+                multitenancyPurchaseOrder.setId(payment.getId());
+                multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+                multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+                multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+                multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+            }
+            multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+        }
+
+        return multitenancyInvoice;
+    }
+
+    /**
+     * Gets the interim invoice of the current customer
+     * @param registry is the GovernanceUserRegistry
+     * @return an MultiTenancyInvoice object
+     * @throws Exception Exception
+     */
+    private MultitenancyInvoice getCurrentInvoiceOfCustomer(UserRegistry registry) throws Exception {
+        // we have to generate the invoice for this.
+        
+
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngineViewer =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        Customer customer = getCurrentCustomer(registry, billingEngineViewer);
+        if (customer == null) {
+            // no customer => no invoices
+            return null;
+        }
+        
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        billingEngineContext.setCustomer(customer);
+        billingEngineViewer.generateBill(billingEngineContext);
+
+        // reloading the customer with new updates
+        customer = billingEngineContext.getCustomer();
+        Invoice invoice = customer.getActiveInvoice();
+
+        // convert it and return
+        if (invoice == null) {
+            return null;
+        }
+
+        if (customer.getId() != invoice.getCustomer().getId()) {
+            String msg = "Trying to looking at an invoice of another customer, customer: " +
+                            customer.getId() + ", invoice: " + invoice.getId() + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        
+        MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+        multitenancyInvoice.setBillingDate(invoice.getDate());
+        multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+        multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+        multitenancyInvoice.setEndDate(invoice.getEndDate());
+        multitenancyInvoice.setInvoiceId(invoice.getId());
+        multitenancyInvoice.setStartDate(invoice.getStartDate());
+        
+        // getting the purchase orders
+        List<Payment> payments = invoice.getPayments();
+        MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+                new MultitenancyPurchaseOrder[payments.size()];
+        for (int i = 0; i < payments.size(); i++) {
+            Payment payment = payments.get(i);
+            MultitenancyPurchaseOrder multitenancyPurchaseOrder = new MultitenancyPurchaseOrder();
+            multitenancyPurchaseOrder.setId(payment.getId());
+            multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+            multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+            multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+            multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+        }
+        multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+
+        List<Subscription> subscriptions = invoice.getSubscriptions();
+        MultitenancySubscription[] multitenancySubscriptions =
+                new MultitenancySubscription[subscriptions.size()];
+        for (int i = 0; i < subscriptions.size(); i++) {
+            Subscription subscription = subscriptions.get(i);
+            MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+            multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+            multitenancySubscription.setActiveSince(subscription.getActiveSince());
+            multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+            multitenancySubscription.setActive(subscription.isActive());
+
+            BilledEntry[] itemEntries;
+            List<? extends Item> subItems = subscription.getItem().getChildren();
+            if(subItems!=null){
+                itemEntries = new BilledEntry[subItems.size()];
+                for(int j=0; j<subItems.size(); j++){
+                    BilledEntry billedEntry = new BilledEntry();
+                    Item billedItem = subItems.get(j);
+                    billedEntry.setName(billedItem.getDescription()); //description
+                    if(billedItem.getCost()!=null){
+                        billedEntry.setCost(billedItem.getCost().toString());   //cost
+                    }else{
+                        billedEntry.setCost(new Cash("$0").toString());
+                    }
+                    itemEntries[j] = billedEntry;
+                }
+            }else{
+                itemEntries = new BilledEntry[0];
+            }
+
+
+            multitenancySubscription.setBilledEntries(itemEntries);
+            multitenancySubscriptions[i] = multitenancySubscription;
+        }
+        multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+        Cash totalCost = invoice.getTotalCost();
+        if (totalCost == null) {
+            totalCost = new Cash("$0");
+        }
+        multitenancyInvoice.setTotalCost(totalCost.serializeToString());
+        
+        Cash totalPaymentCash = invoice.getTotalPayment();
+        if (totalPaymentCash == null) {
+            totalPaymentCash = new Cash("$0");
+        }
+        multitenancyInvoice.setTotalPayments(totalPaymentCash.serializeToString());
+
+        return multitenancyInvoice;
+    }
+
+    /**
+     * Gets the tenant is and then fills the customer details
+     * @param userRegistry to get the tenant id
+     * @param billingEngine to fill the customer details
+     * @return   a customer object
+     * @throws Exception Exception
+     */
+    private Customer getCurrentCustomer(UserRegistry userRegistry,
+                                        BillingEngine billingEngine) throws Exception {
+        int currentTenantId = userRegistry.getTenantId();
+        TenantManager tenantManger = Util.getRealmService().getTenantManager();
+        Tenant currentTenant = (Tenant) tenantManger.getTenant(currentTenantId);
+
+        List<Customer> customers = billingEngine.getCustomersWithName(currentTenant.getDomain());
+        if (customers == null || customers.isEmpty()) {
+            return null;
+        }
+        return customers.get(0);
+    }
+
+    private BillingPeriod[] getAvailableBillingPeriods(UserRegistry registry) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        
+        Customer customer = getCurrentCustomer(registry, billingEngine);
+        if (customer == null) {
+            return new BillingPeriod[0];
+        }
+        
+        List<Invoice> invoices = billingEngine.getInvoices(customer);
+        if (invoices == null || invoices.size() == 0) {
+            return new BillingPeriod[0];
+        }
+        
+        return getBillingPeriodsFromInvoices(invoices);
+    }
+
+    /**
+     * Get the billing period details when given the invoices
+     * @param invoices is list of invoices
+     * @return an array of billing periods
+     */
+    private BillingPeriod[] getBillingPeriodsFromInvoices(List<Invoice> invoices){
+        BillingPeriod[] billingPeriods = new BillingPeriod[invoices.size()];
+        int index = 0;
+        for (Invoice invoice : invoices) {
+            BillingPeriod billingPeriod = new BillingPeriod();
+            billingPeriod.setInvoiceId(invoice.getId());
+            billingPeriod.setStartDate(invoice.getStartDate());
+            billingPeriod.setEndDate(invoice.getEndDate());
+            billingPeriod.setInvoiceDate(invoice.getDate());
+            billingPeriods[index++] = billingPeriod;
+        }
+        return billingPeriods;
+    }
+
+    /**
+     * Sends the payment received email to the customer
+     * @param payment is the payment object with the payment details 
+     * @throws Exception Exception
+     */
+    private void sendPaymentReceivedEmail(Payment payment) throws Exception{
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+        if(payment.getInvoice()!=null){
+            Invoice invoice = billingEngine.getInvoice(payment.getInvoice().getId());
+            if(invoice!=null){
+                Customer customer = invoice.getCustomer();
+                if(customer!=null){
+                    Map<String, String> mailParameters = new HashMap<String, String>();
+                    mailParameters.put("date",
+                            new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+                    mailParameters.put("transaction-id", payment.getDescription());
+                    mailParameters.put("amount", payment.getAmount().toString());
+                    mailParameters.put("invoice-id", String.valueOf(payment.getInvoice().getId()));
+
+                    try{
+                        String customerName =
+                                ClaimsMgtUtil.getFirstName(Util.getRealmService(), customer.getId());
+                        if(customerName!=null){
+                            mailParameters.put("customer-name", customerName);
+                        }else{
+                            mailParameters.put("customer-name", "");
+                        }
+
+                    }catch(Exception e){
+                        log.error("Could not get tenant information for tenant: " +
+                                customer.getName() + "\n" + e.getMessage());
+                        mailParameters.put("customer-name", "");
+                    }
+
+                    //sending the mail to the customer
+                    billingEngine.sendPaymentReceivedEmail(
+                            customer.getEmail(),
+                            BillingConstants.PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+                            mailParameters);
+
+                    String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+                    //customer's first name is not important to finance team. Therefore it is
+                    //being replace with the domain name
+                    mailParameters.put("customer-name", customer.getName());
+                    billingEngine.sendPaymentReceivedEmail(
+                            financeEmail,
+                            BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+                            mailParameters
+                    );
+                }else{
+                    String msg = "Cannot send email to customer. Customer details not available";
+                    log.error(msg);
+                    throw new Exception(msg);
+                }
+            }else{
+                String msg = "Cannot send email to customer. Invoice details not available";
+                log.error(msg);
+                throw new Exception(msg);
+            }
+        }else{
+            String msg = "Cannot send email to customer. Invoice Id is not available";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+    }
+
+
+    private void sendRegistrationPaymentReceivedEmail(Payment payment) throws Exception {
+        BillingManager billingManager = Util.getBillingManager();
+        BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+        String tenantDomain = payment.getDescription().split(" ")[0];
+        int tenantId = Util.getTenantManager().getTenantId(tenantDomain);
+        Tenant tenant = (Tenant) Util.getTenantManager().getTenant(tenantId);
+
+        Map<String, String> mailParameters = new HashMap<String, String>();
+        mailParameters.put("date", new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+        mailParameters.put("transaction-id", payment.getDescription().split(" ")[1]);
+        mailParameters.put("amount", payment.getAmount().toString());
+        mailParameters.put("invoice-id", "Registration - " + tenantDomain);
+        mailParameters.put("tenant-domain", tenantDomain);
+
+        String customerName = null;
+        String customerEmail = tenant.getEmail();
+        try {
+            customerName = ClaimsMgtUtil.getFirstName(Util.getRealmService(), tenantId);
+            if (customerName != null) {
+                mailParameters.put("customer-name", customerName);
+            } else {
+                mailParameters.put("customer-name", "");
+            }
+
+        } catch (Exception e) {
+            log.error("Could not get tenant information for tenant: " +
+                      customerName + "\n" + e.getMessage());
+            mailParameters.put("customer-name", "");
+        }
+
+        //sending the mail to the customer
+        billingEngine.sendPaymentReceivedEmail(
+                customerEmail,
+                BillingConstants.REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+                mailParameters);
+
+        String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+        //customer's first name is not important to finance team. Therefore it is
+        //being replace with the domain name
+        mailParameters.put("customer-name", customerName);
+        billingEngine.sendPaymentReceivedEmail(
+                financeEmail,
+                BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+                mailParameters
+        );
+
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
new file mode 100644
index 0000000..7c354e4
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
@@ -0,0 +1,173 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.billing.core.*;
+import org.wso2.carbon.billing.mgt.api.DefaultTenantBilling;
+import org.wso2.carbon.billing.mgt.api.MultitenancyBillingInfo;
+import org.wso2.carbon.billing.mgt.handlers.MultitenancySubscriptionFeedingHandler;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.usage.api.TenantUsageRetriever;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.throttling.agent.ThrottlingAgent;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+public class Util {
+    private static BillingManager billingManager = null;
+    private static DataAccessManager dataAccessManager = null;
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static TenantUsageRetriever tenantUsageRetriever;
+    private static MultitenancyBillingInfo billingInfo;
+
+    public static ConfigurationContextService getContextService() {
+        return contextService;
+    }
+
+    public static void setContextService(ConfigurationContextService contextService) {
+        Util.contextService = contextService;
+    }
+
+    private static ServiceTracker throttlingRuleInvokerTracker = null;
+    private static BundleContext bundleContext;
+    private static Log log = LogFactory.getLog(Util.class);
+    private static ConfigurationContextService contextService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static void setTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        Util.tenantUsageRetriever = tenantUsageRetriever;
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static TenantUsageRetriever getTenantUsageRetriever() {
+        return tenantUsageRetriever;
+    }
+
+    public static TenantManager getTenantManager() {
+        if (realmService == null) {
+            return null;
+        }
+        return realmService.getTenantManager();
+    }
+
+    public static BillingManager getBillingManager() {
+        return billingManager;
+    }
+
+    public static void setBillingManager(BillingManager billingManager) {
+        Util.billingManager = billingManager;
+    }
+
+    public static void registerSubscriptionFeedingHandlers(BundleContext bundleContext) {
+        bundleContext.registerService(BillingHandler.class.getName(),
+                new MultitenancySubscriptionFeedingHandler(), null);
+    }
+    
+    public static void registerTenantBillingService(BundleContext bundleContext) {
+        bundleContext.registerService(TenantBillingService.class.getName(),
+                new DefaultTenantBilling(), null);
+    }
+
+    public static void scheduleBilling() throws BillingException {
+        BillingEngine billingEngine =
+                billingManager.getBillingEngine(StratosConstants.MULTITENANCY_SCHEDULED_TASK_ID);
+        if (billingEngine != null) {
+            billingEngine.scheduleBilling();
+        } else {
+            log.info("No billing engine for scheduled tasks");
+        }
+
+    }
+
+    public static void registerBillingInfo(BundleContext bundleContext) throws Exception {
+        billingInfo = new MultitenancyBillingInfo();
+        bundleContext.registerService(MultitenancyBillingInfo.class.getName(), billingInfo, null);
+    }
+
+    public static MultitenancyBillingInfo getMultitenancyBillingInfo() {
+        return billingInfo;
+    }
+
+    public static DataAccessManager getDataAccessManager() {
+        return dataAccessManager;
+    }
+
+    public static void setDataAccessManager(DataAccessManager dataAccessManager) {
+        Util.dataAccessManager = dataAccessManager;
+    }
+
+    public static void initDataAccessManager() {
+        DataAccessManager dataAccessManager = new DataAccessManager(
+                billingManager.getBillingConfiguration().getDataSource());
+        Util.dataAccessManager = dataAccessManager;
+    }
+
+    /**
+     * This method used to create service tracker that tracks throttlingAgent service which
+     * registered when throttling agent starts
+     *
+     * @param bundleContext bundle context that belongs to component
+     */
+    public static void initializeThrottling(BundleContext bundleContext) {
+        throttlingRuleInvokerTracker = new ServiceTracker(bundleContext, ThrottlingAgent.class.getName(),
+                null);
+        throttlingRuleInvokerTracker.open();
+    }
+
+    /**
+     * This method updates the throttling rules for given tenant and update the cache at manager
+     *
+     * @param tenantId Tenant Id of the tenant that need to update throttling rules at manager
+     */
+    public static void executeThrottlingRules(int tenantId) {
+        try {
+            ThrottlingAgent embeddedRuleInvoker =
+                    (ThrottlingAgent) throttlingRuleInvokerTracker.getService();
+            if (embeddedRuleInvoker != null) {
+                embeddedRuleInvoker.executeThrottlingRules(tenantId);
+            }
+        } catch (Exception e) {
+            log.error("Error in executing throttling rules in manager" + e.toString());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..71e6e35
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+  ~
+  ~  Licensed under the Apache License, Version 2.0 (the "License");
+  ~  you may not use this file except in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~       http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing, software
+  ~  distributed under the License is distributed on an "AS IS" BASIS,
+  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~  See the License for the specific language governing permissions and
+  ~  limitations under the License.
+  -->
+
+<component xmlns="http://products.wso2.org/carbon">
+    <ManagementPermissions>
+        <ManagementPermission>
+            <DisplayName>Billing</DisplayName>
+            <ResourceId>/permission/admin/billing</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>View Invoice</DisplayName>
+            <ResourceId>/permission/admin/billing/invoice</ResourceId>
+        </ManagementPermission>
+    </ManagementPermissions>
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..3aaf3de
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<!--
+		! ! Copyright 2006 The Apache Software Foundation. ! ! Licensed under
+		the Apache License, Version 2.0 (the "License"); ! you may not use
+		this file except in compliance with the License. ! You may obtain a
+		copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0
+		! ! Unless required by applicable law or agreed to in writing,
+		software ! distributed under the License is distributed on an "AS IS"
+		BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+		or implied. ! See the License for the specific language governing
+		permissions and ! limitations under the License. !
+	-->
+<serviceGroup>
+
+	<service name="MultitenancyBillingService" scope="transportsession">
+		<transports>
+			<transport>https</transport>
+		</transports>
+
+		<parameter name="ServiceClass" locked="false">
+			org.wso2.carbon.billing.mgt.services.BillingService
+        </parameter>
+
+        <parameter name="adminService" locked="true">true</parameter>
+
+        <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+        <operation name="getPaginatedBalances">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getOutstandingBalance">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getAvailableBillingPeriodsBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="makeAdjustment">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="addRegistrationPayment">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+  	</service>
+
+    <service name="BillingDataAccessService" scope="transportsession">
+        <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+		<transports>
+			<transport>https</transport>
+		</transports>
+
+		<parameter name="ServiceClass" locked="false">
+			org.wso2.carbon.billing.mgt.services.BillingDataAccessService
+        </parameter>
+
+        <parameter name="adminService" locked="true">true</parameter>
+
+        <operation name="changeSubscriptionBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="deactivateActiveSubscriptionBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getActiveSubscriptionOfCustomerBySuperTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="addSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="getInactiveSubscriptionsOfCustomer">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+
+        <operation name="activateSubscription">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+        
+        <operation name="changeSubscriptionForTenant">
+            <parameter name="superTenantService" locked="true">true</parameter>
+        </operation>
+  	</service>
+
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/pom.xml
new file mode 100644
index 0000000..03fb6c5
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/pom.xml
@@ -0,0 +1,117 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>billing-parent</artifactId>
+        <version>2.1.0</version>
+	<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.billing.mgt</artifactId>
+    <version>2.1.3</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Billing</name>
+
+    <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>
+                        <!--<Require-Bundle>
+                            drools;visibility:=reexport
+                        </Require-Bundle>-->
+                        <Private-Package>
+                            org.wso2.carbon.billing.mgt.internal.*,
+                            org.wso2.carbon.billing.mgt.beans.*,
+                            org.wso2.carbon.billing.mgt.util.*,
+                        </Private-Package>
+                        <Export-Package>
+                            org.wso2.carbon.billing.mgt.dataobjects.*,
+                            org.wso2.carbon.billing.mgt.handlers.*,
+                            org.wso2.carbon.billing.mgt.api.*,
+                            org.wso2.carbon.billing.mgt.services.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.rule.*,
+                            org.quartz.*; version=2.1.1,
+                            org.apache.synapse.task.*,
+                            org.wso2.carbon.stratos.common.*,
+                            org.wso2.carbon.throttling.agent.client.*,
+                            org.wso2.carbon.throttling.agent.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.billing.core</artifactId>
+			<version>2.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.usage</artifactId>
+	    <version>2.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.throttling.agent</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
new file mode 100644
index 0000000..cd9b4bd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
@@ -0,0 +1,201 @@
+package org.wso2.carbon.billing.mgt.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.mgt.services.BillingDataAccessService;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.Calendar;
+
+public class DefaultTenantBilling implements TenantBillingService {
+    
+    private static final Log log = LogFactory.getLog(DefaultTenantBilling.class);
+    
+    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException {
+
+        Customer customer = new Customer();
+        customer.setName(tenant.getDomain());
+        customer.setEmail(tenant.getEmail());
+        customer.setStartedDate(tenant.getCreatedDate());
+        customer.setFullName(tenant.getAdminFirstName() + " " + tenant.getAdminLastName());
+
+        customer.setId(tenant.getId());
+        Subscription subscription = new Subscription();
+        subscription.setCustomer(customer);
+        subscription.setActive(false);
+        subscription.setActiveSince(Calendar.getInstance().getTime());
+        Item item = new Item();
+        subscription.setItem(item);
+        subscription.setSubscriptionPlan(usagePlan);
+        try {
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            dataAccessService.addSubscription(subscription);
+        } catch (Exception e) {
+            log.error("Could not add new subscription for tenant: " +
+                      tenant.getDomain() + " " + e.getMessage(), e);
+        }
+    }
+
+    public String getActiveUsagePlan(String tenantDomain) throws StratosException {
+        Subscription subscription;
+        try {
+            TenantManager tenantMan = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantMan.getTenantId(tenantDomain);
+            BillingDataAccessService billingDataAccessService = new BillingDataAccessService();
+            subscription = billingDataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+        } catch (Exception e) {
+            String msg = "Error occurred while getting the usage plan for tenant: " + 
+                         tenantDomain + " " + e.getMessage();
+            log.error(msg);
+            throw new StratosException(msg, e);
+        }
+
+        if(subscription!=null){
+            return subscription.getSubscriptionPlan();
+        }else{
+            return null;
+        }
+    }
+
+    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException {
+        try {
+            TenantManager tenantManager = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantManager.getTenantId(tenantDomain);
+
+            BillingDataAccessService billingDataAccessService = new BillingDataAccessService();
+            Subscription currentSubscription = billingDataAccessService.
+                    getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+
+            if (currentSubscription != null && currentSubscription.getSubscriptionPlan() != null) {
+                if (!currentSubscription.getSubscriptionPlan().equals(usagePlan)) {
+                    boolean updated = billingDataAccessService.changeSubscriptionBySuperTenant(tenantId, usagePlan);
+                    if (updated) {
+                        log.debug("Usage plan was changed successfully from " + currentSubscription.getSubscriptionPlan() +
+                                  " to " + usagePlan);
+                    } else {
+                        log.debug("Usage plan was not changed");
+                    }
+                }
+            }else{
+                //tenant does not have an active subscription. First we have to check whether the tenant
+                //is active. If he is active only we will add a new usage plan. Otherwise it is useless
+                //to add a usage plan to an inactive tenant
+                Tenant tenant = tenantManager.getTenant(tenantId);
+                if(tenant.isActive()){
+                    //we add a new subscription
+                    Subscription subscription = new Subscription();
+                    subscription.setActive(true);
+                    subscription.setSubscriptionPlan(usagePlan);
+                    subscription.setActiveSince(null);
+                    subscription.setActiveUntil(null);
+                    Customer customer = new Customer();
+                    customer.setName(tenantDomain);
+                    customer.setId(tenantId);
+                    subscription.setCustomer(customer);
+
+                    int subsId = billingDataAccessService.addSubscription(subscription);
+                    if(subsId>0){
+                        log.info("Added a new " + subscription.getSubscriptionPlan() + " plan for the tenant " +
+                                 tenantDomain);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while changing the subscription plan for tenant: " + tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void activateUsagePlan(String tenantDomain) throws StratosException {
+        try {
+            TenantManager tenantManager = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantManager.getTenantId(tenantDomain);
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            Subscription subscription = dataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+            if (subscription != null) {
+                String msg = "Unable to activate the subscription for tenant: " + tenantId +
+                             ". An active subscription already exists";
+                log.info(msg);
+            } else {
+                Subscription[] inactiveSubscriptions = dataAccessService.getInactiveSubscriptionsOfCustomer(tenantId);
+                if (inactiveSubscriptions.length == 1) {
+                    //This is the scenario where the tenant has registered, but not activated yet
+                    subscription = inactiveSubscriptions[0];
+                    boolean activated = dataAccessService.activateSubscription(subscription.getId());
+                    if (activated) {
+                        log.info("Subscription was activated for tenant: " + tenantId);
+                    }
+                }else if(inactiveSubscriptions.length > 1){
+                    //this is the scenario where the tenant has been deactivated by admin and
+                    //again activated. Here, I am adding a new active subscription which is similar to the
+                    //last existed one
+                    Subscription subscriptionToAdd = inactiveSubscriptions[0];
+                    subscriptionToAdd.setActive(true);
+                    subscriptionToAdd.setActiveSince(null);
+                    subscriptionToAdd.setActiveUntil(null);
+
+                    int subsId = dataAccessService.addSubscription(subscriptionToAdd);
+                    if(subsId>0){
+                        log.info("New subscription: " + subscriptionToAdd.getSubscriptionPlan() +
+                                " added and it was activated for tenant: " + tenantId);
+                    }
+                }else{
+                    //this means there are no subscriptions. Lets handle this later
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while activating the subscription for tenant: " +
+                    tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException {
+        try {
+            TenantManager tenantMan = 
+                    CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantMan.getTenantId(tenantDomain);
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+
+            Subscription subscription = 
+                    dataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+
+            if (subscription == null) {
+                String msg = "Unable to deactivate the subscription for tenant: " + tenantId +
+                        ". An active subscription doesn't exist";
+                log.info(msg);
+            } else {
+                boolean deactivated = 
+                        dataAccessService.deactivateActiveSubscriptionBySuperTenant(tenantId);
+                if (deactivated) {
+                    log.info("Active subscription of tenant " + tenantId + " was deactivated");
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while deactivating the active subscription of tenant: " +
+                    tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void deleteBillingData(int tenantId) throws StratosException{
+        try {
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            dataAccessService.deleteBillingData(tenantId);
+        } catch (Exception e) {
+            String msg = "Error deleting subscription  for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
new file mode 100644
index 0000000..eacb0d4
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.api;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyPackage;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Reads the multitenancy-packages.xml and populates the
+ * multitenancy packages list
+ */
+public class MultitenancyBillingInfo {
+    private static Log log = LogFactory.getLog(MultitenancyBillingInfo.class);
+    private static final String PACKAGE_DESCRIPTION_CONFIG_FILENAME = "multitenancy-packages.xml";
+    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
+            "http://wso2.com/carbon/multitenancy/billing/pacakges";
+    
+    List<MultitenancyPackage> multitenancyPackages = new ArrayList<MultitenancyPackage>();
+
+    public MultitenancyBillingInfo() throws BillingException {
+        // this should be only available to the super tenants..
+        multitenancyPackages = deserializePackageDescriptionConfig();
+    }
+
+    public List<MultitenancyPackage> getMultitenancyPackages() {
+        return multitenancyPackages;
+    }
+
+    /*
+     * Deserialize following XML
+    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+        <package name="multitenancy-free">
+            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+            <users>
+                <limit>5</limit>
+                <charge>0</charge> <!-- charge per month -->
+            </users>
+            <resourceVolume>
+                <limit>10</limit> <!--mb per user -->
+            </resourceVolume>
+            <bandwidth>
+                <limit>1000</limit> <!-- mb per user -->
+                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+            </bandwidth>
+        </package>
+        <package name="multitenancy-small">
+            ...
+        </package>
+    </packages>
+     */
+    private List<MultitenancyPackage> deserializePackageDescriptionConfig() throws BillingException {
+        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                PACKAGE_DESCRIPTION_CONFIG_FILENAME;
+        
+        OMElement packageConfigs;
+        try {
+            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
+        } catch (Exception e) {
+            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        Iterator packageConfigsChildsIt = packageConfigs.getChildElements();
+        while (packageConfigsChildsIt.hasNext()) {
+            OMElement packageConfigEle = (OMElement) packageConfigsChildsIt.next();
+            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
+                    packageConfigEle.getQName())) {
+                continue;
+            }
+            
+            MultitenancyPackage multitenancyPackage = new MultitenancyPackage();
+            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
+            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
+            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
+            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
+
+            String resourceVolumeLimit =
+                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
+            String resourceVolumeOveruseCharge =
+                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
+            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
+            String bandwidthOveruseCharge =
+                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
+            String cartridgeCPUHourLimit =
+                    getPackageConfigValue("cartridge.hourLimit", packageConfigEle);
+            String cartridgeCPUHourOverUsageCharge =
+                    getPackageConfigValue("cartridge.overUsageCharge", packageConfigEle);
+            int usersLimitInt = -1;
+            if (!usersLimit.equals("unlimited")) {
+                usersLimitInt = Integer.parseInt(usersLimit);
+            }
+            int resourceVolumeLimitInt = -1;
+            if (!resourceVolumeLimit.equals("unlimited")) {
+                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
+            }
+            int bandwidthLimitInt = -1;
+            if (!bandwidthLimit.equals("unlimited")) {
+                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
+            }
+            
+            int cartridgeCPUHourLimitInt = -1;
+            if(cartridgeCPUHourLimit!=null && !cartridgeCPUHourLimit.equals("unlimited")){
+                cartridgeCPUHourLimitInt = Integer.parseInt(cartridgeCPUHourLimit);
+            }
+
+
+            multitenancyPackage.setName(packageName);
+            multitenancyPackage.setSubscriptionCharge(new Cash(subscriptionCharge));
+            multitenancyPackage.setUsersLimit(usersLimitInt);
+            multitenancyPackage.setChargePerUser(new Cash(usersCharge));
+            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
+            multitenancyPackage.setResourceVolumeOveruseCharge(new Cash(resourceVolumeOveruseCharge));
+            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
+            multitenancyPackage.setBandwidthOveruseCharge(new Cash(bandwidthOveruseCharge));
+            multitenancyPackage.setCartridgeCPUHourLimit(cartridgeCPUHourLimitInt);
+            multitenancyPackage.setCartridgeCPUOveruseCharge(new Cash(cartridgeCPUHourOverUsageCharge));
+
+            
+            multitenancyPackages.add(multitenancyPackage);
+        }
+        return multitenancyPackages;
+    }
+
+    private String getPackageConfigValue(String key, OMElement packageNode) throws BillingException {
+        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
+        AXIOMXPath xpathExpression;
+        try {
+            xpathExpression = new AXIOMXPath(qualifiedKey);
+            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
+            List valueNodes = xpathExpression.selectNodes(packageNode);
+            if (valueNodes.isEmpty()) {
+                if (log.isDebugEnabled()) {
+                    String msg = "No results found parsing package configuration for key: " + 
+                            qualifiedKey + ".";
+                    log.debug(msg);
+                }
+                return null;
+            }
+            OMElement valueNode = (OMElement) valueNodes.get(0);
+            return valueNode.getText();
+        } catch (JaxenException e) {
+            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
new file mode 100644
index 0000000..8b88b99
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+/**
+ * Under a subscription there are billed items. For example
+ * subscription fee, bandwidth overuse charge, storage overuse charge
+ */
+public class BilledEntry {
+    String name;
+    String cost;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getCost() {
+        return cost;
+    }
+
+    public void setCost(String cost) {
+        this.cost = cost;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
new file mode 100644
index 0000000..76ff4e6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Date;
+
+/**
+ * This class is used when providing available invoices to the user
+ */
+public class BillingPeriod {
+    private int invoiceId;
+    private Date startDate;
+    private Date endDate;
+    private Date invoiceDate;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public Date getInvoiceDate() {
+        return new Date(invoiceDate.getTime());
+    }
+
+    public void setInvoiceDate(Date invoiceDate) {
+        this.invoiceDate = new Date(invoiceDate.getTime());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
new file mode 100644
index 0000000..994a161
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Arrays;
+import java.util.Date;
+
+public class MultitenancyInvoice {
+    private int invoiceId;
+    private Date billingDate;
+    private Date startDate;
+    private Date endDate;
+    private String boughtForward;
+    private String carriedForward;
+    private String totalPayments;
+    private String totalCost;
+    private boolean lastInvoice;
+    private MultitenancySubscription[] subscriptions;
+    private MultitenancyPurchaseOrder[] purchaseOrders;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public Date getBillingDate() {
+        return new Date(billingDate.getTime());
+    }
+
+    public void setBillingDate(Date billingDate) {
+        this.billingDate = new Date(billingDate.getTime());
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public String getBoughtForward() {
+        return boughtForward;
+    }
+
+    public void setBoughtForward(String boughtForward) {
+        this.boughtForward = boughtForward;
+    }
+
+    public String getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(String carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public String getTotalPayments() {
+        return totalPayments;
+    }
+
+    public void setTotalPayments(String totalPayments) {
+        this.totalPayments = totalPayments;
+    }
+
+    public String getTotalCost() {
+        return totalCost;
+    }
+
+    public void setTotalCost(String totalCost) {
+        this.totalCost = totalCost;
+    }
+
+    public boolean isLastInvoice() {
+        return lastInvoice;
+    }
+
+    public void setLastInvoice(boolean lastInvoice) {
+        this.lastInvoice = lastInvoice;
+    }
+
+    public MultitenancySubscription[] getSubscriptions() {
+        return Arrays.copyOf(subscriptions, subscriptions.length);
+    }
+
+    public void setSubscriptions(MultitenancySubscription[] subscriptions) {
+        this.subscriptions = Arrays.copyOf(subscriptions, subscriptions.length);
+    }
+
+    public MultitenancyPurchaseOrder[] getPurchaseOrders() {
+        return Arrays.copyOf(purchaseOrders, purchaseOrders.length);
+    }
+
+    public void setPurchaseOrders(MultitenancyPurchaseOrder[] purchaseOrders) {
+        this.purchaseOrders = Arrays.copyOf(purchaseOrders, purchaseOrders.length);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
new file mode 100644
index 0000000..ffddda0
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Date;
+
+/**
+ * Payment record details
+ */
+public class MultitenancyPurchaseOrder {
+    private Date paymentDate;
+    private String payment;
+    private int id;
+    private String transactionId;
+
+    public Date getPaymentDate() {
+        return new Date(paymentDate.getTime());
+    }
+
+    public void setPaymentDate(Date paymentDate) {
+        this.paymentDate = new Date(paymentDate.getTime());
+    }
+
+    public String getPayment() {
+        return payment;
+    }
+
+    public void setPayment(String payment) {
+        this.payment = payment;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getTransactionId() {
+        return transactionId;
+    }
+
+    public void setTransactionId(String transactionId) {
+        this.transactionId = transactionId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
new file mode 100644
index 0000000..5490e9f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Arrays;
+import java.util.Date;
+
+public class MultitenancySubscription {
+    String subscribedPackage;
+    BilledEntry[] billedEntries;
+    Date activeSince;
+    Date activeUntil;
+    boolean isActive;
+
+    public String getSubscribedPackage() {
+        return subscribedPackage;
+    }
+
+    public void setSubscribedPackage(String subscribedPackage) {
+        this.subscribedPackage = subscribedPackage;
+    }
+
+    public BilledEntry[] getBilledEntries() {
+        return Arrays.copyOf(billedEntries, billedEntries.length);
+    }
+
+    public void setBilledEntries(BilledEntry[] billedEntries) {
+        this.billedEntries = Arrays.copyOf(billedEntries, billedEntries.length);
+    }
+
+    public Date getActiveSince() {
+        return new Date(activeSince.getTime());
+    }
+
+    public void setActiveSince(Date activeSince) {
+        this.activeSince = new Date(activeSince.getTime());
+    }
+
+    public Date getActiveUntil() {
+        return new Date(activeUntil.getTime());
+    }
+
+    public void setActiveUntil(Date activeUntil) {
+        this.activeUntil = new Date( activeUntil.getTime());
+    }
+
+    public boolean isActive() {
+        return isActive;
+    }
+
+    public void setActive(boolean active) {
+        isActive = active;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
new file mode 100644
index 0000000..5d8aea6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Multitenancy customer class
+ */
+public class MultitenancyCustomer extends Customer {
+
+    private int numberOfUsers;
+    private long incomingBandwidth;
+    private long outgoingBandwidth;
+    private long totalBandwidth;
+    private long currentStorage;
+    private long historyStorage;
+    private long totalStorage;
+    private long cartridgeCPUHours;
+    private int tenantId = MultitenantConstants.INVALID_TENANT_ID;
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public int getNumberOfUsers() {
+        return numberOfUsers;
+    }
+
+    public void setNumberOfUsers(int numberOfUsers) {
+        this.numberOfUsers = numberOfUsers;
+    }
+
+    public long getIncomingBandwidth() {
+        return incomingBandwidth;
+    }
+
+    public void setIncomingBandwidth(long incomingBandwidth) {
+        this.incomingBandwidth = incomingBandwidth;
+    }
+
+    public long getOutgoingBandwidth() {
+        return outgoingBandwidth;
+    }
+
+    public void setOutgoingBandwidth(long outgoingBandwidth) {
+        this.outgoingBandwidth = outgoingBandwidth;
+    }
+
+    public long getTotalBandwidth() {
+        return totalBandwidth;
+    }
+
+    public void setTotalBandwidth(long totalBandwidth) {
+        this.totalBandwidth = totalBandwidth;
+    }
+
+    public long getCurrentStorage() {
+        return currentStorage;
+    }
+
+    public void setCurrentStorage(long currentStorage) {
+        this.currentStorage = currentStorage;
+    }
+
+    public long getHistoryStorage() {
+        return historyStorage;
+    }
+
+    public void setHistoryStorage(long historyStorage) {
+        this.historyStorage = historyStorage;
+    }
+
+    public long getTotalStorage() {
+        return totalStorage;
+    }
+
+    public void setTotalStorage(long totalStorage) {
+        this.totalStorage = totalStorage;
+    }
+
+    public long getCartridgeCPUHours() {
+        return cartridgeCPUHours;
+    }
+
+    public void setCartridgeCPUHours(long cartridgeCPUHours) {
+        this.cartridgeCPUHours = cartridgeCPUHours;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        if (!super.equals(o)) {
+            return false;
+        }
+
+        MultitenancyCustomer that = (MultitenancyCustomer) o;
+
+        if (tenantId != that.tenantId) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = super.hashCode();
+        result = 31 * result + tenantId;
+        return result;
+    }
+}


[27/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
new file mode 100644
index 0000000..05f3d8b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
@@ -0,0 +1,2557 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.jdbc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.billing.core.utilities.DataSourceHolder;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import javax.sql.DataSource;
+import java.sql.*;
+import java.sql.Date;
+import java.util.*;
+
+public class DataAccessObject {
+    public static final Log log = LogFactory.getLog(DataAccessObject.class);
+    public static final int INVALID = -1;
+    //following timezone will be changed according to the one defined in the billing-config.xml
+    //It is done in the MonthlyScheduleHelper
+    public static String TIMEZONE="GMT-8:00";
+
+    DataSource dataSource;
+
+    public DataAccessObject(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    public DataAccessObject() {
+        this.dataSource = DataSourceHolder.getDataSource();
+    }
+    // transaction handling
+
+    public void beginTransaction() throws BillingException {
+        if (Transaction.getNestedDepth() != 0) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not started, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+            Transaction.incNestedDepth();
+            return;
+        }
+
+        Connection conn;
+        try {
+            conn = dataSource.getConnection();
+            if (conn.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
+                conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+            }
+            conn.setAutoCommit(false);
+            Transaction.incNestedDepth();
+        } catch (SQLException e) {
+            String msg = "Failed to start new billing transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        Transaction.setConnection(conn);
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        Transaction.setRollbacked(true);
+        if (Transaction.getNestedDepth() != 1) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not rollbacked, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+
+            Transaction.decNestedDepth();
+            return;
+        }
+
+        Connection conn = Transaction.getConnection();
+        try {
+            conn.rollback();
+
+        } catch (SQLException e) {
+            String msg = "Failed to rollback transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            endTransaction();
+            Transaction.decNestedDepth();
+        }
+    }
+
+    public void commitTransaction() throws BillingException {
+        if (Transaction.getNestedDepth() != 1) {
+            if (log.isTraceEnabled()) {
+                log.trace("The transaction was not commited, because it is called within a "
+                        + "transaction, nested depth: " + Transaction.getNestedDepth() + ".");
+            }
+            Transaction.decNestedDepth();
+            return;
+        }
+
+        if (Transaction.isRollbacked()) {
+            String msg = "The transaction is already rollbacked, you can not commit a transaction "
+                    + "already rollbacked, nested depth: " + Transaction.getNestedDepth() + ".";
+            log.debug(msg);
+            Transaction.decNestedDepth();
+            throw new BillingException(msg);
+        }
+
+        Connection conn = Transaction.getConnection();
+        try {
+            conn.commit();
+
+        } catch (SQLException e) {
+            String msg = "Failed to commit transaction. " + e.getMessage();
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            endTransaction();
+            Transaction.decNestedDepth();
+        }
+    }
+
+    private void endTransaction() throws BillingException {
+
+        if (Transaction.isStarted()) {
+            Connection conn = Transaction.getConnection();
+            try {
+                conn.close();
+                //log.info("Database connection closed: ");
+            } catch (SQLException e) {
+                String msg = "Failed to close transaction. " + e.getMessage();
+                log.error(msg, e);
+                throw new BillingException(msg, e);
+
+            } finally {
+                Transaction.setStarted(false);
+                Transaction.setConnection(null);
+            }
+        }
+    }
+
+    public int getItemIdWithName(String itemName) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int id = INVALID;
+        try {
+            String sql = "SELECT BC_ID FROM BC_ITEM WHERE BC_NAME=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                id = result.getInt("BC_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to check the existence of the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            
+        }
+
+        return id;
+    }
+
+    public int getItemId(String itemName, int parentId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int id = INVALID;
+        try {
+            String sql = "SELECT BC_ID FROM BC_ITEM WHERE BC_NAME=? AND BC_PARENT_ITEM_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+            ps.setInt(2, parentId);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                id = result.getInt("BC_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to check the existence of the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+
+        return id;
+    }
+
+    public List<Item> getItemsWithName(String itemName) throws BillingException {
+        /*Connection conn = null;
+        try {
+              conn = DataSourceHolder.getDataSource().getConnection();
+                } catch (SQLException e) {
+                    String msg = "Failed to establish data connection";
+                    log.error(msg, e);
+                }
+        */
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Item> items = new ArrayList<Item>();
+
+        try {
+            String sql = "SELECT BC_ID, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM WHERE BC_NAME=?";
+            ps = conn.prepareStatement(sql);
+            ps.setString(1, itemName);
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = new Item();
+                item.setName(itemName);
+                int id = result.getInt("BC_ID");
+                item.setId(id);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    Item parentItem;
+                    if (id == parentId) {
+                        parentItem = item;
+                    } else {
+                        parentItem = getItem(parentId);
+                    }
+                    item.setParent(parentItem);
+                }
+                items.add(item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the items with name " + itemName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            /*try{
+                if(conn !=null){
+                    conn.close();
+                }
+            }
+            catch (SQLException e){
+                String msg = "Error while closing connection";
+                log.error(msg, e);
+            }*/
+        }
+
+        return items;
+    }
+
+    public int addInvoice(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceId = INVALID;
+
+        try {
+            String sql = "INSERT INTO BC_INVOICE (BC_TENANT_ID, BC_DATE, BC_START_DATE, "
+                    + "BC_END_DATE, BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, "
+                    + "BC_TOTAL_COST) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoice.getCustomer().getId());
+            ps.setTimestamp(2, new Timestamp(invoice.getDate().getTime()));
+            ps.setTimestamp(3, new Timestamp(invoice.getStartDate().getTime()));
+            ps.setTimestamp(4, new Timestamp(invoice.getEndDate().getTime()));
+            ps.setString(5, invoice.getBoughtForward().serializeToString());
+            ps.setString(6, invoice.getCarriedForward().serializeToString());
+            ps.setString(7, invoice.getTotalPayment().serializeToString());
+            ps.setString(8, invoice.getTotalCost().serializeToString());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceId = result.getInt(1);
+                invoice.setId(invoiceId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice for customer, "
+                    + invoice.getCustomer().getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceId;
+    }
+
+    public int addItem(Item item) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int itemId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_ITEM (BC_NAME, BC_COST, BC_DESCRIPTION, " +
+                    "BC_PARENT_ITEM_ID) " +
+                    "VALUES (?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setString(1, item.getName());
+
+
+            Cash cost = item.getCost();
+            if (cost == null) {
+                ps.setString(2, null);
+            } else {
+                ps.setString(2, cost.serializeToString());
+            }
+            ps.setString(3, item.getDescription());
+            if (item.getParent() == null) {
+                ps.setNull(4, Types.INTEGER);
+            } else {
+                ps.setInt(4, item.getParent().getId());
+            }
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                itemId = result.getInt(1);
+                item.setId(itemId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the item, " +
+                    item.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return itemId;
+    }
+
+    // return the existence of the customer
+
+    public void fillCustomerData(int customerId, Customer customer) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            customer.setId(customerId);
+            customer.setName(tenant.getDomain());
+            customer.setStartedDate(tenant.getCreatedDate());
+            customer.setEmail(tenant.getEmail());
+            //customer.setAddress(); //we dont have the address
+        }catch (Exception e){
+            String msg = "Failed to fill the data for customer: " +
+                    customer.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    public List<Customer> getAllCustomers() throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            Tenant[] tenants = tenantManager.getAllTenants();
+            if(tenants!=null && tenants.length>0){
+                for(Tenant tenant : tenants){
+                    Customer customer = new Customer();
+                    customer.setId(tenant.getId());
+                    customer.setName(tenant.getDomain());
+                    customer.setStartedDate(tenant.getCreatedDate());
+                    customer.setEmail(tenant.getEmail());
+                    //customer.setAddress(); //no address yet
+                    customers.add(customer);
+                }
+            }
+        } catch (Exception e){
+            String msg = "Failed to get all the customers.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public List<Item> getAllItems() throws BillingException {
+        Map<Integer, Item> items = new HashMap<Integer, Item>();
+        Map<Item, Integer> itemParents = new HashMap<Item, Integer>();
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_ID, BC_NAME, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM";
+            ps = conn.prepareStatement(sql);
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = new Item();
+                int id = result.getInt("BC_ID");
+                item.setId(id);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    itemParents.put(item, parentId);
+                }
+                items.put(id, item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get all the items.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+
+        // before return resolve all the ids for items who have parents
+        for (Map.Entry<Item, Integer> entry : itemParents.entrySet()) {
+            Item item = entry.getKey();
+            int parentId = entry.getValue();
+            Item parentItem = items.get(parentId);
+            item.setParent(parentItem);
+        }
+        List<Item> returnVal = new ArrayList<Item>();
+        returnVal.addAll(items.values());
+        return returnVal;
+    }
+
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if(tenant!=null){
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        }catch(Exception e){
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public Customer getCustomer(int customerId) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        Customer customer = null;
+
+        try{
+            Tenant tenant = tenantManager.getTenant(customerId);
+            if(tenant!=null){
+                customer = new Customer();
+                customer.setId(customerId);
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+            }
+        } catch (Exception e){
+            String msg = "Failed to get customer for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customer;
+    }
+
+    public Item getItem(int itemId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        /*try {
+            conn = DataSourceHolder.getDataSource().getConnection();
+        } catch (SQLException e) {
+            String msg = "Failed to establish data connection";
+            log.error(msg, e);
+        }*/
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_NAME, BC_COST, BC_DESCRIPTION, BC_PARENT_ITEM_ID " +
+                    " FROM BC_ITEM WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, itemId);
+
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                Item item = new Item();
+                item.setId(itemId);
+                String costStr = result.getString("BC_COST");
+                Cash cost = new Cash(costStr);
+                item.setCost(cost);
+                item.setDescription(result.getString("BC_DESCRIPTION"));
+                item.setName(result.getString("BC_NAME"));
+                int parentId = result.getInt("BC_PARENT_ITEM_ID");
+                if (parentId > 0) {
+                    Item parentItem;
+                    if (itemId == parentId) {
+                        parentItem = item;
+                    } else {
+                        parentItem = getItem(parentId);
+                    }
+                    item.setParent(parentItem);
+                }
+                return item;
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the item with item id: " + itemId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+            /*try{
+                if(conn !=null){
+                    conn.close();
+                }
+            }
+            catch (SQLException e){
+                String msg = "Error while closing connection";
+                log.error(msg, e);
+            }*/
+        }
+
+        return null;
+    }
+
+    public void updateSubscription(Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        try {
+            String sql = "UPDATE BC_SUBSCRIPTION SET BC_IS_ACTIVE=?, " +
+                    "BC_ACTIVE_SINCE=? , BC_ACTIVE_UNTIL=?, BC_ITEM_ID=?, BC_TENANT_ID=? " +
+                    "WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+
+            // updating the subscription
+            ps.setInt(1, subscription.isActive() ? 1 : 0);
+            long activeSinceTime = 0;
+            if (subscription.getActiveSince() != null) {
+                activeSinceTime = subscription.getActiveSince().getTime();
+            }
+            ps.setTimestamp(2, new Timestamp(activeSinceTime));
+            long activeUntilTime = 0;
+            if (subscription.getActiveUntil() != null) {
+                activeUntilTime = subscription.getActiveUntil().getTime();
+            }
+            ps.setTimestamp(3, new Timestamp(activeUntilTime));
+            ps.setInt(4, subscription.getItem().getId());
+            ps.setInt(5, subscription.getCustomer().getId());
+            ps.setInt(6, subscription.getId());
+
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Error in updating the subscription: " + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            }
+            catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    public int addSubscription(Subscription subscription, String filter) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int subscriptionId = -1;
+        try {
+            String sql = "INSERT INTO BC_SUBSCRIPTION (BC_FILTER, BC_IS_ACTIVE, " +
+                    "BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, BC_TENANT_ID) " +
+                    "VALUES (?, ?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the subscription
+            ps.setString(1, filter);
+            ps.setInt(2, subscription.isActive() ? 1 : 0);
+            long activeSinceTime = 0;
+            if (subscription.getActiveSince() != null) {
+                activeSinceTime = subscription.getActiveSince().getTime();
+            }else{
+                activeSinceTime = System.currentTimeMillis();
+                subscription.setActiveSince(new Date(activeSinceTime));
+            }
+            ps.setTimestamp(3, new Timestamp(activeSinceTime));
+            long activeUntilTime = 0;
+
+            if (subscription.getActiveUntil() != null) {
+                activeUntilTime = subscription.getActiveUntil().getTime();
+            }
+            else{
+                //When adding to database each user will activate until 2 years 
+                //from the registration date
+                Calendar activeUntilDate = Calendar.getInstance();
+                activeUntilDate.setTimeInMillis(subscription.getActiveSince().getTime());
+                activeUntilDate.add(Calendar.YEAR,2);
+                activeUntilTime = activeUntilDate.getTimeInMillis();
+            }
+
+            ps.setTimestamp(4, new Timestamp(activeUntilTime));
+            ps.setInt(5, getItemIdWithName(filter));
+
+            //setting the customer id: we dont have the customer id in the customer object
+            //which comes with the subscription object. Therefore we have to get it.
+            if(subscription.getCustomer().getId()==0){
+                int customerId = CustomerUtils.getCustomerId(subscription.getCustomer().getName());
+                if(customerId==0){
+                    throw new BillingException("No customer found with domain: " +
+                            subscription.getCustomer().getName());
+                }
+                ps.setInt(6, customerId);
+            }else{
+                ps.setInt(6, subscription.getCustomer().getId());
+            }
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                subscriptionId = result.getInt(1);
+                subscription.setId(subscriptionId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the subscription.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptionId;
+    }
+
+    public void deleteBillingData(int tenantId) throws Exception {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement deleteSubItemPs = null;
+        PreparedStatement deleteInvoiceSubsPs = null;
+        PreparedStatement deletePaymentSubsPs = null;
+        PreparedStatement deletePaymentPs = null;
+        PreparedStatement deleteInvoicePs = null;
+        PreparedStatement deleteSubscriptionPs = null;
+        try {
+            conn.setAutoCommit(false);
+            String deleteSubItemRecordsSql = "DELETE FROM BC_INVOICE_SUBSCRIPTION_ITEM WHERE BC_INVOICE_SUBSCRIPTION_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?));";
+            deleteSubItemPs = conn.prepareStatement(deleteSubItemRecordsSql);
+            deleteSubItemPs.setInt(1, tenantId);
+            deleteSubItemPs.executeUpdate();
+
+            String deleteInvoiceSubsRecordsSql = "DELETE FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID IN " +
+                                                 "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?) OR " +
+                                                 "BC_SUBSCRIPTION_ID IN (SELECT BC_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?)";
+            deleteInvoiceSubsPs = conn.prepareStatement(deleteInvoiceSubsRecordsSql);
+            deleteInvoiceSubsPs.setInt(1, tenantId);
+            deleteInvoiceSubsPs.setInt(2, tenantId);
+            deleteInvoiceSubsPs.executeUpdate();
+
+            String deletePaymentSubsRecordsSql = "DELETE FROM BC_PAYMENT_SUBSCRIPTION WHERE BC_PAYMENT_ID IN " +
+                                                 "(SELECT BC_ID FROM BC_PAYMENT WHERE BC_TENANT_ID = ?) OR " +
+                                                 "BC_SUBSCRIPTION_ID IN (SELECT BC_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?)";
+            deletePaymentSubsPs = conn.prepareStatement(deletePaymentSubsRecordsSql);
+            deletePaymentSubsPs.setInt(1, tenantId);
+            deletePaymentSubsPs.setInt(2, tenantId);
+            deletePaymentSubsPs.executeUpdate();
+
+            String deletePaymentRecordsSql = "DELETE FROM BC_PAYMENT WHERE BC_INVOICE_ID IN " +
+                                             "(SELECT BC_ID FROM BC_INVOICE WHERE BC_TENANT_ID = ?)";
+            deletePaymentPs = conn.prepareStatement(deletePaymentRecordsSql);
+            deletePaymentPs.setInt(1, tenantId);
+            deletePaymentPs.executeUpdate();
+
+            String deleteInvoiceRecordsSql = "DELETE FROM BC_INVOICE WHERE BC_TENANT_ID = ?";
+            deleteInvoicePs = conn.prepareStatement(deleteInvoiceRecordsSql);
+            deleteInvoicePs.setInt(1, tenantId);
+            deleteInvoicePs.executeUpdate();
+
+            String deleteSubscriptionRecordsSql = "DELETE FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID = ?";
+            deleteSubscriptionPs = conn.prepareStatement(deleteSubscriptionRecordsSql);
+            deleteSubscriptionPs.setInt(1, tenantId);
+            deleteSubscriptionPs.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Failed to delete billing information for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (deleteSubItemPs != null) {
+                    deleteSubItemPs.close();
+                }
+                if (deleteInvoiceSubsPs != null) {
+                    deleteInvoiceSubsPs.close();
+                }
+                if (deletePaymentSubsPs != null) {
+                    deletePaymentSubsPs.close();
+                }
+                if (deletePaymentPs != null) {
+                    deletePaymentPs.close();
+                }
+                if (deleteInvoicePs != null) {
+                    deleteInvoicePs.close();
+                }
+                if (deleteSubscriptionPs != null) {
+                    deleteSubscriptionPs.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    /**
+     * Get all the active subscriptions for a particular filter.
+     * Customers and Items are just dummy objects that only have a valid id.
+     *
+     * @param filter the name of the filter (This is not used.Will be removed from
+     *               the signature in the future trunk).
+     * @return the array of the subscriptions.
+     * @throws BillingException throws if there is an error.
+     */
+    public List<Subscription> getFilteredActiveSubscriptions(String filter) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        Date lastInvoiceDate = getLastInvoiceDate();
+        try {
+            String sql = "";
+            //if the last invoice date is null, that means there has been no bill generation yet.
+            //so we have to consider all the subscriptions
+            if(lastInvoiceDate==null){
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_FILTER, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION";
+                ps = conn.prepareStatement(sql);
+            }else{
+                //this means there has been a previous bill generation. Now we only consider
+                //1. Active subscriptions
+                //2. Inactive subscriptions which ended after the last invoice date
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_FILTER, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE (BC_IS_ACTIVE=?) OR " +
+                        "(BC_IS_ACTIVE=? AND BC_ACTIVE_UNTIL>=?)";
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1,1);
+                ps.setInt(2,0);
+                ps.setTimestamp(3, new Timestamp(lastInvoiceDate.getTime()));
+            }
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActive(result.getInt("BC_IS_ACTIVE")==1);
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+                subscription.setActiveSince(new Date(
+                        result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+
+                // filling with dummy customer
+                Customer customer = new Customer();
+                customer.setId(customerId);
+                subscription.setCustomer(customer);
+                //subscription.setActive(true);
+                subscriptions.add(subscription);
+                // we will fill the payment details too
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscriptions.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    public Invoice getLastInvoice(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Invoice invoice = null;
+        try {
+            String sql = "SELECT BC_ID, BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_COST, BC_TOTAL_PAYMENTS "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=? AND BC_DATE=(SELECT MAX(BC_DATE) "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=?) ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            ps.setInt(2, customer.getId());
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setCustomer(customer);
+                invoice.setDate(result.getTimestamp("BC_DATE"));
+                invoice.setStartDate(result.getTimestamp("BC_START_DATE"));
+                invoice.setEndDate(result.getTimestamp("BC_END_DATE"));
+                String boughtForwardStr = result.getString("BC_BOUGHT_FORWARD");
+                invoice.setBoughtForward(new Cash(boughtForwardStr));
+                String carriedForwardStr = result.getString("BC_CARRIED_FORWARD");
+                invoice.setCarriedForward(new Cash(carriedForwardStr));
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                invoice.setTotalCost(new Cash(totalCostStr));
+                String totalPaymentsStr = result.getString("BC_TOTAL_PAYMENTS");
+                invoice.setTotalPayment(new Cash(totalPaymentsStr));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice for customer: " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoice;
+    }
+
+    public List<Invoice> getAllInvoices(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        List<Invoice> invoices = new ArrayList<Invoice>();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        try {
+            String sql = "SELECT BC_ID, BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_COST, BC_TOTAL_PAYMENTS "
+                    + "FROM BC_INVOICE WHERE BC_TENANT_ID=? ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Invoice invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setCustomer(customer);
+                invoice.setDate(result.getTimestamp("BC_DATE"));
+                invoice.setStartDate(result.getTimestamp("BC_START_DATE"));
+                invoice.setEndDate(result.getTimestamp("BC_END_DATE"));
+                String boughtForwardStr = result.getString("BC_BOUGHT_FORWARD");
+                invoice.setBoughtForward(new Cash(boughtForwardStr));
+                String carriedForwardStr = result.getString("BC_CARRIED_FORWARD");
+                invoice.setCarriedForward(new Cash(carriedForwardStr));
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                invoice.setTotalCost(new Cash(totalCostStr));
+                String totalPaymentsStr = result.getString("BC_TOTAL_PAYMENTS");
+                invoice.setTotalPayment(new Cash(totalPaymentsStr));
+
+                invoices.add(invoice);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get invoices for customer: " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoices;
+    }
+
+    public void fillUnbilledPayments(Subscription subscription,
+                                     Map<Integer, Payment> payments,
+                                     Invoice invoice) throws BillingException {
+
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet results = null;
+        java.sql.Timestamp startDate= new Timestamp(invoice.getStartDate().getTime());
+        java.sql.Timestamp endDate= new Timestamp(invoice.getEndDate().getTime());
+        try {
+            /*String sql = "SELECT P.BC_ID, P.BC_DATE, P.BC_AMOUNT, P.BC_DESCRIPTION " +
+                    " FROM BC_PAYMENT P, BC_PAYMENT_SUBSCRIPTION PS " +
+                    "WHERE PS.BC_SUBSCRIPTION_ID=? AND PS.BC_PAYMENT_ID=P.BC_ID " +
+                    "AND P.BC_INVOICE_ID IS NULL";
+            */
+            String sql = "SELECT P.BC_ID, P.BC_DATE, P.BC_AMOUNT, P.BC_DESCRIPTION " +
+                    " FROM BC_PAYMENT P, BC_PAYMENT_SUBSCRIPTION PS " +
+                    "WHERE PS.BC_SUBSCRIPTION_ID=? AND PS.BC_PAYMENT_ID=P.BC_ID " +
+                    "AND P.BC_DATE>=? AND P.BC_DATE<?";
+
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, subscription.getId());
+            Calendar cal = Calendar.getInstance();
+            cal.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
+            ps.setTimestamp(2, startDate, cal);
+            ps.setTimestamp(3, endDate, cal);
+            results = ps.executeQuery();
+            while (results.next()) {
+                Payment payment;
+                int paymentId = results.getInt("BC_ID");
+                if (payments.get(paymentId) != null) {
+                    payment = payments.get(paymentId);
+                } else {
+                    payment = new Payment();
+                    payment.setId(paymentId);
+                    payment.setDate(results.getTimestamp("BC_DATE"));
+                    payment.setDescription(results.getString("BC_DESCRIPTION"));
+                    String amount = results.getString("BC_AMOUNT");
+                    if (amount == null) {
+                        amount = "0";
+                    }
+                    Cash paymentCash = new Cash(amount);
+                    payment.setAmount(paymentCash);
+                    payments.put(paymentId, payment);
+                }
+                payment.addSubscription(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to fill the payment for subscription: "
+                    + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (results != null) {
+                    results.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+    }
+
+    public void associatePaymentWithInvoice(Payment payment,
+                                            Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        try {
+            String sql = "UPDATE BC_PAYMENT SET BC_INVOICE_ID=? WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+
+            // inserting the data values
+            ps.setInt(1, invoice.getId());
+            ps.setInt(2, payment.getId());
+
+            ps.executeUpdate();
+        } catch (SQLException e) {
+            String msg = "Error in associating invoice: " + invoice.getId() +
+                    " with payment: " + payment.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+        }
+    }
+
+    public int addInvoiceSubscription(Invoice invoice,
+                                      Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceSubscriptionId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_INVOICE_SUBSCRIPTION (BC_INVOICE_ID, BC_SUBSCRIPTION_ID) "
+                    + "VALUES (?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoice.getId());
+            ps.setInt(2, subscription.getId());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceSubscriptionId = result.getInt(1);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice subscription, invoice id: " +
+                    invoice.getId() + ", subscription id: " + subscription.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceSubscriptionId;
+    }
+
+    public int addInvoiceSubscriptionItem(Item item,
+                                          int invoiceSubscriptionId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceSubscriptionItemId = INVALID;
+        try {
+            String sql = "INSERT INTO BC_INVOICE_SUBSCRIPTION_ITEM (BC_INVOICE_SUBSCRIPTION_ID, " +
+                    "BC_ITEM_ID, BC_COST, BC_DESCRIPTION) VALUES (?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data values
+            ps.setInt(1, invoiceSubscriptionId);
+            ps.setInt(2, item.getId());
+            if(item.getCost()!=null){
+                ps.setString(3, item.getCost().serializeToString());
+            }else{
+                ps.setString(3, new Cash("$0").serializeToString());
+            }
+            ps.setString(4, item.getDescription());
+
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                invoiceSubscriptionItemId = result.getInt(1);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the invoice subscription item, item id: " +
+                    item.getId() + ", invoice subscription id: " + invoiceSubscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoiceSubscriptionItemId;
+    }
+
+
+    public int addPayment(Payment payment) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int paymentId = INVALID;
+        int invoiceId = INVALID;
+        int customerId = INVALID;
+        if (payment.getInvoice() != null) {
+            invoiceId = payment.getInvoice().getId();
+        }
+        if(invoiceId!=INVALID){
+            customerId = getCustomerIdFromInvoiceId(invoiceId);
+        }
+        try {
+            String sql = "INSERT INTO BC_PAYMENT (BC_DATE, BC_AMOUNT, " +
+                    "BC_DESCRIPTION, BC_INVOICE_ID, BC_TENANT_ID) " +
+                    "VALUES (?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data
+            long paymentTime = System.currentTimeMillis();
+            //there was a problem of time shown as 00:00:00 when getting the date sent
+            //from frontend. Therefore, to get rid of it, I am creating the timestamp
+            //by getting the current time. This may be a few seconds different from the
+            //time sent from frontend
+            /*if (payment.getDate() != null) {
+                paymentTime = payment.getDate().getTime();
+            }*/
+            ps.setTimestamp(1, new Timestamp(paymentTime));
+            ps.setString(2, payment.getAmount().serializeToString());
+            ps.setString(3, payment.getDescription());
+            if (invoiceId == INVALID) {
+                ps.setNull(4, Types.INTEGER);
+            } else {
+                ps.setInt(4, invoiceId);
+            }
+            if(customerId == INVALID){
+                ps.setNull(5, Types.INTEGER);
+            }else{
+                ps.setInt(5, customerId);
+            }
+
+            ps.executeUpdate();
+
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                paymentId = result.getInt(1);
+                payment.setId(paymentId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the payment, payment id: " + paymentId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        // adn then insert the subscriptions
+        addPaymentSubscriptionsEntry(payment);
+        return paymentId;
+    }
+
+    public void addPaymentSubscriptionsEntry(Payment payment) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        List<Subscription> subscriptions = payment.getSubscriptions();
+        if (subscriptions == null) {
+            return;
+        }
+        try {
+            for (Subscription subscription : subscriptions) {
+                String sql = "INSERT INTO BC_PAYMENT_SUBSCRIPTION ( " +
+                        "BC_PAYMENT_ID, BC_SUBSCRIPTION_ID) " +
+                        "VALUES (?, ?)";
+                ps = conn.prepareStatement(sql);
+
+                // inserting the data
+                ps.setInt(1, payment.getId());
+                ps.setInt(2, subscription.getId());
+
+                ps.executeUpdate();
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the payment subscriptions, " +
+                    "payment id: " + payment.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+        }
+    }
+
+    public int addRegistrationPayment(Payment payment, String usagePlan) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int paymentId = INVALID;
+        String tenantDomain = payment.getDescription().split(" ")[0];
+        try {
+            int tenantId = Util.getRealmService().getTenantManager().getTenantId(tenantDomain);
+            String sql = "INSERT INTO BC_REGISTRATION_PAYMENT (BC_DATE, BC_AMOUNT, " +
+                         "BC_DESCRIPTION, BC_USAGE_PLAN, BC_TENANT_ID) " +
+                         "VALUES (?, ?, ?, ?, ?)";
+            ps = conn.prepareStatement(sql, new String[]{"BC_ID"});
+
+            // inserting the data
+            long paymentTime = System.currentTimeMillis();
+            ps.setTimestamp(1, new Timestamp(paymentTime));
+            ps.setString(2, payment.getAmount().serializeToString());
+            ps.setString(3, payment.getDescription().split(" ")[1]);
+            ps.setString(4, usagePlan);
+            ps.setInt(5, tenantId);
+            ps.executeUpdate();
+            result = ps.getGeneratedKeys();
+            if (result.next()) {
+                paymentId = result.getInt(1);
+                payment.setId(paymentId);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to insert the registration payment record, id: " + paymentId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } catch (UserStoreException e) {
+            String msg = "Failed to get tenant id of registration payment for: " + tenantDomain + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return paymentId;
+    }
+
+    public List<Subscription> getFilteredActiveSubscriptionsForCustomer(String filter, Customer customer)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        Date lastInvoiceDate = getLastInvoiceDate();
+        try {
+            String sql="";
+            if(lastInvoiceDate==null){
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE " +
+                    "BC_TENANT_ID=? ORDER BY BC_ACTIVE_UNTIL DESC"; //not sure whether this
+                                                                                           //ORDER BY is necessary
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1, customer.getId());
+            }else{
+                sql = "SELECT BC_ID, BC_IS_ACTIVE, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID=? AND " +
+                        "((BC_IS_ACTIVE=? ) OR (BC_IS_ACTIVE=? AND BC_ACTIVE_UNTIL>=?)) ORDER BY BC_ACTIVE_UNTIL DESC";
+
+                ps = conn.prepareStatement(sql);
+                ps.setInt(1, customer.getId());
+                ps.setInt(2, 1);             //active=true
+                ps.setInt(3, 0);             //active=false
+                ps.setTimestamp(4, new Timestamp(lastInvoiceDate.getTime()));
+            }
+
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActive(result.getInt("BC_IS_ACTIVE")==1);
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                subscription.setCustomer(customer);
+                //subscription.setActive(true);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscriptions for " +
+                    "customer = " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    /**
+     * this doesn't load the subscriptions
+     *
+     * @param customer
+     * @return
+     * @throws BillingException
+     */
+    public List<Invoice> getInvoices(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Invoice> invoices = new ArrayList<Invoice>();
+        try {
+            String sql = "SELECT BC_ID, BC_DATE, BC_START_DATE, BC_END_DATE, BC_BOUGHT_FORWARD, "
+                    + "BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, BC_TOTAL_COST FROM BC_INVOICE "
+                    + "WHERE BC_TENANT_ID=? ORDER BY BC_DATE DESC";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Invoice invoice = new Invoice();
+                invoice.setId(result.getInt("BC_ID"));
+                invoice.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+                invoice.setStartDate(new Date(result.getTimestamp("BC_START_DATE").getTime()));
+                invoice.setEndDate(new Date(result.getTimestamp("BC_END_DATE").getTime()));
+                invoice.setCustomer(customer);
+
+                String bfStr = result.getString("BC_BOUGHT_FORWARD");
+                if (bfStr == null) {
+                    bfStr = "$0";
+                }
+                invoice.setBoughtForward(new Cash(bfStr));
+
+                String cfStr = result.getString("BC_CARRIED_FORWARD");
+                if (cfStr == null) {
+                    cfStr = "$0";
+                }
+                invoice.setCarriedForward(new Cash(cfStr));
+
+                String totalPayStr = result.getString("BC_TOTAL_PAYMENTS");
+                if (totalPayStr == null) {
+                    totalPayStr = "$0";
+                }
+                invoice.setTotalPayment(new Cash(totalPayStr));
+
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                if (totalCostStr == null) {
+                    totalCostStr = "$0";
+                }
+                invoice.setTotalCost(new Cash(totalCostStr));
+                invoices.add(invoice);
+            }
+        } catch (SQLException e) {
+            String msg =
+                    "Failed to get the invoice for: " + "customer = " + customer.getName() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg =
+                        RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                                ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoices;
+    }
+
+    /**
+     * this load the subscriptions and payments associated
+     *
+     * @param invoiceId
+     * @return
+     * @throws BillingException
+     */
+    public Invoice getInvoice(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Invoice invoice = null;
+        try {
+            String sql = "SELECT BC_TENANT_ID, BC_DATE, BC_START_DATE, BC_END_DATE, "
+                    + "BC_BOUGHT_FORWARD, BC_CARRIED_FORWARD, BC_TOTAL_PAYMENTS, BC_TOTAL_COST "
+                    + "FROM BC_INVOICE WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                invoice = new Invoice();
+
+                invoice.setEndDate(new Date(result.getTimestamp("BC_END_DATE").getTime()));
+                invoice.setId(invoiceId);
+                invoice.setStartDate(new Date(result.getTimestamp("BC_START_DATE").getTime()));
+                invoice.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+
+                String bfStr = result.getString("BC_BOUGHT_FORWARD");
+                if (bfStr == null) {
+                    bfStr = "$0";
+                }
+                invoice.setBoughtForward(new Cash(bfStr));
+
+                String cfStr = result.getString("BC_CARRIED_FORWARD");
+                if (cfStr == null) {
+                    cfStr = "$0";
+                }
+                invoice.setCarriedForward(new Cash(cfStr));
+
+                String totalPayStr = result.getString("BC_TOTAL_PAYMENTS");
+                if (totalPayStr == null) {
+                    totalPayStr = "$0";
+                }
+                invoice.setTotalPayment(new Cash(totalPayStr));
+
+                String totalCostStr = result.getString("BC_TOTAL_COST");
+                if (totalCostStr == null) {
+                    totalCostStr = "$0";
+                }
+                invoice.setTotalCost(new Cash(totalCostStr));
+
+                int customerId = result.getInt("BC_TENANT_ID");
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                invoice.setCustomer(customer);
+
+                fillInvoiceSubscriptions(invoice);
+                fillInvoicePayments(invoice);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice for: " + "invoice id = " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                        ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return invoice;
+    }
+
+    private void fillInvoicePayments(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int customerId = INVALID;
+        //int invoiceId = invoice.getId();
+        if(invoice.getCustomer()==null){
+            return;
+        }else{
+            customerId = invoice.getCustomer().getId();
+        }
+        java.sql.Timestamp startDate = new Timestamp(invoice.getStartDate().getTime());
+        java.sql.Timestamp endDate = new Timestamp(invoice.getEndDate().getTime());
+        List<Payment> payments = new ArrayList<Payment>();
+
+        try {
+            /*String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION "
+                    + "FROM BC_PAYMENT WHERE BC_INVOICE_ID=?";
+            */
+            String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION "
+                    + "FROM BC_PAYMENT WHERE BC_TENANT_ID=? AND BC_DATE>=? AND BC_DATE<?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customerId);
+            Calendar cal = Calendar.getInstance();
+            cal.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
+            ps.setTimestamp(2, startDate, cal);
+            ps.setTimestamp(3, endDate, cal);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Payment payment = new Payment();
+                payment.setId(result.getInt("BC_ID"));
+                String cashPayment = result.getString("BC_AMOUNT");
+                payment.setAmount(new Cash(cashPayment));
+                payment.setDate(result.getTimestamp("BC_DATE"));
+                payment.setDescription(result.getString("BC_DESCRIPTION"));
+
+                payments.add(payment);
+            }
+        } catch (SQLException e) {
+            String msg =
+                    "Failed to get the invoice payments for: " + "invoice id = " + invoice.getId() + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        invoice.setPayments(payments);
+    }
+
+    private void fillInvoiceSubscriptions(Invoice invoice) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int invoiceId = invoice.getId();
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+
+        try {
+            String sql = "SELECT BC_ID, BC_SUBSCRIPTION_ID "
+                    + "FROM BC_INVOICE_SUBSCRIPTION WHERE BC_INVOICE_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                int invoiceSubscriptionId = result.getInt("BC_ID");
+                int subscriptionId = result.getInt("BC_SUBSCRIPTION_ID");
+                Subscription subscription = getSubscription(subscriptionId);
+                subscription.setInvoiceSubscriptionId(invoiceSubscriptionId);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice subscriptions for: " + "invoice id = "
+                    + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR +
+                        ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        invoice.setSubscriptions(subscriptions);
+    }
+
+    public Subscription getSubscription(int subscriptionId)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Subscription subscription = null;
+        try {
+            String sql = "SELECT BC_ID, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID, BC_IS_ACTIVE, BC_FILTER FROM BC_SUBSCRIPTION WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, subscriptionId);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                subscription = new Subscription();
+                subscription.setId(subscriptionId);
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+                // filling with dummy item
+                Item item = getItem(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                subscription.setCustomer(customer);
+                int isActive = result.getInt("BC_IS_ACTIVE");
+                subscription.setActive(isActive == 1);
+                //subscription plan name
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscription for id: " + subscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscription;
+    }
+
+        public Subscription getActiveSubscriptionOfCustomer(int customerId)
+            throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Subscription subscription = null;
+        try {
+            String sql = "SELECT BC_ID, BC_ACTIVE_SINCE, BC_ACTIVE_UNTIL, BC_ITEM_ID, " +
+                    "BC_TENANT_ID, BC_IS_ACTIVE, BC_FILTER FROM BC_SUBSCRIPTION WHERE BC_TENANT_ID=? AND BC_IS_ACTIVE=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customerId);
+            ps.setInt(2,1);
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setActiveSince(
+                        new Date(result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                // filling with dummy item
+                Item item = getItem(itemId);
+                subscription.setItem(item);
+                // filling with dummy customer
+                //Customer customer = getCustomer(customerId);
+                Customer customer = CustomerUtils.getCustomer(customerId);
+                subscription.setCustomer(customer);
+                int isActive = result.getInt("BC_IS_ACTIVE");
+                subscription.setActive(isActive == 1);
+                //subscription plan name
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the active subscription for customer id: " + customerId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscription;
+    }
+
+    public List<Item> getBilledItems(Subscription subscription) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+
+        int invoiceSubscriptionId = subscription.getInvoiceSubscriptionId();
+        if (invoiceSubscriptionId == INVALID) {
+            String msg = "Not a invoiced subscription, subscription id: "
+                    + subscription.getId() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+
+        List<Item> items = new ArrayList<Item>();
+        try {
+            String sql = "SELECT BC_ITEM_ID, BC_COST, BC_DESCRIPTION " +
+                    "FROM BC_INVOICE_SUBSCRIPTION_ITEM WHERE BC_INVOICE_SUBSCRIPTION_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceSubscriptionId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Item item = getItem(result.getInt("BC_ITEM_ID"));
+                String cost = result.getString("BC_COST");
+                String description = result.getString("BC_DESCRIPTION");
+                if (cost != null) {
+                    item.setCost(new Cash(cost));
+                }
+                if(description!=null && !"".equals(description)){
+                    item.setDescription(description);
+                }
+                items.add(item);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoiced subscription items for " +
+                    "invoice subscription id: " + invoiceSubscriptionId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR
+                        + ex.getMessage();
+                log.error(msg, ex);
+                throw new BillingException(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return items;
+    }
+
+    public List<Subscription> getInvoiceSubscriptions(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+
+        try {
+            String sql = "SELECT S.BC_ID, S.BC_FILTER, S.BC_IS_ACTIVE, S.BC_ACTIVE_SINCE, S.BC_ACTIVE_UNTIL, S.BC_ITEM_ID, S.BC_TENANT_ID FROM " +
+                        "BC_SUBSCRIPTION S, BC_INVOICE_SUBSCRIPTION BIS " +
+                        "WHERE S.BC_ID=BIS.BC_SUBSCRIPTION_ID AND BIS.BC_INVOICE_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                Subscription subscription = new Subscription();
+                subscription.setId(result.getInt("BC_ID"));
+                subscription.setSubscriptionPlan(result.getString("BC_FILTER"));
+                subscription.setActiveSince(new Date(
+                        result.getTimestamp("BC_ACTIVE_SINCE").getTime()));
+                subscription.setActiveUntil(
+                        new Date(result.getTimestamp("BC_ACTIVE_UNTIL").getTime()));
+                int itemId = result.getInt("BC_ITEM_ID");
+                int customerId = result.getInt("BC_TENANT_ID");
+                boolean isActive = result.getBoolean("BC_IS_ACTIVE");
+
+                // filling with dummy item
+                Item item = new Item();
+                item.setId(itemId);
+                subscription.setItem(item);
+
+                // filling with dummy customer
+                Customer customer = new Customer();
+                customer.setId(customerId);
+                subscription.setCustomer(customer);
+                subscription.setActive(isActive);
+                subscriptions.add(subscription);
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the invoice subscriptions for invoice: " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return subscriptions;
+    }
+
+    private int getCustomerIdFromInvoiceId(int invoiceId) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        int customerId = INVALID;
+
+        try {
+            String sql = "SELECT BC_TENANT_ID FROM BC_INVOICE WHERE BC_ID=?";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, invoiceId);
+            result = ps.executeQuery();
+
+            while (result.next()) {
+                customerId = result.getInt("BC_TENANT_ID");
+            }
+        } catch (SQLException e) {
+            String msg = "Failed to get the customer Id for invoice: " + invoiceId + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+
+        } finally {
+            try {
+                if (ps != null) {
+                    ps.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+
+            try {
+                if (result != null) {
+                    result.close();
+                }
+            } catch (SQLException ex) {
+                String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
+                log.error(msg, ex);
+            }
+        }
+        return customerId;
+    }
+
+    public Payment getLastPayment(Customer customer) throws BillingException {
+        Connection conn = Transaction.getConnection();
+        PreparedStatement ps = null;
+        ResultSet result = null;
+        Payment payment = null;
+        try {
+            String sql = "SELECT BC_ID, BC_DATE, BC_AMOUNT, BC_DESCRIPTION FROM BC_PAYMENT WHERE BC_TENANT_ID=?" +
+                        " AND BC_DATE=(SELECT MAX(BC_DATE) FROM BC_PAYMENT WHERE BC_TENANT_ID=?) ";
+            ps = conn.prepareStatement(sql);
+            ps.setInt(1, customer.getId());
+            ps.setInt(2, customer.getId());
+            result = ps.executeQuery();
+
+            if (result.next()) {
+                payment = new Payment();
+                payment.setAmount(new Cash(result.getString("BC_AMOUNT")));
+                payment.setDate(new Date(result.getTimestamp("BC_DATE").getTime()));
+                payment.setDescription(result.getString("BC_DESCRIPTION"));
+            }
+        } catch (SQLException e)

<TRUNCATED>

[47/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
new file mode 100644
index 0000000..5696643
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskInitializer.java
@@ -0,0 +1,47 @@
+/**
+ *  Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.synapse.task.TaskConstants;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
+
+public class AutoscalerTaskInitializer extends AbstractAxis2ConfigurationContextObserver {
+
+    public static final java.lang.String CARBON_TASK_SCHEDULER = "CARBON_TASK_SCHEDULER";
+    public static final java.lang.String CARBON_TASK_REPOSITORY = "CARBON_TASK_REPOSITORY";
+
+    public void createdConfigurationContext(ConfigurationContext configContext) {
+        TaskScheduler scheduler = (TaskScheduler)configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER);
+        if (scheduler == null) {
+            scheduler = new TaskScheduler(TaskConstants.TASK_SCHEDULER);
+            scheduler.init(null);
+            configContext.setProperty(AutoscalerTaskInitializer.CARBON_TASK_SCHEDULER, scheduler);
+        } else if(!scheduler.isInitialized()) {
+            scheduler.init(null);
+        }
+
+        if (configContext.getProperty(AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY) == null) {
+            TaskDescriptionRepository repository = new TaskDescriptionRepository();
+            configContext.setProperty(
+                    AutoscalerTaskInitializer.CARBON_TASK_REPOSITORY, repository);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
new file mode 100644
index 0000000..b1650d6
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalerTaskMgmtAdminService.java
@@ -0,0 +1,345 @@
+/**
+ * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMFactory;
+import org.apache.axiom.om.OMNamespace;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionFactory;
+import org.apache.synapse.task.TaskDescriptionSerializer;
+import org.apache.synapse.task.service.TaskManagementService;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.task.TaskManagementException;
+import org.wso2.carbon.task.TaskManager;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import java.util.*;
+
+public class AutoscalerTaskMgmtAdminService extends AbstractAdmin implements TaskManagementService{
+
+    private static final Log log = LogFactory.getLog(AutoscalerTaskMgmtAdminService.class);
+
+    private TaskSchedulingManager schedulingManager;
+
+
+    private static final String TASK_EXTENSION_NS =
+            "http://www.wso2.org/tasks";
+
+    private static final OMFactory FACTORY = OMAbstractFactory.getOMFactory();
+
+    private static final OMNamespace TASK_OM_NAMESPACE = FACTORY.createOMNamespace(
+            TASK_EXTENSION_NS, "task");
+
+    public AutoscalerTaskMgmtAdminService(){}
+    
+    public AutoscalerTaskMgmtAdminService(ConfigurationContext configurationContext) {
+        this.schedulingManager = TaskSchedulingManager.getInstance();
+        this.configurationContext = configurationContext;
+    }
+
+    public void shutdown() {
+        schedulingManager.shutDown(getConfigContext());
+    }
+
+    public void addTaskDescription(TaskDescription taskDescription, Map<String, Object> resources)
+            throws Exception {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task " + taskDescription.getName() + "..";
+            log.error(msg, e);  
+            throw e;
+        }
+    }
+
+    /**
+     * Passing the Task Description to scheduling manager to actually add it to the Task
+     * Description Repository.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void addTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding the Task " + taskDescription.getName());
+        }
+        try {
+            Map<String, Object> resources = new HashMap<String, Object>();
+            schedulingManager.scheduleTask(taskDescription, resources, getConfigContext());
+        } catch (Exception e) {
+            String msg = "Cannot add the task";
+            log.error(msg, e);
+        }
+    }
+
+    public void addTaskDescriptionInAnOmElement(String taskElementString) throws
+                                                                          TaskManagementException,
+                                                                          XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Add TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        TaskDescription taskDescription = validateAndCreate(taskElement);
+
+        try {
+            addTaskDescription(taskDescription);
+        } catch (Exception e) {
+            try {
+                getTaskManager().deleteTaskDescription(taskDescription.getName(),
+                        taskDescription.getGroup());
+            } catch (Exception ignored) {
+            }
+            handleException("Error creating a task : " + e.getMessage(), e);
+        }
+    }
+
+
+
+    public void deleteTaskDescription(TaskDescription taskDescription) {
+        String taskName = taskDescription.getName();
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Indicating Task Scheduling manager to delete the task with the given task Name.
+     *
+     * @param taskName taskName
+     */
+    public void deleteTaskDescription(String taskName) {
+        if (log.isDebugEnabled()) {
+            log.debug("Deleting the task " + taskName);
+        }
+        try {
+            TaskDescription taskDescription = new TaskDescription();
+            taskDescription.setName(taskName);
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+        } catch (Exception e) {
+            log.error("Cannot delete the task " + taskName, e);
+        }
+    }
+
+    /**
+     * Notifying the Task Scheduling Manager to delete the previous Task Description from the
+     * Task Description Repository and add the edited task.
+     *
+     * @param taskDescription TaskDescription
+     */
+    public void editTaskDescription(TaskDescription taskDescription) {
+        if (log.isDebugEnabled()) {
+            log.debug("Editing the task " + taskDescription.getName());
+        }
+        if (schedulingManager.isContains(taskDescription.getName(), getConfigContext())) {
+            schedulingManager.deleteTaskDescription(taskDescription, getConfigContext());
+            schedulingManager.scheduleTask(taskDescription, null, getConfigContext());
+        } else {
+            log.error("Task " + taskDescription.getName() + "does not exist");
+        }
+    }
+
+    public void editTaskDescriptionInOmElement(
+            String taskElementString) throws TaskManagementException, XMLStreamException {
+        OMElement taskElement = AXIOMUtil.stringToOM(taskElementString);
+        if (log.isDebugEnabled()) {
+            log.debug("Edit TaskDescription - Get a Task configuration  :" + taskElement);
+        }
+        try {
+            editTaskDescription(validateAndCreate(taskElement));
+        } catch (Exception e) {
+            String msg = "Error editing Task";
+            throw new TaskManagementException(msg, e);
+        }
+    }
+
+    /**
+     * Returns the list of Task Descriptions that have been already added to the Task Description
+     * Repository.
+     *
+     * @return A list of Task Descriptions
+     */
+    public List<TaskDescription> getAllTaskDescriptions() {
+        List<TaskDescription> taskDescriptions = new ArrayList<TaskDescription>();
+        Iterator<TaskDescription> iterator = schedulingManager.getAllTaskDescriptions(
+                getConfigContext());
+
+        while (iterator.hasNext()) {
+            TaskDescription taskDescription = iterator.next();
+            if (taskDescription != null) {
+                taskDescriptions.add(taskDescription);
+            }
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("All available Task based Scheduled Functions " + taskDescriptions);
+        }
+        return taskDescriptions;
+    }
+
+    public String getAllTaskDescriptionsInAnOMElement() throws AxisFault {
+        OMElement rootElement =
+                OMAbstractFactory.getOMFactory().createOMElement(new QName(TASK_EXTENSION_NS,
+                        "taskExtension", "task"));
+        try {
+            List<TaskDescription> descriptions = getAllTaskDescriptions();
+            for (TaskDescription taskDescription : descriptions) {
+                if (taskDescription != null) {
+                    OMElement taskElement =
+                            TaskDescriptionSerializer.serializeTaskDescription(TASK_OM_NAMESPACE,
+                                                                               taskDescription);
+                    validateTaskElement(taskElement);
+                    rootElement.addChild(taskElement);
+                }
+            }
+        } catch (TaskManagementException e) {
+            String msg = "Error loading all tasks";
+            log.error(msg, e);
+            throw new AxisFault(msg, e);
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Returning all TaskDescriptions as  :" + rootElement);
+        }
+        return rootElement.toString();
+    }
+
+    /**
+     * Returns the names of job groups that are being executed.
+     *
+     * @return An array of strings
+     */
+    public String[] getAllJobGroups() {
+        List<String> strings = getTaskManager().getAllJobGroups();
+        return strings.toArray(new String[strings.size()]);
+    }
+
+    /**
+     * Returns the TaskDescription associates with a particular task name
+     *
+     * @param taskName Task Name
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(String taskName) {
+        return schedulingManager.getTaskDescription(taskName, getConfigContext());
+    }
+
+    public boolean isContains(String taskName) {
+        return schedulingManager.isContains(taskName, getConfigContext());
+    }
+
+    /**
+     * @param taskClass taskClass
+     * @return list of strings containing properties of the task class
+     */
+    public List<String> getPropertyNames(String taskClass) {
+        return null;
+    }
+
+    /**
+     * Returns the TaskManager instance currently being used
+     *
+     * @return TaskManager
+     */
+    private synchronized TaskManager getTaskManager() {
+        return (TaskManager) getConfigContext().getProperty(
+                TaskManager.CARBON_TASK_MANAGER);
+    }
+
+    /**
+     * Validates the OMElement which has a particular TaskDescription
+     * serialized into it.
+     *
+     * @param taskElement taskElement
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskElement(
+            OMElement taskElement) throws TaskManagementException {
+        if (taskElement == null) {
+            handleException("Task Description OMElement can not be found.");
+        }
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg) throws TaskManagementException {
+        log.error(msg);
+        throw new TaskManagementException(msg);
+    }
+
+    /**
+     * Handles the exception thrown and logs it.
+     *
+     * @param msg message to be logged
+     * @param e   exception thrown
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void handleException(String msg, Exception e) throws TaskManagementException {
+        log.error(msg, e);
+        throw new TaskManagementException(msg, e);
+    }
+
+    /**
+     * Validates an OMElement which has a TaskDescription serialized into it
+     * and returns the corresponding TaskDescription
+     *
+     * @param taskElement OMElement containing the TaskDescription
+     * @return TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static TaskDescription validateAndCreate(
+            OMElement taskElement) throws TaskManagementException {
+
+        validateTaskElement(taskElement);
+        TaskDescription taskDescription =
+                TaskDescriptionFactory.createTaskDescription(taskElement, TASK_OM_NAMESPACE);
+        validateTaskDescription(taskDescription);
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description : " + taskDescription);
+        }
+        return taskDescription;
+    }
+
+    /**
+     * Validates TaskDescriptions
+     *
+     * @param description TaskDescription
+     * @throws TaskManagementException TaskManagementException
+     */
+    private static void validateTaskDescription(
+            TaskDescription description) throws TaskManagementException {
+        if (description == null) {
+            handleException("Task Description can not be found.");
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
new file mode 100644
index 0000000..2edbd3a
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/AutoscalingJob.java
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.mediator.autoscale.lbautoscale.task;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.task.Task;
+import org.quartz.Job;
+import org.quartz.JobDetail;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import java.util.Map;
+
+public class AutoscalingJob implements Job {
+
+    public static final String AUTOSCALER_TASK = "autoscalerTask";
+
+    public static final String SYNAPSE_ENVI = "synapseEnv";
+
+    private static final Log log = LogFactory.getLog(AutoscalingJob.class);
+
+    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
+
+        try {
+
+            Task task = null;
+
+            JobDetail jobDetail = jobExecutionContext.getJobDetail();
+
+            if (log.isDebugEnabled()) {
+                log.debug("Executing Autoscaler task : " + jobDetail.getKey().getName());
+            }
+
+            @SuppressWarnings("rawtypes")
+            Map mjdm = jobExecutionContext.getMergedJobDataMap();
+
+            task = (Task) mjdm.get(AUTOSCALER_TASK);
+
+            if (task instanceof ManagedLifecycle) {
+                // Execute Autoscaler task
+                ((ServiceRequestsInFlightAutoscaler) task).execute();
+            }
+
+        } catch (Exception e) {
+            throw new JobExecutionException(e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
new file mode 100644
index 0000000..712ceb3
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/ServiceRequestsInFlightAutoscaler.java
@@ -0,0 +1,525 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.task;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.ClusteringFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.ManagedLifecycle;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.task.Task;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.AppNodeSanityCheckCallable;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.AutoscaleDeciderCallable;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.InstanceCountCallable;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.callables.PendingInstanceCountCallable;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerOsgiClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerStubClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.wso2.carbon.lb.common.replication.RequestTokenReplicationCommand;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleConstants;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+/**
+ * Service request in flight autoscaler task for Stratos service level auto-scaling
+ */
+public class ServiceRequestsInFlightAutoscaler implements Task, ManagedLifecycle {
+
+    private static final Log log = LogFactory.getLog(ServiceRequestsInFlightAutoscaler.class);
+
+    /**
+     * This instance holds the loadbalancer configuration
+     */
+    private LoadBalancerConfiguration loadBalancerConfig;
+
+    /**
+     * Autoscaler service client instance
+     */
+    private CloudControllerClient autoscalerService;
+
+    /**
+     * AppDomainContexts for each domain
+     * Key - domain
+     * Value - Map of key - sub domain
+     * value - {@link AppDomainContext}
+     */
+    private Map<String, Map<String, ?>> appDomainContexts =
+        new HashMap<String, Map<String, ?>>();
+
+    /**
+     * LB Context for LB cluster
+     */
+    private final LoadBalancerContext lbContext = new LoadBalancerContext();
+
+    /**
+     * Attribute to keep track whether this instance is the primary load balancer.
+     */
+    private boolean isPrimaryLoadBalancer;
+
+    /**
+     * Keeps track whether this task is still running
+     */
+    private boolean isTaskRunning;
+    
+    /**
+     * Thread pool used in this task to execute parallel tasks.
+     */
+    private ExecutorService executor = Executors.newFixedThreadPool(100);
+
+    /**
+     * Check that all app nodes in all clusters meet the minimum configuration
+     */
+    private void appNodesSanityCheck() {
+        
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+        
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+            
+            String msg =
+                    "Sanity check is failed to run. No Appdomain context is generated for the" +
+                        " domain " + serviceDomain;
+            
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+                log.debug("Sanity check has started for: "+AutoscaleUtil.domainSubDomainString(serviceDomain, serviceSubDomain));
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    if (appCtxt != null) {
+                        // Concurrently perform the application node sanity check.
+                        Callable<Boolean> worker =
+                            new AppNodeSanityCheckCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> appNodeSanityCheck = executor.submit(worker);
+                        jobList.add(appNodeSanityCheck);
+
+                    } else{
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else{
+                    log.error(msg);
+                }
+            }
+        }
+        
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            } 
+        }
+
+    }
+
+    /**
+     * Autoscale the entire system, analyzing the requests in flight of each domain - sub domain
+     */
+    private void autoscale() {
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            String msg =
+                "Autoscaler check is failed to run. No Appdomain context is generated for the" +
+                    " domain " + serviceDomain;
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                log.debug("Autoscaling analysis is starting to run for domain: " + serviceDomain +
+                    " and sub domain: " + serviceSubDomain);
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+
+                    if (appCtxt != null) {
+
+                        // Concurrently make the auto-scaling decisions
+                        Callable<Boolean> worker =
+                            new AutoscaleDeciderCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> autoscalerDeciderCheck = executor.submit(worker);
+                        jobList.add(autoscalerDeciderCheck);
+
+                    } else {
+                        log.error(msg + " and sub domain " + serviceSubDomain + " combination.");
+                    }
+                } else {
+                    log.error(msg);
+                }
+            }
+        }
+
+        // Retrieve the results of the concurrently performed sanity checks.
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+    }
+
+    /**
+     * We compute the number of running instances of a particular domain using clustering agent.
+     */
+    private void computeRunningAndPendingInstances() {
+
+        int runningInstances = 0, pendingInstances = 0;
+
+        List<Future<Boolean>> jobList = new ArrayList<Future<Boolean>>();
+
+        for (String serviceDomain : loadBalancerConfig.getServiceDomains()) {
+
+            // get the list of service sub_domains specified in loadbalancer config
+            String[] serviceSubDomains = loadBalancerConfig.getServiceSubDomains(serviceDomain);
+
+            for (String serviceSubDomain : serviceSubDomains) {
+
+                AppDomainContext appCtxt;
+                if (appDomainContexts.get(serviceDomain) != null) {
+                    appCtxt = (AppDomainContext) appDomainContexts.get(serviceDomain).get(serviceSubDomain);
+                    
+                    log.debug("Values in App domain context: " +
+                        appCtxt.getPendingInstanceCount() +
+                            " - " +
+                            appCtxt.getRunningInstanceCount() +
+                            " - Ctxt: " +
+                            appCtxt.hashCode());
+
+                    if (appCtxt != null) {
+                        Callable<Boolean> worker =
+                            new InstanceCountCallable(serviceDomain, serviceSubDomain, autoscalerService, appCtxt);
+                        Future<Boolean> countInstancesJob = executor.submit(worker);
+                        jobList.add(countInstancesJob);
+                    }
+                }
+            }
+        }
+
+        for (Future<Boolean> job : jobList) {
+            try {
+                job.get();
+            } catch (Exception ignore) {
+                log.error(ignore.getMessage(), ignore);
+                // no need to throw
+            }
+        }
+
+        /* Calculate running load balancer instances */
+
+        // count this LB instance in.
+        runningInstances = 1;
+
+        runningInstances += AutoscalerTaskDSHolder.getInstance().getAgent().getAliveMemberCount();
+
+        lbContext.setRunningInstanceCount(runningInstances);
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain") == null) {
+            String msg = "Clustering Agent's domain parameter is null. Please specify a domain" +
+                " name in axis2.xml of Elastic Load Balancer.";
+            log.error(msg);
+            throw new RuntimeException(msg);
+        }
+
+        String lbDomain = AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("domain").getValue().toString();
+
+        String lbSubDomain = null;
+
+        if (AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain") != null) {
+            lbSubDomain =
+                AutoscalerTaskDSHolder.getInstance().getAgent().getParameter("subDomain").getValue().toString();
+        }
+
+        // reset
+        pendingInstances = 0;
+        try {
+            pendingInstances = lbContext.getPendingInstanceCount();
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            // no need to throw
+        }
+
+        lbContext.setPendingInstanceCount(pendingInstances);
+
+        log.debug("Load Balancer members of domain: " +
+            lbDomain +
+            " and sub domain: " +
+            lbSubDomain +
+            " running instances (including this): " +
+            runningInstances +
+            " - pending instances: "
+            +
+            pendingInstances);
+
+    }
+
+    @Override
+    public void destroy() {
+        appDomainContexts.clear();
+        log.debug("Cleared AppDomainContext Map.");
+    }
+
+    /**
+     * This is method that gets called periodically when the task runs.
+     * <p/>
+     * The exact sequence of execution is shown in this method.
+     */
+    @Override
+    public void execute() {
+
+        appDomainContexts =
+            AutoscaleUtil.getAppDomainContexts(
+                AutoscalerTaskDSHolder.getInstance().getConfigCtxt(),
+                loadBalancerConfig);
+
+        if (isTaskRunning) {
+            log.debug("Task is already running!");
+            return;
+        }
+        try {
+            isTaskRunning = true;
+            setIsPrimaryLB();
+            if (!isPrimaryLoadBalancer) {
+                log.debug("This is not the primary load balancer, hence will not " +
+                        "perform any sanity check.");
+                return;
+            }
+            sanityCheck();
+            autoscale();
+        } finally {
+            // if there are any changes in the request length
+            if (Boolean.parseBoolean(System.getProperty(AutoscaleConstants.IS_TOUCHED))) {
+                // primary LB will send out replication message to all load balancers
+                sendReplicationMessage();
+            }
+            isTaskRunning = false;
+            log.debug("Task finished a cycle.");
+        }
+    }
+
+    @Override
+    public void init(final SynapseEnvironment synEnv) {
+
+        String msg = "Autoscaler Service initialization failed and cannot proceed.";
+
+        loadBalancerConfig = AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig();
+
+        if (loadBalancerConfig == null) {
+            log.error(msg + "Reason: Load balancer configuration is null.");
+            throw new RuntimeException(msg);
+        }
+
+        ConfigurationContext configCtx = ((Axis2SynapseEnvironment) synEnv).getAxis2ConfigurationContext();
+        AutoscalerTaskDSHolder.getInstance().setConfigCtxt(configCtx);
+
+        appDomainContexts = AutoscaleUtil.getAppDomainContexts(configCtx, loadBalancerConfig);
+        
+        AutoscalerTaskDSHolder.getInstance().setAgent(configCtx.getAxisConfiguration().getClusteringAgent());
+
+        boolean useEmbeddedAutoscaler = loadBalancerConfig.getLoadBalancerConfig().useEmbeddedAutoscaler();
+        
+        try {
+
+            if(useEmbeddedAutoscaler){
+                autoscalerService = new CloudControllerOsgiClient();
+            } else{
+                autoscalerService = new CloudControllerStubClient();
+            }
+            // let's initialize the auto-scaler service
+            autoscalerService.init();
+
+        }catch (Exception e) {
+            log.error(msg, e);
+            throw new RuntimeException(msg, e);
+        }
+
+        if (log.isDebugEnabled()) {
+
+            log.debug("Autoscaler task is initialized.");
+
+        }
+    }
+
+    /**
+     * Sanity check to see whether the number of LBs is the number specified in the LB config
+     */
+    private void loadBalancerSanityCheck() {
+
+        log.debug("Load balancer sanity check has started.");
+
+        // get current LB instance count
+        int currentLBInstances = lbContext.getInstances();
+
+        LoadBalancerConfiguration.LBConfiguration lbConfig =
+            loadBalancerConfig.getLoadBalancerConfig();
+
+        // get minimum requirement of LB instances
+        int requiredInstances = lbConfig.getInstances();
+
+        if (currentLBInstances < requiredInstances) {
+            log.debug("LB Sanity check failed. Running/Pending LB instances: " + currentLBInstances +
+                ". Required LB instances: " + requiredInstances);
+            int diff = requiredInstances - currentLBInstances;
+
+            // gets the domain of the LB
+            String lbDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("domain")
+                    .getValue()
+                    .toString();
+            String lbSubDomain =
+                AutoscalerTaskDSHolder
+                    .getInstance()
+                    .getAgent()
+                    .getParameter("subDomain")
+                    .getValue()
+                    .toString();
+
+            // Launch diff number of LB instances
+            log.debug("Launching " + diff + " LB instances.");
+
+            runInstances(lbContext, lbDomain, lbSubDomain, diff);
+        }
+    }
+
+    private int runInstances(final LoadBalancerContext context, final String domain,
+        final String subDomain,
+        int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = autoscalerService.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed. domain: " +
+                        domain +
+                            ", sub domain: " +
+                            subDomain);
+                    successfullyStartedInstanceCount--;
+                } else {
+                    log.debug("An instance of domain: " +
+                        domain +
+                            " and sub domain: " +
+                            subDomain +
+                            " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of sub domain: " + subDomain +
+                    " of domain : " + domain + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+    /**
+     * This method makes sure that the minimum configuration of the clusters in the system is
+     * maintained
+     */
+    private void sanityCheck() {
+
+        if (!isPrimaryLoadBalancer) {
+            log.debug("This is not the primary load balancer, hence will not " +
+                "perform any sanity check.");
+            return;
+        }
+
+        log.debug("This is the primary load balancer, starting to perform sanity checks.");
+
+        computeRunningAndPendingInstances();
+        loadBalancerSanityCheck();
+        appNodesSanityCheck();
+    }
+
+    /**
+     * Replicate information needed to take autoscaling decision for other ELBs
+     * in the cluster.
+     */
+    private void sendReplicationMessage() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+            RequestTokenReplicationCommand msg = new RequestTokenReplicationCommand();
+            msg.setAppDomainContexts(appDomainContexts);
+            try {
+                clusteringAgent.sendMessage(msg, true);
+                System.setProperty(AutoscaleConstants.IS_TOUCHED, "false");
+                log.debug("Request token replication messages sent out successfully!!");
+
+            } catch (ClusteringFault e) {
+                log.error("Failed to send the request token replication message.", e);
+            }
+        }
+        else {
+            log
+                .debug("Clustering Agent is null. Hence, unable to send out the replication message.");
+        }
+    }
+
+    /**
+     * This method will check whether this LB is the primary LB or not and set
+     * attribute accordingly.
+     */
+    private void setIsPrimaryLB() {
+
+        ClusteringAgent clusteringAgent = AutoscalerTaskDSHolder.getInstance().getAgent();
+        if (clusteringAgent != null) {
+
+            isPrimaryLoadBalancer = clusteringAgent.isCoordinator();
+
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
new file mode 100644
index 0000000..9c5ca8b
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/task/TaskSchedulingManager.java
@@ -0,0 +1,185 @@
+/**
+ * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.task;
+
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.task.TaskDescription;
+import org.apache.synapse.task.TaskDescriptionRepository;
+import org.apache.synapse.task.TaskScheduler;
+import org.wso2.carbon.task.TaskManager;
+
+import java.util.Iterator;
+import java.util.Map;
+
+public class TaskSchedulingManager {
+
+    private static final Log log = LogFactory.getLog(TaskSchedulingManager.class);
+
+    private static TaskSchedulingManager thisInstance = new TaskSchedulingManager();
+
+    public static TaskSchedulingManager getInstance() {
+        return thisInstance;
+    }
+
+    /**
+     * This method adds a particular Task to the Task Description Repository and schedule it
+     * for the execution.
+     *
+     * @param taskDescription      TaskDescription
+     * @param resources            Map containing require meta data for the task execution.
+     * @param configurationContext ConfigurationContext
+     */
+    public void scheduleTask(TaskDescription taskDescription, Map<String, Object> resources,
+                             ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Adding a Task Description to the Task Description Repository");
+        }
+
+        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).scheduleTask(
+                taskDescription, resources, AutoscalingJob.class);
+
+        if (log.isDebugEnabled()) {
+            log.debug("Task Description " + taskDescription.getName() +
+                    " added to the Task Description Repository");
+        }
+    }
+
+    /**
+     * Returns a Task Description with a given name from the Task Description Repository.
+     *
+     * @param taskName             taskName
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription
+     */
+    public TaskDescription getTaskDescription(
+            String taskName, ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a Start up : " + taskName + " from the configuration");
+        }
+
+        TaskDescription taskDescription = getTaskDescriptionRepository(
+                configurationContext).getTaskDescription(taskName);
+
+        if (taskDescription != null) {
+            if (log.isDebugEnabled()) {
+                log.debug("Returning a Task Description : " + taskDescription);
+
+            }
+            return taskDescription;
+        } else {
+            if (log.isDebugEnabled()) {
+                log.debug("No Task Description can be found with name :" + taskName);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * This method search for a given Task which has already been added to the Task Description
+     * Repository and removes it.
+     *
+     * @param taskDescription             TaskDescription
+     * @param configurationContext ConfigurationContext
+     */
+    public void deleteTaskDescription(TaskDescription taskDescription, ConfigurationContext configurationContext) {
+        String taskName = null;
+        if (taskDescription != null) {
+            taskName = taskDescription.getName();
+            getTaskDescriptionRepository(configurationContext).removeTaskDescription(taskName);
+            getTaskScheduler(configurationContext).deleteTask(taskName, taskDescription.getGroup());
+
+            if (log.isDebugEnabled()) {
+                log.debug("Deleted TaskDescription : " + taskName + " from the configuration");
+            }
+        } else {
+            log.warn("Unable to delete the Task " + taskName
+                    + ",as it doesn't exist in the Repository");
+        }
+    }
+
+    /**
+     * Retrieves all Task Descriptions added to the Task Description Repository at a given instance.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescription Iterator
+     */
+    public Iterator<TaskDescription> getAllTaskDescriptions(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Returning a All TaskDescription from the configuration");
+        }
+        return getTaskDescriptionRepository(configurationContext).getAllTaskDescriptions();
+    }
+
+    /**
+     * This method checks whether a particular Task has already been added to the Task Description
+     * Repository associated with the context of this execution and returns a flag indicating the
+     * existence.
+     *
+     * @param taskName             Name of the task to be searched
+     * @param configurationContext ConfigurationContext
+     * @return a boolean depending on the existence of a task
+     */
+    public boolean isContains(String taskName, ConfigurationContext configurationContext) {
+        return !getTaskDescriptionRepository(configurationContext).isUnique(taskName);
+    }
+
+    /**
+     * Returns the Carbon TaskDescriptionRepository instance that carries details of the added
+     * tasks for execution.
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskDescriptionRepository
+     */
+    private synchronized TaskDescriptionRepository getTaskDescriptionRepository(
+            ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Description Repository");
+        }
+        return (TaskDescriptionRepository) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_REPOSITORY);
+    }
+
+    /**
+     * Returns the carbon TaskScheduler associated with the context of scheduling the task execution
+     *
+     * @param configurationContext ConfigurationContext
+     * @return TaskScheduler
+     */
+    private synchronized TaskScheduler getTaskScheduler(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Retrieving access to Task Scheduler");
+        }
+        return (TaskScheduler) configurationContext.getProperty(
+                TaskManager.CARBON_TASK_SCHEDULER);
+    }
+
+    public void shutDown(ConfigurationContext configurationContext) {
+        if (log.isDebugEnabled()) {
+            log.debug("Starting to shut down tasks");
+        }
+
+//        getTaskDescriptionRepository(configurationContext).addTaskDescription(taskDescription);
+        getTaskScheduler(configurationContext).shutDown();
+
+        if (log.isDebugEnabled()) {
+            log.debug("All tasks shut down");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
new file mode 100644
index 0000000..d4ae9ef
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleConstants.java
@@ -0,0 +1,65 @@
+/*                                                                             
+ * Copyright 2004,2005 The Apache Software Foundation.                         
+ *                                                                             
+ * Licensed under the Apache License, Version 2.0 (the "License");             
+ * you may not use this file except in compliance with the License.            
+ * You may obtain a copy of the License at                                     
+ *                                                                             
+ *      http://www.apache.org/licenses/LICENSE-2.0                             
+ *                                                                             
+ * Unless required by applicable law or agreed to in writing, software         
+ * distributed under the License is distributed on an "AS IS" BASIS,           
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.    
+ * See the License for the specific language governing permissions and         
+ * limitations under the License.                                              
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.util;
+
+/**
+ * Constants
+ */
+public final class AutoscaleConstants {
+    public static final String REQUEST_ID = "request.id";
+    public static final String APP_DOMAIN_CONTEXTS = "autoscale.app.domain.contexts";
+    public static final String TARGET_DOMAIN = "autoscale.target.domain";
+    public static final String TARGET_SUB_DOMAIN = "autoscale.target.sub.domain";
+    public static final String LOAD_BALANCER_CONFIG = "loadbalancer.conf";
+    
+    /**
+     * we use this to track the changes happen to request token list lengths.
+     */
+    public static final String IS_TOUCHED = "is_touched";
+    
+    /**
+     * We'll check whether a server is started up in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int SERVER_START_UP_CHECK_TIME = 30000;
+    
+    /**
+     * We'll check whether an instance is left the cluster in every this much of time.
+     * (in milliseconds)
+     */
+    public static final int INSTANCE_REMOVAL_CHECK_TIME = 5000;
+
+    /**
+     * Name of the EC2 instance tag which if set on an instance, the autoscaler will not
+     * terminate such instance
+     */
+    public static final String AVOID_TERMINATION = "avoidTermination";
+
+    public static enum InstanceState {
+        RUNNING("running"), PENDING("pending"), TERMINATED("terminated"), SHUTTING_DOWN("shutting-down");
+
+        private String state;
+
+        InstanceState(String state) {
+            this.state = state;
+        }
+
+        public String getState() {
+            return state;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
new file mode 100644
index 0000000..c3131af
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscaleUtil.java
@@ -0,0 +1,356 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.mediator.autoscale.lbautoscale.util;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.clustering.management.GroupManagementAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.protocol.HTTP;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.LoadBalancerContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.state.check.PendingInstancesStateChecker;
+import org.apache.axiom.om.util.Base64;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Utility methods for Autoscale mediator
+ */
+public final class AutoscaleUtil {
+
+    private static final Log log = LogFactory.getLog(AutoscaleUtil.class);
+
+    private AutoscaleUtil() {
+    }
+
+    /**
+     * handles the exception
+     *
+     * @param msg exception message
+     */
+    public static void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(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);
+    }
+
+    /**
+     * 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;
+    }
+
+    /**
+     * 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 InstanceManager createEC2InstanceManager(String accessKey,
+                                                              String secretKey,
+                                                              String instanceMgtEPR) {
+        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
+        AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentials);
+        ec2Client.setEndpoint(instanceMgtEPR);
+        return new InstanceManager(ec2Client);
+    }*/
+
+    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 = AutoscaleUtil.getBytesFromFile(file);
+            if (bytes != null) {
+//                /BASE64.e encoder = new BASE64Encoder();
+                userData = Base64.encode(bytes);
+            }
+        } catch (IOException e) {
+            AutoscaleUtil.handleException("Cannot read data from payload file " + payloadFileName,
+                                          e);
+        }
+        return userData;
+    }
+
+    /*public static boolean areEqual(List<GroupIdentifier> securityGroups1, String[] sourceGroups2) {
+        for (String sourceGroup : sourceGroups2) {
+            boolean isSourceGroupFound = false;
+            for (GroupIdentifier securityGroup : securityGroups1) {
+                if (securityGroup.getGroupName().equals(sourceGroup)) {
+                    isSourceGroupFound = true;
+                }
+            }
+            if (!isSourceGroupFound) {
+                return false;
+            }
+        }
+        return true;
+    } */
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    public static int getTenantId(String url) {
+        String address = url;
+        String servicesPrefix = "/t/";
+        if (address != null && address.contains(servicesPrefix)) {
+            int domainNameStartIndex =
+                    address.indexOf(servicesPrefix) + servicesPrefix.length();
+            int domainNameEndIndex = address.indexOf('/', domainNameStartIndex);
+            String domainName = address.substring(domainNameStartIndex,
+                    domainNameEndIndex == -1 ? address.length() : domainNameEndIndex);
+            // return tenant id if domain name is not null
+            if (domainName != null) {
+                try {
+                    return AutoscalerTaskDSHolder.getInstance().getRealmService().getTenantManager().getTenantId(domainName);
+                } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                    log.error("An error occurred while obtaining the tenant id.", e);
+                }
+            }
+        }
+        // return 0 if the domain name is null
+        return 0;
+    }
+
+    /**
+     * TODO These methods should use to common place since these are using endpoints and mediators
+     */
+    @SuppressWarnings("unchecked")
+    public static String getTargetHost(MessageContext synCtx) {
+        org.apache.axis2.context.MessageContext axis2MessageContext =
+                ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        Map<String, String> headers =
+                (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
+        String address = headers.get(HTTP.TARGET_HOST);
+        if (address.contains(":")) {
+            address = address.substring(0, address.indexOf(":"));
+        }
+        return address;
+    }
+
+    @SuppressWarnings("unchecked")
+    public static Map<String, Map<String, ?>> getAppDomainContexts(ConfigurationContext configCtx,
+ LoadBalancerConfiguration lbConfig) {
+        Map<String, Map<String, ?>> oldAppDomainContexts =
+        	(Map<String, Map<String, ?>>) configCtx.getPropertyNonReplicable(AutoscaleConstants.APP_DOMAIN_CONTEXTS);
+        Map<String, Map<String, ?>> newAppDomainContexts = new HashMap<String, Map<String, ?>>();
+        
+            ClusteringAgent clusteringAgent = configCtx.getAxisConfiguration().getClusteringAgent();
+
+            for (String domain : lbConfig.getServiceDomains()) {
+
+                for (String subDomain : lbConfig.getServiceSubDomains(domain)) {
+                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                        throw new SynapseException("Axis2 clustering GroupManagementAgent for domain: " + domain +
+                                                   ", sub-domain: " + subDomain +
+                                                   " has not been defined");
+                    }
+
+                    if(oldAppDomainContexts == null || oldAppDomainContexts.get(domain) == null || 
+                    		(oldAppDomainContexts.get(domain) != null && oldAppDomainContexts.get(domain).get(subDomain) == null)){
+                    	
+                    	AppDomainContext appCtxt = new AppDomainContext(lbConfig.getServiceConfig(domain,
+                                subDomain));
+
+                    	addAppDomainContext(newAppDomainContexts, domain, subDomain, appCtxt);
+                    	
+                    } else {
+                        addAppDomainContext(newAppDomainContexts, domain, subDomain, (AppDomainContext) oldAppDomainContexts.get(domain).get(subDomain));
+                    }
+                    
+                }
+
+            }
+//        }
+        configCtx.setNonReplicableProperty(AutoscaleConstants.APP_DOMAIN_CONTEXTS,
+                                           newAppDomainContexts);
+
+        return newAppDomainContexts;
+    }
+    
+    
+    private static void addAppDomainContext(Map<String, Map<String, ?>> appDomainContexts,
+                                     String domain, String subDomain, AppDomainContext appCtxt) {
+
+        Map<String, AppDomainContext> map ;
+        
+        if(appDomainContexts.containsKey(domain)){
+            map = (Map<String, AppDomainContext>) appDomainContexts.get(domain);
+        }
+        else{
+            map = new HashMap<String, AppDomainContext>();
+        }
+        // put this appDomainContext
+        map.put(subDomain, appCtxt);
+        
+        // update the parent map
+        appDomainContexts.put(domain, map);
+        
+    }
+    
+    public static String domainSubDomainString(String domain, String subDomain){
+        return "Domain: "+domain+" - Sub Domain: "+subDomain;
+    }
+    
+    public static int runInstances(final CloudControllerClient client, final LoadBalancerContext context, final String domain,
+        final String subDomain, int diff) {
+
+        int successfullyStartedInstanceCount = diff;
+
+        if(context == null){
+            // can't help
+            return 0;
+        }
+        
+        while (diff > 0) {
+            // call autoscaler service and ask to spawn an instance
+            // and increment pending instance count only if autoscaler service returns
+            // true.
+            try {
+                String ip = client.startInstance(domain, subDomain);
+
+                if (ip == null || ip.isEmpty()) {
+                    log.debug("Instance start up failed for " + domainSubDomainString(domain, subDomain));
+                    successfullyStartedInstanceCount--;
+                    
+                } else {
+                    log.debug("An instance of " + domainSubDomainString(domain, subDomain) +
+                        " is started up.");
+                    if (context != null) {
+                        context.incrementPendingInstances(1);
+                    }
+                }
+            } catch (Exception e) {
+                log.error("Failed to start an instance of " + domainSubDomainString(domain, subDomain) + ".\n", e);
+                successfullyStartedInstanceCount--;
+            }
+
+            diff--;
+        }
+
+        if (successfullyStartedInstanceCount > 0) {
+            
+            Thread stateChecker =
+                new Thread(new PendingInstancesStateChecker(
+                    context,
+                    domain,
+                    subDomain,
+                    successfullyStartedInstanceCount,
+                    context.getRunningInstanceCount(),
+                    client));
+            stateChecker.start();
+        }
+
+        return successfullyStartedInstanceCount;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
new file mode 100644
index 0000000..f097e2e
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/util/AutoscalerTaskDSHolder.java
@@ -0,0 +1,129 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.util;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.axis2.context.ConfigurationContext;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.LBConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.stratos.cloud.controller.interfaces.CloudControllerService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * Singleton class to hold Agent Management Service
+ */
+public class AutoscalerTaskDSHolder {
+    
+    private ConfigurationContextService configurationContextService;
+    private LoadBalancerConfiguration wholeLbConfig;
+    private CloudControllerService cloudControllerService;  
+
+    private RealmService realmService;
+    private ClusteringAgent agent;
+    private ConfigurationContext configCtxt;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+
+    private static AutoscalerTaskDSHolder instance = new AutoscalerTaskDSHolder();
+
+    private AutoscalerTaskDSHolder(){
+
+    }
+
+    public static AutoscalerTaskDSHolder getInstance(){
+        return instance;
+    }
+
+    public ConfigurationContextService getConfigurationContextServiceService(){
+        return this.configurationContextService;
+    }
+
+    public void setConfigurationContextService(ConfigurationContextService cCtxService){
+        this.configurationContextService = cCtxService;
+    }
+    
+    public LoadBalancerConfiguration getWholeLoadBalancerConfig() {
+        return wholeLbConfig;
+    }
+    
+    public LBConfiguration getLoadBalancerConfig() {
+        return wholeLbConfig.getLoadBalancerConfig();
+    }
+
+    public ClusteringAgent getAgent() {
+        return agent;
+    }
+
+    public void setAgent(ClusteringAgent agent) {
+        this.agent = agent;
+    }
+
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        if (lbConfigSer != null) {
+            this.wholeLbConfig = (LoadBalancerConfiguration) lbConfigSer.getLoadBalancerConfig();
+        } else {
+            this.wholeLbConfig = null;
+        }
+    }
+
+	public void setConfigCtxt(ConfigurationContext configCtxt) {
+		this.configCtxt = configCtxt;
+	}
+
+	public ConfigurationContext getConfigCtxt() {
+		return configCtxt;
+	}
+
+	public void setCloudControllerService(CloudControllerService cc) {
+        this.cloudControllerService = cc;
+    }
+	
+	public CloudControllerService getCloudControllerService() {
+        return cloudControllerService;
+    }
+
+	public UserRegistry getConfigRegistry() {
+        return configRegistry;
+    }
+
+    public void setConfigRegistry(UserRegistry configRegistry) {
+        this.configRegistry = configRegistry;
+    }
+    
+    public UserRegistry getGovernanceRegistry() {
+        return governanceRegistry;
+    }
+
+    public void setGovernanceRegistry(UserRegistry governanceRegistry) {
+        this.governanceRegistry = governanceRegistry;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
new file mode 100644
index 0000000..399d502
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorFactory
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorFactory
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorFactory

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
new file mode 100644
index 0000000..05fce78
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/META-INF/services/org.apache.synapse.config.xml.MediatorSerializer
@@ -0,0 +1,2 @@
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleInMediatorSerializer
+org.wso2.carbon.mediator.autoscale.ec2autoscale.mediators.AutoscaleOutMediatorSerializer
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
new file mode 100644
index 0000000..f8ecf6f
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-load-average.xml
@@ -0,0 +1,138 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.LoadAverageBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The minimum and maximum limits of the load balancer instances
+        -->
+        <property name="minLoadBalancerInstances" value="1"/>
+
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The low and high limits of the load average
+        -->
+        <property name="loadAverageLowerLimit" value="2"/>
+        <property name="loadAverageHigherLimit" value="5"/>
+
+        <!--
+            The Load Balanced Service Ports
+        -->
+        <property name="serviceHttpPort" value="9763"/>
+        <property name="serviceHttpsPort" value="9443"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
new file mode 100644
index 0000000..3e66066
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/resources/synapse-messages-in-flight.xml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+  ~  Copyright (c) 2005-2010, WSO2 Inc. (http://wso2.com) All Rights Reserved.
+  ~
+  ~  WSO2 Inc. licenses this file to you under the Apache License,
+  ~  Version 2.0 (the "License"); you may not use this file except
+  ~  in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing,
+  ~  software distributed under the License is distributed on an
+  ~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~  KIND, either express or implied.  See the License for the
+  ~  specific language governing permissions and limitations
+  ~  under the License.
+  -->
+
+<!-- The default synapse configuration shipped with the WSO2 Load Balancer
+     This handles the load balancing and the autoscaling of the stratos services
+ -->
+
+<definitions xmlns="http://ws.apache.org/ns/synapse">
+
+    <!-- You can add any flat sequences, endpoints, etc.. to this synapse-messages-in-flight.xml file if you do
+         *not* want to have the defaults given below, specific to WSO2 LB and auto-scaler
+    -->
+
+
+    <!-- Given below is the auto-scale mediator specific task. Uncomment it, if you want to
+         auto-scale your applications.
+    -->
+
+    <task class="org.wso2.carbon.mediator.autoscale2.MessagesInFlightBasedEC2LoadAnalyzerTask"
+          name="LoadAnalyzer">
+
+
+        <!--
+            The private key for the ec2
+        -->
+        <property name="ec2PrivateKey" value="/mnt/payload/pk.pem"/>
+
+        <!--
+            The certificate for the ec2
+        -->
+        <property name="ec2Cert" value="/mnt/payload/cert.pem"/>
+
+        <!--
+            The amazon instance type for the load balanced service instances.
+            Recommended and the default is m1.large.
+        -->
+        <property name="instanceType" value="m1.large"/>
+
+        <!--
+            The amazon instance type for the instances of the load balancer itself.
+            Default is m1.large. Can be changed to m1.small too.
+        -->
+        <property name="loadBalancerInstanceType" value="m1.large"/>
+
+        <!--
+            The group of the service being load balanced.
+        -->
+        <property name="applicationGroup" value="as-2011-02-23,cloud-mysql,default"/>
+
+        <!--
+            The group of the load balancer.
+        -->
+        <property name="loadBalancerGroup" value="stratos-appserver-lb,cloud-mysql,default"/>
+
+        <!--
+            The Amazon availability zone for the instances. 1-c is given as the default
+        -->
+        <property name="availabilityZone" value="us-east-1c"/>
+
+        <!--
+            Additional information for the amazon instances
+        -->
+        <property name="instanceAdditionalInfo" value="EC2 autoscale instance"/>
+
+        <!--
+            The key pair
+        -->
+        <property name="key" value="stratos-1.0.0-keypair"/>
+
+        <!--
+            The service payload file which should be loaded to the bucket
+        -->
+        <property name="applicationPayload" value="resources/cluster_node.zip"/>
+
+        <!--
+            The load balancer payload file which should be loaded to the bucket
+        -->
+        <property name="loadBalancerPayload" value="/mnt/payload.zip"/>
+
+        <!--
+            The elasticIP property can be overriden by the ELASTIC_IP environment var,
+             which is set in the payload
+        -->
+        <property name="elasticIP" value="${ELASTIC_IP}"/>
+
+        <!--
+            The time in milliseconds which the message takes to expire
+        -->
+        <property name="messageExpiryTime" value="60000"/>
+
+        <!--
+            The minimum and maximum limits of the load balanced service instances
+        -->
+        <property name="minAppInstances" value="1"/>
+        <property name="maxAppInstances" value="5"/>
+
+        <!--
+            The number of load balancer instances
+        -->
+        <property name="loadBalancerInstances" value="1"/>
+
+        <!--
+            The given queue length per node, for the calculation in scaling up
+        -->
+        <property name="queueLengthPerNode" value="400"/>
+        <property name="roundsToAverage" value="10"/>
+
+        <!--
+            The instances spawned at once, per scaling up decision.
+	    Default and the recommended value is 1
+        -->
+        <property name="instancesPerScaleUp" value="1"/>
+
+        <!--
+            The interval to trigger the task in seconds
+        -->
+        <trigger interval="5"/>
+    </task>
+</definitions>


[45/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
new file mode 100644
index 0000000..7cdd8c8
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/LoadBalanceEndpointServiceComponent.java
@@ -0,0 +1,394 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.lb.endpoint.internal;
+
+import org.apache.axis2.deployment.DeploymentEngine;
+import org.apache.axis2.engine.AxisConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.Mediator;
+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.apache.synapse.mediators.base.SequenceMediator;
+import org.apache.synapse.mediators.builtin.SendMediator;
+import org.apache.synapse.mediators.filters.InMediator;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.cartridge.messages.CreateClusterDomainMessage;
+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.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.lb.endpoint.EndpointDeployer;
+import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.wso2.carbon.lb.endpoint.builder.TopologySyncher;
+import org.wso2.carbon.lb.endpoint.cluster.manager.ClusterDomainManagerImpl;
+import org.wso2.carbon.lb.endpoint.endpoint.TenantAwareLoadBalanceEndpoint;
+import org.wso2.carbon.lb.endpoint.subscriber.TopologySubscriber;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+import org.wso2.carbon.lb.endpoint.util.TopologyConstants;
+
+import java.io.File;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @scr.component name="org.wso2.carbon.load.balancer.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"
+ * @scr.reference name="org.wso2.carbon.lb.common"
+ * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ */
+@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 {
+            SynapseEnvironmentService synEnvService =
+                                                      ConfigHolder.getInstance()
+                                                                  .getSynapseEnvironmentService(MultitenantConstants.SUPER_TENANT_ID);
+
+            registerDeployer(ConfigHolder.getInstance().getAxisConfiguration(),
+                             synEnvService.getSynapseEnvironment());
+
+			      if (ConfigHolder.getInstance().getConfigCtxt() != null) {
+				      ConfigHolder
+						    .getInstance()
+						    .getConfigCtxt()
+						    .setNonReplicableProperty(
+								CreateClusterDomainMessage.CLUSTER_DOMAIN_MANAGER,
+								new ClusterDomainManagerImpl());
+				        log.debug("Setting property Cluster Domain MANAGER ... ");
+
+		  	    }
+			
+            SynapseEnvironment synapseEnv = synEnvService.getSynapseEnvironment();
+
+            /* Registering Tenant Aware Load Balance Endpoint */
+
+            // get the main sequence mediator
+            SequenceMediator mainSequence =
+                                            (SequenceMediator) synapseEnv.getSynapseConfiguration()
+                                                                         .getSequence("main");
+
+            boolean successfullyRegistered = false;
+            
+            // iterate through its child mediators
+            for (Mediator child : mainSequence.getList()) {
+
+                // find the InMediator
+                if (child instanceof InMediator) {
+                    
+                    for(Mediator inChild : ((InMediator)child).getList()){
+                        
+                        // find the SendMediator
+                        if (inChild instanceof SendMediator) {
+                            
+                            SendMediator sendMediator = (SendMediator) inChild;
+                            
+                            /* add Tenant Aware LB endpoint */
+                            
+                            TenantAwareLoadBalanceEndpoint tenantAwareEp = new TenantAwareLoadBalanceEndpoint();
+
+                            tenantAwareEp.init(synapseEnv);
+                            
+                            sendMediator.setEndpoint(tenantAwareEp);
+                            
+                            successfullyRegistered = true;
+
+                            if (log.isDebugEnabled()) {
+                                log.debug("Added Tenant Aware Endpoint: " +
+                                          sendMediator.getEndpoint().getName() + "" +
+                                          " to Send Mediator.");
+                            }
+                        }
+                    }
+                }
+            }
+            
+            if(!successfullyRegistered){
+                String msg = "Failed to register Tenant Aware Load Balance Endpoint in Send Mediator.";
+                log.fatal(msg);
+                throw new TenantAwareLoadBalanceEndpointException(msg);
+            }
+
+            if (log.isDebugEnabled()) {
+                log.debug("Endpoint Admin bundle is activated ");
+            }
+            
+            if (ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl() != null) {
+
+                // start consumer
+                // initialize TopologyBuilder Consumer
+                Thread topologyConsumer =
+                    new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+                // start consumer
+                topologyConsumer.start();
+
+                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
+
+            }
+            activated = true;
+        } catch (Throwable e) {
+            log.error("Failed to activate Endpoint Admin bundle ", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        try {
+            Set<Map.Entry<Integer, SynapseEnvironmentService>> entrySet =
+                    ConfigHolder.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) {
+        ConfigHolder.getInstance().setAxisConfiguration(
+                cfgCtxService.getServerConfigContext().getAxisConfiguration());
+        ConfigHolder.getInstance().setConfigCtxt(cfgCtxService.getServerConfigContext());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(null);
+        ConfigHolder.getInstance().setConfigCtxt(null);
+    }
+
+    protected void setSynapseConfigurationService(
+            SynapseConfigurationService synapseConfigurationService) {
+
+        ConfigHolder.getInstance().setSynapseConfiguration(
+                synapseConfigurationService.getSynapseConfiguration());
+    }
+
+    protected void unsetSynapseConfigurationService(
+            SynapseConfigurationService synapseConfigurationService) {
+
+        ConfigHolder.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 = ConfigHolder.getInstance().getSynapseEnvironmentServices().
+                containsKey(synapseEnvironmentService.getTenantId());
+
+        ConfigHolder.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) {
+        ConfigHolder.getInstance().removeSynapseEnvironmentService(
+                synapseEnvironmentService.getTenantId());
+    }
+
+    protected void setRegistryService(RegistryService regService) {
+        if (log.isDebugEnabled()) {
+            log.debug("RegistryService bound to the endpoint component");
+        }
+        try {
+            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+            ConfigHolder.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");
+        }
+        ConfigHolder.getInstance().setConfigRegistry(null);
+    }
+
+    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service bound to the endpoint component");
+        }
+        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
+    }
+
+    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
+        if (log.isDebugEnabled()) {
+            log.debug("Dependency management service unbound from the endpoint component");
+        }
+        ConfigHolder.getInstance().setDependencyManager(null);
+    }
+
+    protected void setSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+
+    }
+
+    protected void unsetSynapseRegistrationsService(
+            SynapseRegistrationsService synapseRegistrationsService) {
+        int tenantId = synapseRegistrationsService.getTenantId();
+        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
+            SynapseEnvironment env = ConfigHolder.getInstance().
+                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
+
+            ConfigHolder.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) {
+        ConfigHolder.getInstance().setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        ConfigHolder.getInstance().setRealmService(null);
+    }
+    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
new file mode 100644
index 0000000..0f42aad
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/internal/RegistryManager.java
@@ -0,0 +1,51 @@
+/*
+ *  Copyright WSO2 Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.wso2.carbon.lb.endpoint.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+import org.wso2.carbon.lb.common.util.DomainMapping;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+
+public class RegistryManager {
+    UserRegistry governanceRegistry = ConfigHolder.getInstance().getGovernanceRegistry();
+    private static final Log log = LogFactory.getLog(RegistryManager.class);
+    /**
+     *
+     */
+    private Resource resource = null;
+    public static final String HOST_INFO = "hostinfo/";
+    public static final String ACTUAL_HOST = "actual.host";
+
+    public DomainMapping getMapping(String hostName) {
+        DomainMapping domainMapping;
+        try {
+            if (governanceRegistry.resourceExists(HOST_INFO + hostName)) {
+                resource = governanceRegistry.get(HOST_INFO + hostName);
+                domainMapping = new DomainMapping(hostName);
+                domainMapping.setActualHost(resource.getProperty(ACTUAL_HOST));
+                return domainMapping;
+            }
+        } catch (RegistryException e) {
+            log.info("Error while getting registry resource");
+            throw new RuntimeException(e);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
new file mode 100644
index 0000000..dd05f83
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopicHealthChecker.java
@@ -0,0 +1,67 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.lb.endpoint.subscriber;
+
+import javax.jms.TopicSubscriber;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This health checker runs forever, and is responsible for re-establishing a connection
+ * between ELB and CC.
+ */
+public class TopicHealthChecker implements Runnable{
+    
+    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
+    private String topicName;
+    private TopicSubscriber subscriber;
+
+    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
+        this.topicName = topicName;
+        this.subscriber = subscriber;
+    }
+    
+    @Override
+    public void run() {
+        log.info("Topic Health Checker is running... ");
+
+        while (true) {
+            try {
+                subscriber.getTopic();
+                
+                // health checker runs in every 30s
+                Thread.sleep(30000);
+
+            } 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) {
+                }
+            }
+
+        }
+
+        TopologySubscriber.subscribe(topicName);
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
new file mode 100644
index 0000000..ed30069
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologyListener.java
@@ -0,0 +1,28 @@
+package org.wso2.carbon.lb.endpoint.subscriber;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.TextMessage;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+
+public class TopologyListener implements MessageListener {
+
+	private static final Log log = LogFactory.getLog(TopologyListener.class);
+
+	@Override
+    public void onMessage(Message message) {
+		TextMessage receivedMessage = (TextMessage) message;
+        try {
+            
+            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
+
+        } catch (JMSException e) {
+        	log.error(e.getMessage(), e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
new file mode 100644
index 0000000..a36445a
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/subscriber/TopologySubscriber.java
@@ -0,0 +1,77 @@
+package org.wso2.carbon.lb.endpoint.subscriber;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.endpoint.util.ConfigHolder;
+import org.wso2.carbon.lb.endpoint.util.TopologyConstants;
+
+public class TopologySubscriber {
+
+	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
+	
+    public static void subscribe(String topicName) {
+        Properties initialContextProperties = new Properties();
+        TopicSubscriber topicSubscriber = null;
+        TopicSession topicSession = null;
+        TopicConnection topicConnection = null;
+        InitialContext initialContext = null;
+
+        initialContextProperties.put("java.naming.factory.initial",
+            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+
+        String mbServerUrl = null;
+        if (ConfigHolder.getInstance().getLbConfig() != null) {
+            mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
+        }
+        String connectionString =
+            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
+                (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl) + "'&reconnect='true'";
+        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+
+        try {
+            initialContext = new InitialContext(initialContextProperties);
+            TopicConnectionFactory topicConnectionFactory =
+                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+            topicConnection = topicConnectionFactory.createTopicConnection();
+            topicConnection.start();
+            topicSession =
+                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Topic topic = topicSession.createTopic(topicName);
+            topicSubscriber =
+                topicSession.createSubscriber(topic);
+
+            topicSubscriber.setMessageListener(new TopologyListener());
+
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+
+            try {
+                if (topicSubscriber != null) {
+                    topicSubscriber.close();
+                }
+
+                if (topicSession != null) {
+                    topicSession.close();
+                }
+
+                if (topicConnection != null) {
+                    topicConnection.close();
+                }
+            } catch (JMSException e1) {
+                // ignore
+            }
+
+        } 
+        finally {
+            // start the health checker
+            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
+            healthChecker.start();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
new file mode 100644
index 0000000..59f68ae
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/ConfigHolder.java
@@ -0,0 +1,189 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.lb.endpoint.util;
+
+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.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.lb.endpoint.TenantAwareLoadBalanceEndpointException;
+import org.wso2.carbon.lb.endpoint.TenantLoadBalanceMembershipHandler;
+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.HashMap;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+/**
+ *
+ */
+public class ConfigHolder {
+
+    private static ConfigHolder instance;
+    private static final Log log = LogFactory.getLog(ConfigHolder.class);
+
+    private SynapseConfiguration synapseConfiguration;
+    private ConfigurationContext configCtxt;
+    private AxisConfiguration axisConfiguration;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+    private DependencyManagementService dependencyManager;
+    private TenantLoadBalanceMembershipHandler tenantMembershipHandler;
+    private LoadBalancerConfigurationService lbConfigService;
+    private BlockingQueue<String> sharedTopologyQueue = new LinkedBlockingQueue<String>();
+    private String previousMsg;
+    
+
+    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
+            new HashMap<Integer, SynapseEnvironmentService>();
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    private RealmService realmService;
+
+    private ConfigHolder() {
+    }
+
+    public static ConfigHolder getInstance() {
+        if (instance == null) {
+            instance = new ConfigHolder();
+        }
+        return instance;
+    }
+
+    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 void setTenantLoadBalanceMembershipHandler(TenantLoadBalanceMembershipHandler handler) {
+        tenantMembershipHandler = handler;
+    }
+    
+    public TenantLoadBalanceMembershipHandler getTenantLoadBalanceMembershipHandler() {
+        return tenantMembershipHandler;
+    }
+
+    public ConfigurationContext getConfigCtxt() {
+        return configCtxt;
+    }
+
+    public void setConfigCtxt(ConfigurationContext configCtxt) {
+        this.configCtxt = configCtxt;
+    }
+    
+    public void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        this.lbConfigService = lbConfigSer;
+    }
+
+    public LoadBalancerConfiguration getLbConfig() {
+        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
+    }
+
+	public BlockingQueue<String> getSharedTopologyDiffQueue() {
+	    return sharedTopologyQueue;
+    }
+
+	public void setSharedTopologyDiffQueue(BlockingQueue<String> sharedTopologyDiffQueue) {
+	    this.sharedTopologyQueue = sharedTopologyDiffQueue;
+    }
+
+	public String getPreviousMsg() {
+	    return previousMsg;
+    }
+
+	public void setPreviousMsg(String previousMsg) {
+	    this.previousMsg = previousMsg;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
new file mode 100644
index 0000000..7e2fb79
--- /dev/null
+++ b/components/load-balancer/lb-endpoint/org.wso2.carbon.lb.endpoint/4.1.3/src/main/java/org/wso2/carbon/lb/endpoint/util/TopologyConstants.java
@@ -0,0 +1,13 @@
+package org.wso2.carbon.lb.endpoint.util;
+
+public class TopologyConstants {
+    
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+    public static final String MB_SERVER_URL = "mb.server.ip";
+    public static final String DEFAULT_MB_SERVER_URL = "localhost:5672";
+    
+    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
new file mode 100644
index 0000000..92dae9d
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/pom.xml
@@ -0,0 +1,115 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+        <artifactId>loadbalancer-components</artifactId>
+        <version>4.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.lb.common</artifactId>
+    <packaging>bundle</packaging>
+    <version>4.1.3</version>
+    <name>WSO2 Loadbalancer - Common</name>
+    <url>http://wso2.org</url>
+    
+    <dependencies>
+    	<dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>4.1.0</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>2.1.1-wso2v4</version>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+        </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>
+        </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>
+                <version>2.12</version>
+                <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.wso2.carbon.lb.common.*,
+                        </Export-Package>
+                        <Private-Package>
+                        	org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
new file mode 100644
index 0000000..54503ab
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/LRUCache.java
@@ -0,0 +1,100 @@
+/*
+ *  Copyright WSO2 Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.wso2.carbon.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/c1efa393/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
new file mode 100644
index 0000000..b2cfcc2
--- /dev/null
+++ b/components/load-balancer/org.wso2.carbon.lb.common/4.1.3/src/main/java/org/wso2/carbon/lb/common/cache/URLMappingCache.java
@@ -0,0 +1,44 @@
+/*
+ *  Copyright WSO2 Inc.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.wso2.carbon.lb.common.cache;
+
+import org.wso2.carbon.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;
+   }
+}


[49/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
new file mode 100644
index 0000000..7373902
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/AutoscalerConstant.java
@@ -0,0 +1,72 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+public final class AutoscalerConstant {
+
+    /**
+     * elastic-scaler-config XML file's elements
+     */
+    public static final String SERIALIZATION_DIR_ELEMENT = "serializationDir";
+    public static final String IAAS_PROVIDER_ELEMENT = "iaasProvider";
+    public static final String IAAS_PROVIDER_TYPE_ATTR = "type";
+    public static final String IAAS_PROVIDER_NAME_ATTR = "name";
+    public static final String PROPERTY_ELEMENT = "property";
+    public static final String PROPERTY_NAME_ATTR= "name";
+    public static final String PROPERTY_VALUE_ATTR = "value";
+    public static final String IMAGE_ID_ELEMENT = "imageId";
+    public static final String SCALE_DOWN_ORDER_ELEMENT = "scaleDownOrder";
+    public static final String SCALE_UP_ORDER_ELEMENT = "scaleUpOrder";
+    public static final String PROVIDER_ELEMENT = "provider";
+    public static final String IDENTITY_ELEMENT = "identity";
+    public static final String CREDENTIAL_ELEMENT = "credential";
+    public static final String DEFAULT_SERVICE_ELEMENT = "default";
+    public static final String SERVICE_ELEMENT = "service";
+    public static final String SERVICE_DOMAIN_ATTR = "domain";
+    public static final String SERVICE_SUB_DOMAIN_ATTR = "subDomain";
+    
+    /**
+     * Secret Manager related aliases.
+     */
+    public static final String EC2_IDENTITY_ALIAS = "elastic.scaler.ec2.identity";
+    public static final String EC2_CREDENTIAL_ALIAS = "elastic.scaler.ec2.credential";
+    public static final String OPENSTACK_IDENTITY_ALIAS = "elastic.scaler.openstack.identity";
+    public static final String OPENSTACK_CREDENTIAL_ALIAS = "elastic.scaler.openstack.credential";
+    
+    /**
+     * Serializer related constants
+     */
+    public static final String IAAS_CONTEXT_LIST_SERIALIZING_FILE = "iaas-context-list.txt";
+    public static final String LASTLY_USED_IAAS_MAP_SERIALIZING_FILE = "lastly-used-iaas.txt";
+    
+    /**
+     * Payload related constants
+     */
+    public static final String PAYLOAD_DIR = "payload";
+    public static final String PARAMS_FILE_NAME = "launch-params";
+    public static final String RESOURCES_DIR = "resources";
+    public static final String VALUE_SEPARATOR = "=";
+    public static final String ENTRY_SEPARATOR = ",";
+    public static final String APP_PATH_KEY = "APP_PATH";
+    public static final String TENANT_KEY = "TENANT";
+    
+    /**
+	 * Super tenant id
+	 */
+    public static final String SUPER_TENANT_ID = "-1234";
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
new file mode 100644
index 0000000..c2affa5
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasContext.java
@@ -0,0 +1,389 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.jclouds.compute.ComputeService;
+import org.jclouds.compute.domain.Template;
+import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+
+/**
+ * This object holds all IaaS related runtime data.
+ */
+public class IaasContext implements Serializable{
+   
+    private static final long serialVersionUID = -922284976926131383L;
+    
+    // name of the IaaS
+    private Enum<Iaases> name;
+    
+    /* We keep following maps in order to make the look up time, low.*/
+    
+    /**
+     * Key - domain
+     * Value - is another map
+     *          key - sub domain
+     *          value - <code>InstanceContext</code>
+     */
+    private Map<String, Map<String, InstanceContext>> instanceCtxts;
+    
+    /**
+     * Key - public IP
+     * Value - <code>InstanceContext</code>
+     */
+    private Map<String, InstanceContext> publicIpToInstanceCtxt;
+    
+    /**
+     * Key - node id 
+     * Value - <code>InstanceContext</code>
+     */
+    private Map<String, InstanceContext> nodeIdToInstanceCtxt;
+    
+    
+//    private transient Map<String, Template> domainToTemplateMap;
+    private transient ComputeService computeService;
+    
+    // Since Jclouds' NodeMetadata object contains unserializable objects, I had to use 3 maps.
+//    private Map<String, String> nodeIdToDomainMap = new LinkedHashMap<String, String>();
+//    private Map<String, String> publicIpToDomainMap = new LinkedHashMap<String, String>();
+//    private Map<String, String> publicIpToNodeIdMap = new LinkedHashMap<String, String>();
+    
+    private int scaleUpOrder, scaleDownOrder;
+
+    public IaasContext(Enum<Iaases> name, ComputeService computeService) {
+        this.name = name;
+        this.computeService = computeService;
+        instanceCtxts = new LinkedHashMap<String, Map<String,InstanceContext>>();
+        publicIpToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
+        nodeIdToInstanceCtxt = new LinkedHashMap<String, InstanceContext>();
+    }
+
+    public Enum<Iaases> getName() {
+        return name;
+    }
+    
+    public void addInstanceContext(InstanceContext ctx) {
+        
+        if(ctx == null){
+            return;
+        }
+        
+        String domain = ctx.getDomain();
+        String subDomain = ctx.getSubDomain();
+        
+        if(domain != null && subDomain != null){
+            addToInstanceCtxts(domain, subDomain, ctx);
+        }
+        
+    }
+    
+    public void addNodeDetails(String domain, String subDomain, String nodeId, String ip) {
+        
+        if(getInstanceContext(domain, subDomain) != null){
+            getInstanceContext(domain, subDomain).addNode(nodeId, ip);
+            
+            nodeIdToInstanceCtxt.put(nodeId, getInstanceContext(domain, subDomain));
+            publicIpToInstanceCtxt.put(ip, getInstanceContext(domain, subDomain));
+        }
+    }
+    
+    private void addToInstanceCtxts(String domainName, String subDomainName, InstanceContext ctx) {
+
+        Map<String, InstanceContext> map;
+        
+        if(instanceCtxts.get(domainName) == null){
+            map = new HashMap<String, InstanceContext>();
+            
+        } else{
+            map = instanceCtxts.get(domainName);
+        }
+        
+        map.put(subDomainName, ctx);
+        instanceCtxts.put(domainName, map);
+        
+    }
+
+//    public void addToDomainToTemplateMap(String key, Template value) {
+//        domainToTemplateMap.put(key, value);
+//    }
+
+    public Template getTemplate(String domain, String subDomain) {
+        if(getInstanceContext(domain, subDomain) == null){
+            return null;
+        }
+        return getInstanceContext(domain, subDomain).getTemplate();
+    }
+    
+    public InstanceContext getInstanceContext(String domain, String subDomain) {
+        if (instanceCtxts.get(domain) != null) {
+            return instanceCtxts.get(domain).get(subDomain);
+        }
+        return null;
+    }
+
+    public ComputeService getComputeService() {
+        return computeService;
+    }
+    
+    public void setComputeService(ComputeService computeService) {
+        this.computeService = computeService;
+    }
+
+//    public void addNodeIdToDomainMap(String nodeId, String domain) {
+//        nodeIdToDomainMap.put(nodeId, domain);
+//    }
+//    
+//    public void addPublicIpToDomainMap(String ip, String domain) {
+//        publicIpToDomainMap.put(ip, domain);
+//    }
+//    
+//    public void addPublicIpToNodeIdMap(String ip, String nodeId) {
+//        publicIpToNodeIdMap.put(ip, nodeId);
+//    }
+
+    /**
+     * This will return the node id of the node which is belong to the
+     * requesting domain, sub domain and which is the most recently created. If it cannot find a
+     * matching node id, this will return <code>null</code>.
+     * @param domain service domain.
+     * @param subDomain service sub domain. 
+     * @return the node Id of the node
+     */
+    public String getLastMatchingNode(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in reverse order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(ctx.getNodeIdToIpMap().size());
+
+        if (iter.hasPrevious()) {
+            return iter.previous();
+        }
+        
+        return null;
+    }
+    
+    /**
+     * This will return the public IP of the node which is belong to the
+     * requesting domain, sub domain and which is the most recently created. If it cannot find a
+     * matching public IP, this will return <code>null</code>.
+     * @param domain service domain. 
+     * @param subDomain service sub domain. 
+     * @return the public IP of the node
+     */
+    public String getLastMatchingPublicIp(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in reverse order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(ctx.getNodeIdToIpMap().size());
+
+        while (iter.hasPrevious()) {
+            return ctx.getNodeIdToIpMap().get(iter.previous());
+        }
+        
+        return null;
+        
+//        // traverse from the last entry of the map
+//        ListIterator<Map.Entry<String, String>> iter =
+//            new ArrayList<Entry<String, String>>(publicIpToDomainMap.entrySet()).
+//                                listIterator(publicIpToDomainMap.size());
+//
+//        while (iter.hasPrevious()) {
+//            Map.Entry<String, String> entry = iter.previous();
+//            if (entry.getValue().equals(domain)) {
+//                return entry.getKey();
+//            }
+//        }
+//        
+//        return null;
+    }
+
+    /**
+     * This will return the node id of the node which is belong to the
+     * requesting domain, sub domain and which is created at first. If it cannot find a
+     * matching node id, this will return <code>null</code>.
+     * @param domain service domain.
+     * @param subDomain service sub domain.
+     * @return node id of the node
+     */
+    public String getFirstMatchingNode(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return null;
+        }
+        
+        // iterate in added order
+        ListIterator<String> iter =
+            new ArrayList<String>(ctx.getNodeIdToIpMap().keySet()).
+                                listIterator(0);
+
+        while (iter.hasNext()) {
+            return iter.next();
+        }
+        
+        return null;
+        
+//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
+//            if (entry.getValue().equals(domain)) {
+//                return entry.getKey();
+//            }
+//        }
+//        return null;
+    }
+
+    /**
+     * This will return the node id of the node which has the given public IP. 
+     * If it cannot find a matching node id, this will return 
+     * <code>null</code>.
+     * @param publicIp public IP of a node.
+     * @return node id of the matching node.
+     */
+    public String getNodeWithPublicIp(String publicIp) {
+
+        InstanceContext ctx;
+
+        for (String ip : publicIpToInstanceCtxt.keySet()) {
+
+            if (ip.equals(publicIp)) {
+
+                ctx = publicIpToInstanceCtxt.get(ip);
+
+                for (String nodeId : nodeIdToInstanceCtxt.keySet()) {
+                    if (ctx.equals(nodeIdToInstanceCtxt.get(nodeId))) {
+                        return nodeId;
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * This will return a list of node Ids that are started in this IaaS and that are 
+     * belong to the given domain, sub domain.
+     * @param domain service domain.
+     * @param subDomain service sub domain.
+     * @return List of node Ids.
+     */
+    public List<String> getNodeIds(String domain, String subDomain) {
+        
+        InstanceContext ctx = getInstanceContext(domain, subDomain);
+        
+        if(ctx == null){
+            return new ArrayList<String>();
+        }
+        
+        return new ArrayList<String>(ctx.getNodeIdToIpMap().keySet());
+        
+
+//        List<String> nodeIds = new ArrayList<String>();
+//
+//        for (Entry<String, String> entry : nodeIdToDomainMap.entrySet()) {
+//            if (entry.getValue().equals(domain)) {
+//                nodeIds.add(entry.getKey());
+//            }
+//        }
+//
+//        return nodeIds;
+    }
+
+    /**
+     * Removes a specific node id and related entries.
+     * @param node id of the node to be removed.
+     */
+    public void removeNodeId(String nodeId) {
+        
+        InstanceContext ctx;
+        
+        if(nodeIdToInstanceCtxt.containsKey(nodeId)){
+            // remove from node id map
+            ctx = nodeIdToInstanceCtxt.remove(nodeId);
+            
+            // remove from public ip map
+            publicIpToInstanceCtxt.remove(ctx.getNodeIdToIpMap().get(nodeId));
+            
+            // remove from main map
+            instanceCtxts.get(ctx.getDomain()).get(ctx.getSubDomain()).removeNode(nodeId);
+            
+        }
+    }
+
+    public boolean equals(Object obj) {
+
+        if (obj instanceof IaasContext) {
+            return new EqualsBuilder().append(getName(), ((IaasContext) obj).getName()).isEquals();
+        }
+        return false;
+
+    }
+    
+    public int hashCode() {
+        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
+        append(name).
+        toHashCode();
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+    
+//    public void setDomainToTemplateMap(Map<String, Template> map) {
+//        domainToTemplateMap = map;
+//    }
+//    
+//    public Map<String, Template> getDomainToTemplateMap() {
+//        return domainToTemplateMap;
+//    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
new file mode 100644
index 0000000..84bb307
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/IaasProvider.java
@@ -0,0 +1,140 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * This is the basic data structure which holds an IaaS specific details.
+ */
+public class IaasProvider {
+    
+    /**
+     * Unique id to identify this IaaS provider.
+     */
+    private String type;
+    
+    /**
+     * human description of this IaaS provider
+     */
+    private String name;
+    
+    /**
+     * Property map for this IaaS provider.
+     */
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    /**
+     * Image identifier.
+     */
+    private String template;
+    
+    /**
+     * Scale up order and scale down order of the IaaS.
+     */
+    private int scaleUpOrder, scaleDownOrder;
+    
+    private String provider, identity, credential;
+    
+//    public enum SortParameter {
+//        SCALE_UP, SCALE_DOWN
+//    }
+
+    
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String id) {
+        this.type = id;
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+    
+    public void setProperty(String key, String value) {
+        
+        if(key != null && value != null){
+            properties.put(key, value);
+        }
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+
+    public String getTemplate() {
+        return template;
+    }
+
+    public void setTemplate(String template) {
+        this.template = template;
+    }
+
+    public int getScaleUpOrder() {
+        return scaleUpOrder;
+    }
+
+    public void setScaleUpOrder(int scaleUpOrder) {
+        this.scaleUpOrder = scaleUpOrder;
+    }
+
+    public int getScaleDownOrder() {
+        return scaleDownOrder;
+    }
+
+    public void setScaleDownOrder(int scaleDownOrder) {
+        this.scaleDownOrder = scaleDownOrder;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getProvider() {
+        return provider;
+    }
+
+    public void setProvider(String provider) {
+        this.provider = provider;
+    }
+
+    public String getIdentity() {
+        return identity;
+    }
+
+    public void setIdentity(String identity) {
+        this.identity = identity;
+    }
+
+    public String getCredential() {
+        return credential;
+    }
+
+    public void setCredential(String credential) {
+        this.credential = credential;
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
new file mode 100644
index 0000000..80f3883
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/InstanceContext.java
@@ -0,0 +1,92 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.io.Serializable;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.jclouds.compute.domain.Template;
+
+/**
+ * This will hold the run-time data related to an instance.
+ * Instance can be an EC2 one, Openstack one etc.
+ */
+public class InstanceContext implements Serializable {
+
+    private static final long serialVersionUID = -2604902942512629140L;
+    private String domain;
+    private String subDomain;
+    private transient Template template;
+
+    /**
+     * Key - node Id
+     * Value - IP
+     */
+    private Map<String, String> nodeIdToIpMap;
+    
+    public InstanceContext(String domain, String subDomain, Template temp) {
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.template = temp;
+        nodeIdToIpMap = new LinkedHashMap<String, String>();
+    }
+//    
+//    public InstanceContext(String domain, String subDomain, Template temp, String nodeId, String publicIp) {
+//        this.domain = domain;
+//        this.subDomain = subDomain;
+//        this.template = temp;
+//        this.nodeId = nodeId;
+//        this.publicIp = publicIp;
+//    }
+
+    
+    public String getDomain() {
+        return domain;
+    }
+
+    public String getSubDomain() {
+        return subDomain;
+    }
+    
+    public Template getTemplate() {
+        return template;
+    }
+    
+    public void setTemplate(Template temp) {
+        this.template = temp;
+    }
+    
+    public void addNode(String nodeId, String ip) {
+        if("".equals(ip)){
+            ip = null;
+        }
+        nodeIdToIpMap.put(nodeId, ip);
+    }
+    
+    public void removeNode(String nodeId) {
+        nodeIdToIpMap.remove(nodeId);
+    }
+
+
+    public Map<String, String> getNodeIdToIpMap() {
+        return nodeIdToIpMap;
+    }
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
new file mode 100644
index 0000000..0dbd6a0
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/util/ServiceTemplate.java
@@ -0,0 +1,83 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.wso2.carbon.lb.common.conf.util.Constants;
+
+/**
+ * We keep details under a service element of jcoluds configuration file,
+ * in this object.
+ */
+public class ServiceTemplate implements Cloneable {
+
+    private String domainName;
+    private String subDomainName = Constants.DEFAULT_SUB_DOMAIN;
+    private Map<String, String> properties = new HashMap<String, String>();
+    
+    public String getDomainName() {
+        return domainName;
+    }
+    
+    public boolean setDomainName(String domainName) {
+        if (!"".equals(domainName)) {
+            this.domainName = domainName;
+            return true;
+        }
+        
+        return false;
+    }
+    
+    public void setProperty(String key, String value) {
+        properties.put(key, value);
+    }
+    
+    public String getProperty(String key) {
+        
+        if(properties.containsKey(key)){
+            return properties.get(key);
+        }
+        
+        return "";
+    }
+
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, String> properties) {
+        this.properties = properties;
+    }
+    
+    public String getSubDomainName() {
+        return subDomainName;
+    }
+
+    public void setSubDomainName(String subDomainName) {
+        if(subDomainName == null || "".equals(subDomainName)){
+            return;
+        }
+        this.subDomainName = subDomainName;
+    }
+    
+    public Object clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
new file mode 100644
index 0000000..325da96
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReader.java
@@ -0,0 +1,556 @@
+/*
+ *  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.autoscaler.service.xml;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.wso2.carbon.autoscaler.service.exception.MalformedConfigurationFileException;
+import org.wso2.carbon.autoscaler.service.util.AutoscalerConstant;
+import org.wso2.carbon.autoscaler.service.util.IaasProvider;
+import org.wso2.carbon.autoscaler.service.util.ServiceTemplate;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.securevault.SecretResolver;
+import org.wso2.securevault.SecretResolverFactory;
+
+/**
+ * Responsible for reading the Elastic scaler configuration file.
+ * Following is a sample XML.
+ *
+ * &lt;elasticScalerConfig&gt;
+ *      &lt;iaasProviders&gt;
+ *          &lt;iaasProvider name="ec2"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;1&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;2&lt;/scaleDownOrder&gt;
+ *              &lt;property name="A" value="a"/&gt;
+ *              &lt;property name="B" value="b"/&gt;
+ *              &lt;template&gt;temp1&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *          
+ *          &lt;iaasProvider name="lxc"&gt;
+ *              &lt;provider&gt;aws-ec2&lt;/provider&gt;
+ *              &lt;identity&gt;aaa&lt;/identity&gt;
+ *              &lt;credential&gt;aaaa&lt;/credential&gt;
+ *              &lt;scaleUpOrder&gt;2&lt;/scaleUpOrder&gt;
+ *              &lt;scaleDownOrder&gt;1&lt;/scaleDownOrder&gt;
+ *              &lt;property name="X" value="x"/&gt;
+ *              &lt;property name="Y" value="y"/&gt;
+ *              &lt;template&gt;temp2&lt;/template&gt;
+ *          &lt;/iaasProvider&gt;
+ *      &lt;/iaasProviders&gt;
+ *      $lt;services&gt;
+ *          $lt;default&gt;
+ *              $lt;property name="availabilityZone" value="us-east-1c"/&gt;
+ *              $lt;property name="securityGroups" value="manager,cep,mb,default"/&gt;
+ *              $lt;property name="instanceType" value="m1.large"/&gt;
+ *              $lt;property name="keyPair" value="aa"/&gt;
+ *          $lt;/default&gt;
+ *          $lt;service domain="wso2.as.domain"&gt;
+ *              $lt;property name="securityGroups" value="manager,default"/&gt;
+ *              $lt;property name="payload" value="resources/as.zip"/&gt;
+ *          $lt;/service&gt;
+ *      $lt;/services&gt;
+ *  &lt;/elasticScalerConfig&gt;
+ */
+public class ElasticScalerConfigFileReader {
+	
+	private static final Log log = LogFactory.getLog(ElasticScalerConfigFileReader.class);
+
+	//get the factory
+	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+	private Document dom;
+	private Element docEle;
+
+	/**
+	 * Path to elastic-scaler-config XML file, which specifies the Iaas specific details and 
+	 * services related details.
+	 */
+	private String elasticScalerConfigFile;
+	
+	
+	public ElasticScalerConfigFileReader(){
+	    
+	    elasticScalerConfigFile = CarbonUtils.getCarbonConfigDirPath() +
+	            File.separator + "elastic-scaler-config.xml";
+	    
+		/**
+		 * Parse the configuration file.
+		 */
+		try {
+			//Using factory, get an instance of document builder
+			DocumentBuilder db = dbf.newDocumentBuilder();
+
+			//parse using builder to get DOM representation of the XML file
+			dom = db.parse(elasticScalerConfigFile);
+			
+
+		}catch(Exception ex) {
+			String msg = "Error occurred while parsing the "+elasticScalerConfigFile+".";
+			handleException(msg, ex);
+		}
+	}
+	
+	/**
+	 * Constructor to be used in the test cases.
+	 * @param file path to elastic-scaler-config xml file.
+	 */
+	public ElasticScalerConfigFileReader(String file) {
+        
+        /**
+         * Parse the configuration file.
+         */
+        try {
+            //Using factory, get an instance of document builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            
+            //parse using builder to get DOM representation of the XML file
+            dom = db.parse(file);
+            
+
+        }catch(Exception ex) {
+            String msg = "Error occurred when parsing the "+file+".";
+            handleException(msg, ex);
+        }
+    }
+	
+	/**
+	 * Returns the serialization directory specified in the configuration file.
+	 * @return the path to the directory or an empty string if element cannot be found.
+	 */
+	public String getSerializationDir() {
+        
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.SERIALIZATION_DIR_ELEMENT);
+
+        // there should be only one serializationDir element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                return prop.getTextContent();
+
+            }
+        }
+        
+        return "";
+    }
+	
+	/**
+	 * Load all IaasProviders from the configuration file and returns a list.
+	 * @return a list of IaasProvider instances.
+	 */
+	public List<IaasProvider> getIaasProvidersList() {
+	    List<IaasProvider> iaasProviders = new ArrayList<IaasProvider>();
+	    
+	    docEle = dom.getDocumentElement();
+	    NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.IAAS_PROVIDER_ELEMENT);
+	    
+	    if (nl != null && nl.getLength() > 0) {
+	        
+	        for(int i=0; i< nl.getLength() ; i++){
+	            iaasProviders.add(getIaasProvider(nl.item(i)));
+	        }
+	        
+	    }
+	    else{
+	        String msg = "Essential '"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element cannot" +
+	        		" be found in "+elasticScalerConfigFile;
+	        handleException(msg);
+	    }
+	    
+	    return iaasProviders;
+	    
+    }
+
+    private IaasProvider getIaasProvider(Node item) {
+
+        IaasProvider iaas = new IaasProvider();
+        
+        if (item.getNodeType() == Node.ELEMENT_NODE) {
+            Element iaasElt = (Element) item;
+            iaas.setType(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR));
+            
+            if("".equals(iaas.getType())){
+                String msg = "'"+AutoscalerConstant.IAAS_PROVIDER_ELEMENT+"' element's '"+
+            AutoscalerConstant.IAAS_PROVIDER_TYPE_ATTR+"' attribute should be specified!";
+                
+                handleException(msg);
+
+            }
+            
+            // this is not mandatory
+            iaas.setName(iaasElt.getAttribute(AutoscalerConstant.IAAS_PROVIDER_NAME_ATTR));
+            
+            iaas.setProperties(loadProperties(iaasElt));
+            loadTemplate(iaas, iaasElt);
+            loadScalingOrders(iaas, iaasElt);
+            loadProvider(iaas, iaasElt);
+            loadIdentity(iaas, iaasElt);
+            loadCredentials(iaas, iaasElt);
+        }
+        
+        
+        return iaas;
+    }
+    
+    /**
+     * Load all ServiceTemplates from the configuration file and returns a list.
+     * @return a list of ServiceTemplate instances.
+     */
+    public List<ServiceTemplate> getTemplates() {
+        
+        List<ServiceTemplate> templates = new ArrayList<ServiceTemplate>();
+        
+        // build default template object
+        ServiceTemplate template = new ServiceTemplate();
+        
+        Element docEle = dom.getDocumentElement();
+        NodeList nl = docEle.getElementsByTagName(AutoscalerConstant.DEFAULT_SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            Node item = nl.item(0);
+
+            if (item.getNodeType() == Node.ELEMENT_NODE) {
+                Element defaultElt = (Element) item;
+                template.setProperties(loadProperties(defaultElt));
+            }
+
+        }
+        
+        // append / overwrite the default template object with values in each domain
+        nl = docEle.getElementsByTagName(AutoscalerConstant.SERVICE_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+
+            for (int i = 0; i < nl.getLength(); i++) {
+                Node item = nl.item(i);
+
+                // clone the default template to an independent object
+                try {
+                    ServiceTemplate temp = (ServiceTemplate) template.clone();
+
+                    if (item.getNodeType() == Node.ELEMENT_NODE) {
+                        Element imageElt = (Element) item;
+
+                        if ("".equals(imageElt.getAttribute(
+                                             AutoscalerConstant.SERVICE_DOMAIN_ATTR))) {
+                            String msg =
+                                "Essential '"+AutoscalerConstant.SERVICE_DOMAIN_ATTR+"' " +
+                                		"attribute of '"+AutoscalerConstant.SERVICE_ELEMENT+
+                                		"' element cannot be found in " + elasticScalerConfigFile;
+
+                            handleException(msg);
+                        }
+
+                        // set domain name
+                        temp.setDomainName(imageElt.getAttribute(AutoscalerConstant.SERVICE_DOMAIN_ATTR));
+                        
+                        // set sub domain
+                        temp.setSubDomainName(imageElt.getAttribute(
+                                              AutoscalerConstant.SERVICE_SUB_DOMAIN_ATTR));
+                        
+                        // load custom properties
+                        Map<String, String> customProperties = loadProperties(imageElt);
+                        
+                        // add custom properties (overwrite default properties where necessary)
+                        for (Entry<String, String> pair : customProperties.entrySet()) {
+                            temp.setProperty(pair.getKey(), pair.getValue());
+                        }
+
+                    }
+                    
+                    // add each domain specific template to list
+                    templates.add(temp);
+
+                } catch (CloneNotSupportedException e) {
+                    String msg = "This is extraordinary!! ";
+                    handleException(msg, e);
+                }
+            }
+        }
+        
+        return templates;
+    }
+    
+    private void loadCredentials(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.CREDENTIAL_ELEMENT);
+
+        // there should be only one credential element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                         AutoscalerConstant.CREDENTIAL_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+
+                // FIXME following is a hack to find the correct alias.
+                if (iaas.getProvider().contains("ec2")) {
+                    alias = AutoscalerConstant.EC2_CREDENTIAL_ALIAS;
+                } else {
+                    alias = AutoscalerConstant.OPENSTACK_CREDENTIAL_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setCredential(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.CREDENTIAL_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadIdentity(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IDENTITY_ELEMENT);
+
+        // there should be only one identity element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IDENTITY_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+
+                // retrieve the value using secure vault
+                SecretResolver secretResolver = SecretResolverFactory.create(docEle, false);
+                String alias;
+                
+                //FIXME following is a hack to find the correct alias.
+                if(iaas.getProvider().contains("ec2")){
+                    alias = AutoscalerConstant.EC2_IDENTITY_ALIAS;
+                }
+                else{
+                    alias = AutoscalerConstant.OPENSTACK_IDENTITY_ALIAS;
+                }
+
+                // retrieve the secured password
+                if (secretResolver != null && secretResolver.isInitialized() && 
+                        secretResolver.isTokenProtected(alias)) {
+
+                    iaas.setIdentity(secretResolver.resolve(alias));
+
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IDENTITY_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadProvider(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROVIDER_ELEMENT);
+
+        // there should be only one provider element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.PROVIDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setProvider(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.PROVIDER_ELEMENT+"' element " +
+            		"has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadScalingOrders(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_UP_ORDER_ELEMENT);
+
+        // there should be only one scaleUpOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleUpOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+" element contained" +
+                    		" in "+elasticScalerConfigFile +"" +
+                    		" has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_UP_ORDER_ELEMENT+"' element" +
+            		" has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+        
+        
+        nl = iaasElt.getElementsByTagName(AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT);
+
+        // there should be only one scaleDownOrder element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                try {
+                    iaas.setScaleDownOrder(Integer.parseInt(prop.getTextContent()));
+                }catch (NumberFormatException e) {
+                    String msg = AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+" element contained" +
+                            " in "+elasticScalerConfigFile +"" +
+                            " has a value which is not an Integer value.";
+                    handleException(msg, e);
+                }
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.SCALE_DOWN_ORDER_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private void loadTemplate(IaasProvider iaas, Element iaasElt) {
+
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.IMAGE_ID_ELEMENT);
+
+        // there should be only one imageId element, we neglect all the others
+        if (nl != null && nl.getLength() > 0) {
+            
+            if (nl.getLength() > 1){
+                log.warn(elasticScalerConfigFile +" contains more than one "+
+                        AutoscalerConstant.IMAGE_ID_ELEMENT+" elements!" +
+                        " Elements other than the first will be neglected.");
+            }
+            
+            if (nl.item(0).getNodeType() == Node.ELEMENT_NODE) {
+                Element prop = (Element) nl.item(0);
+
+                iaas.setTemplate(prop.getTextContent());
+
+            }
+        }
+        else{
+            String msg = "Essential '"+AutoscalerConstant.IMAGE_ID_ELEMENT+"' element" +
+                    " has not specified in "+elasticScalerConfigFile;
+            handleException(msg);
+        }
+    }
+
+    private Map<String, String> loadProperties(Element iaasElt) {
+
+        Map<String, String> propertyMap = new HashMap<String, String>();
+        
+        NodeList nl = iaasElt.getElementsByTagName(AutoscalerConstant.PROPERTY_ELEMENT);
+        
+        if (nl != null && nl.getLength() > 0) {
+            for(int i=0; i< nl.getLength() ; i++){
+                
+                if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
+                    Element prop = (Element) nl.item(i);
+                    
+                    if("".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR)) ||
+                            "".equals(prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR))){
+                        
+                        String msg ="Property element's, name and value attributes should be specified " +
+                        		"in "+elasticScalerConfigFile;
+
+                        handleException(msg);
+                    }
+                    propertyMap.put(prop.getAttribute(AutoscalerConstant.PROPERTY_NAME_ATTR), 
+                                    prop.getAttribute(AutoscalerConstant.PROPERTY_VALUE_ATTR));
+                    
+                }
+            }
+        }
+        
+        return propertyMap;
+    }
+    
+    private void handleException(String msg){
+        log.error(msg);
+        throw new MalformedConfigurationFileException(msg);
+    }
+    
+    private void handleException(String msg, Exception e) {
+        log.error(msg, e);
+        throw new MalformedConfigurationFileException(msg, e);
+    }
+	
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..ae20622
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="AutoscalerService" scope="application">
+        <parameter name="ServiceClass">org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl</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/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
new file mode 100644
index 0000000..946efb6
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextComparatorTest.java
@@ -0,0 +1,97 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.IaasContextComparator;
+import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+
+import junit.framework.TestCase;
+
+public class IaasContextComparatorTest extends TestCase {
+    
+    List<IaasContext> iaasContexts = new ArrayList<IaasContext>();
+    
+    @Override
+    protected void setUp() throws Exception {
+        IaasContext a = new IaasContext(Iaases.ec2, null);
+        a.setScaleUpOrder(1);
+        a.setScaleDownOrder(5);
+        
+        IaasContext b = new IaasContext(Iaases.openstack, null);
+        b.setScaleUpOrder(3);
+        b.setScaleDownOrder(0);
+        
+        iaasContexts.add(a);
+        iaasContexts.add(b);
+        
+        super.setUp();
+    }
+
+    public void testSort() {
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("openstack", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+        IaasContext c = new IaasContext(Iaases.ec2, null);
+        c.setScaleUpOrder(0);
+        c.setScaleDownOrder(4);
+        
+        iaasContexts.add(c);
+        
+        // scale up order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_UP_SORT)));
+        
+        assertEquals("ec2", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        // scale down order sort test
+        Collections.sort(iaasContexts,
+                         IaasContextComparator.ascending(
+                         IaasContextComparator.getComparator(
+                         IaasContextComparator.SCALE_DOWN_SORT)));
+        
+        assertEquals("openstack", iaasContexts.get(0).getName().toString());
+        assertEquals("ec2", iaasContexts.get(1).getName().toString());
+        
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
new file mode 100644
index 0000000..2805d64
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/util/IaasContextTest.java
@@ -0,0 +1,112 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.jclouds.compute.domain.NodeMetadata;
+import org.jclouds.compute.domain.NodeMetadataBuilder;
+import org.wso2.carbon.autoscaler.service.impl.AutoscalerServiceImpl.Iaases;
+import org.wso2.carbon.lb.common.conf.util.Constants;
+
+import junit.framework.TestCase;
+
+public class IaasContextTest extends TestCase {
+
+    IaasContext ctx;
+    NodeMetadata node1, node2, node3, node4;
+    
+    String[] domains = {"wso2.a", "wso2.b", "wso2.c"};
+    String[] subDomains = {"mgt", "worker"};
+    String[] nodeIds = {"1", "2", "3", "4", "5"};
+    String[] ips = {"192.168.1.2", "192.168.1.3", "192.168.1.4"};
+
+    public IaasContextTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        node1 = new NodeMetadataBuilder().id("1")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .publicAddresses(new ArrayList<String>(Arrays.asList("192.168.1.2")))
+                                         .build();
+        node2 = new NodeMetadataBuilder().id("2")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node3 = new NodeMetadataBuilder().id("3")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+        node4 = new NodeMetadataBuilder().id("4")
+                                         .status(org.jclouds.compute.domain.NodeMetadata.Status.RUNNING)
+                                         .build();
+
+        ctx = new IaasContext(Iaases.ec2, null);
+        
+        
+        ctx.addInstanceContext(new InstanceContext(domains[0], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[1], subDomains[1], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], subDomains[0], null));
+        ctx.addInstanceContext(new InstanceContext(domains[2], Constants.DEFAULT_SUB_DOMAIN, null));
+        
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[0], "");
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+        ctx.addNodeDetails(domains[1], subDomains[1], nodeIds[2], ips[1]);
+        ctx.addNodeDetails(domains[2], subDomains[0], nodeIds[3], ips[2]);
+        ctx.addNodeDetails(domains[2], Constants.DEFAULT_SUB_DOMAIN, nodeIds[4], "");
+        
+        
+//        ctx.addNodeIdToDomainMap(node1.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.2", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.2", node1.getId());
+//        ctx.addNodeIdToDomainMap(node2.getId(), "wso2.b");
+//        ctx.addNodeIdToDomainMap(node3.getId(), "wso2.a");
+//        ctx.addPublicIpToDomainMap("192.168.1.3", "wso2.a");
+//        ctx.addPublicIpToNodeIdMap("192.168.1.3", node3.getId());
+//        ctx.addNodeIdToDomainMap(node4.getId(), "wso2.c");
+    }
+
+    public final void testGetLastMatchingNode() {
+
+        assertEquals(nodeIds[1], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.removeNodeId(nodeIds[1]);
+        assertEquals(nodeIds[0], ctx.getLastMatchingNode(domains[0], subDomains[0]));
+        ctx.addNodeDetails(domains[0], subDomains[0], nodeIds[1], ips[0]);
+    }
+
+    public final void testGetFirstMatchingNode() {
+        assertEquals(nodeIds[0], ctx.getFirstMatchingNode(domains[0], subDomains[0]));
+    }
+    
+    public final void testGetLastMatchingPublicIp() {
+        assertEquals(ips[0], ctx.getLastMatchingPublicIp(domains[0], subDomains[0]));
+        assertEquals(null, ctx.getLastMatchingPublicIp(domains[2], Constants.DEFAULT_SUB_DOMAIN));
+    }
+
+    public final void testGetNodeWithPublicIp() {
+        assertEquals(nodeIds[3], ctx.getNodeWithPublicIp(ips[2]));
+    }
+
+    public final void testGetNodeIds() {
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[0], nodeIds[1])), ctx.getNodeIds(domains[0], subDomains[0]));
+        assertEquals(new ArrayList<String>(Arrays.asList(nodeIds[2])), ctx.getNodeIds(domains[1], subDomains[1]));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
new file mode 100644
index 0000000..4a3eb74
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/java/org/wso2/carbon/autoscaler/service/xml/ElasticScalerConfigFileReaderTest.java
@@ -0,0 +1,59 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.autoscaler.service.xml;
+
+import java.util.List;
+import org.wso2.carbon.autoscaler.service.util.IaasProvider;
+import junit.framework.TestCase;
+
+public class ElasticScalerConfigFileReaderTest extends TestCase {
+
+    public void testGetIaasProvidersListy() throws Exception {
+        
+        String file = "src/test/resources/elastic-scaler-config.xml";
+        ElasticScalerConfigFileReader reader = new ElasticScalerConfigFileReader(file);
+        
+        List<IaasProvider> list =reader.getIaasProvidersList();
+        
+        assertEquals(2, list.size());
+        
+        assertEquals("ec2", list.get(0).getType());
+        //assertEquals("cdcd", list.get(0).getIdentity());
+        assertEquals(2, list.get(0).getScaleDownOrder());
+        assertEquals(1, list.get(0).getScaleUpOrder());
+        assertEquals("a", list.get(0).getProperties().get("A.x"));
+        assertEquals("b", list.get(0).getProperties().get("B"));
+        assertEquals(null, list.get(0).getProperties().get("AA"));
+        
+        assertEquals("openstack", list.get(1).getType());
+        //assertEquals("bebbe", list.get(1).getIdentity());
+        assertEquals(1, list.get(1).getScaleDownOrder());
+        assertEquals(2, list.get(1).getScaleUpOrder());
+        assertEquals("x", list.get(1).getProperties().get("X"));
+        assertEquals("y", list.get(1).getProperties().get("Y"));
+        assertEquals(null, list.get(1).getProperties().get("x"));
+        
+        
+        List<org.wso2.carbon.autoscaler.service.util.ServiceTemplate> temps =reader.getTemplates();
+      
+        assertEquals("wso2.as.domain", temps.get(0).getDomainName());
+        assertEquals("manager,default", temps.get(0).getProperty("securityGroups"));
+        
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
new file mode 100644
index 0000000..3ef215e
--- /dev/null
+++ b/components/load-balancer/autoscaler-service/org.wso2.carbon.autoscaler.service/4.1.0/src/test/resources/elastic-scaler-config.xml
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+
+<!--
+  ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+
+<elasticScalerConfig xmlns:svns="http://org.wso2.securevault/configuration">
+
+<svns:secureVault provider="org.wso2.securevault.secret.handler.SecretManagerSecretCallbackHandler"/>
+	<iaasProviders>
+		<iaasProvider type="ec2" name="EC2 specific details">
+			<provider>aws-ec2</provider>
+			<identity svns:secretAlias="elastic.scaler.ec2.identity">cdcd</identity>
+			<credential svns:secretAlias="elastic.scaler.ec2.credential">cdccdc</credential>
+			<scaleUpOrder>1</scaleUpOrder>
+			<scaleDownOrder>2</scaleDownOrder>
+			<property name="A.x" value="a"/>
+			<property name="B" value="b"/>
+			<imageId>tempEC2</imageId>
+		</iaasProvider>
+		<iaasProvider type="openstack" >
+			<provider>lxc</provider>
+			<identity svns:secretAlias="elastic.scaler.openstack.identity">bebbe</identity>
+			<credential svns:secretAlias="elastic.scaler.openstack.credential">bebebe</credential>
+			<scaleUpOrder>2</scaleUpOrder>
+			<scaleDownOrder>1</scaleDownOrder>
+			<property name="X" value="x"/>
+			<property name="Y" value="y"/>
+			<imageId>tempLXC</imageId>
+		</iaasProvider>
+	</iaasProviders>
+	
+	<services>
+		<default>
+			<property name="availabilityZone" value="us-east-1c"/>
+			<property name="securityGroups" value="manager,cep,mb,default"/>
+            <property name="instanceType.ec2" value="m1.large"/>
+            <property name="instanceType.openstack" value="1"/>
+            <property name="minAppInstances" value="1"/>
+            <property name="maxAppInstances" value="5"/>
+            <property name="queueLengthPerNode" value="50"/>
+            <property name="roundsToAverage" value="100"/>
+            <property name="instancesPerScaleUp" value="1"/>
+            <property name="messageExpiryTime" value="60000"/>
+            <property name="keyPair" value="aa"/>
+		</default>
+		<service domain="wso2.as.domain" subDomain="mgt">
+			<property name="securityGroups" value="manager,default"/>
+            <property name="availabilityZone" value="us-east-1c"/>
+            <property name="payload" value="resources/as.zip"/>
+		</service>
+	</services>
+
+</elasticScalerConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
new file mode 100644
index 0000000..842f4cf
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/pom.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+
+
+<!--
+We need to modify this file since this copied from branch
+-->
+<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.wso2.carbon</groupId>
+        <artifactId>loadbalancer-components</artifactId>
+        <version>4.1.0</version>
+        <relativePath>../../../pom.xml</relativePath>
+    </parent>
+
+    <version>4.1.3</version>
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.mediator.autoscale</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Carbon - Autoscale Mediator BE</name>
+    <url>http://wso2.org</url>
+
+    <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>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            !org.wso2.carbon.mediator.autoscale.lbautoscale.internal,
+                            org.wso2.carbon.mediator.autoscale.*
+                        </Export-Package>
+                        <Private-Package>org.wso2.carbon.mediator.autoscale.lbautoscale.internal</Private-Package>
+                        <Import-Package>
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.apache.axis2.*,
+                            org.apache.synapse.*,
+                            org.wso2.carbon.task.*; version=0.0.0,
+                            org.wso2.carbon.core.*,
+                            org.wso2.carbon.lb.common.*,
+                            org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub.*; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            org.apache.axiom.om; version="${axiom.osgi.version.range}",
+                            org.wso2.carbon.stratos.cloud.controller.*,
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+          <groupId>org.apache.axis2.wso2</groupId>
+          <artifactId>axis2</artifactId>
+          <version>1.6.1.wso2v9</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-core</artifactId>
+            <version>2.1.1-wso2v4</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.load.balance.cartridge.autoscaler.service.stub</artifactId>
+            <version>4.1.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.cloud.controller</artifactId>
+            <version>2.1.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.task</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+            <version>2.1.1-wso2v4</version>
+        </dependency>
+
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
----------------------------------------------------------------------
diff --git a/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
new file mode 100644
index 0000000..4f21a85
--- /dev/null
+++ b/components/load-balancer/autoscaler/org.wso2.carbon.mediator.autoscale/4.1.3/src/main/java/org/wso2/carbon/mediator/autoscale/lbautoscale/callables/AppNodeSanityCheckCallable.java
@@ -0,0 +1,84 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.mediator.autoscale.lbautoscale.callables;
+
+import java.util.concurrent.Callable;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.clients.CloudControllerClient;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.context.AppDomainContext;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscaleUtil;
+import org.wso2.carbon.mediator.autoscale.lbautoscale.util.AutoscalerTaskDSHolder;
+
+/** Performing sanity checks for each service domain, sub domain combination **/
+public class AppNodeSanityCheckCallable implements Callable<Boolean> {
+
+    private static final Log log = LogFactory.getLog(AppNodeSanityCheckCallable.class);
+    private String domain;
+    private String subDomain;
+    private CloudControllerClient client;
+    private AppDomainContext appDomainContext;
+    private ServiceConfiguration serviceConfig;
+    
+    public AppNodeSanityCheckCallable(String domain, String subDomain, CloudControllerClient client, AppDomainContext appCtxt){
+        this.domain = domain;
+        this.subDomain = subDomain;
+        this.client = client;
+        this.appDomainContext = appCtxt;
+        serviceConfig =
+                AutoscalerTaskDSHolder.getInstance().getWholeLoadBalancerConfig().getServiceConfig(this.domain,
+                    this.subDomain);
+    }
+    
+    @Override
+    public Boolean call() throws Exception {
+
+        if (appDomainContext != null) {
+            int currentInstances = 0;
+            // we're considering both running and pending instance count
+            currentInstances = appDomainContext.getInstances();
+
+            int requiredInstances = serviceConfig.getMinAppInstances();
+
+            // we try to maintain the minimum number of instances required
+            if (currentInstances < requiredInstances) {
+                log.debug("App domain Sanity check failed for " +
+                    AutoscaleUtil.domainSubDomainString(domain, subDomain) +
+                        " . Current instances: " +
+                        currentInstances +
+                        ". Required instances: " +
+                        requiredInstances);
+
+                int diff = requiredInstances - currentInstances;
+
+                // Launch diff number of App instances
+                log.debug("Launching " +
+                    diff +
+                    " App instances for " +AutoscaleUtil.domainSubDomainString(domain, subDomain));
+
+                // FIXME: should we need to consider serviceConfig.getInstancesPerScaleUp()?
+                AutoscaleUtil.runInstances(client, appDomainContext, this.domain, this.subDomain, diff);
+            }
+        }
+
+        return true;
+    }
+
+}


[29/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
new file mode 100644
index 0000000..a523b60
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A class to handle multiple billing engines
+ */
+public class BillingManager {
+    private static final Log log = LogFactory.getLog(BillingManager.class);
+    private static BillingManager billingManager;
+    private BillingConfiguration billingConfiguration;
+    private DataAccessObject dataAccessObject;
+    private Map<String, BillingEngine> billingEngines = new HashMap<String, BillingEngine>();
+
+    public static BillingManager getInstance() throws BillingException {
+        if (billingManager == null) {
+            String msg = "Billing Manager is not initialized.";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        return billingManager;
+    }
+
+    public static void destroyInstance() {
+        billingManager = null;
+    }
+
+    public BillingManager(BillingConfiguration billingConfiguration) throws BillingException {
+        if (billingManager != null) {
+            String msg = "Billing Manager should not be initialized twice";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        this.billingConfiguration = billingConfiguration;
+        this.dataAccessObject = new DataAccessObject(billingConfiguration.getDataSource());
+        //Create billing engine corresponds to given billingTaskConfigurations
+        Map<String, BillingTaskConfiguration> billingTaskConfigs =
+                billingConfiguration.getBillingTaskConfigs();
+        for (Map.Entry<String, BillingTaskConfiguration> entry : billingTaskConfigs.entrySet()) {
+            String billingTaskName = entry.getKey();
+            BillingTaskConfiguration billingTaskConfiguration = entry.getValue();
+            BillingEngine billingEngine =
+                    new BillingEngine(billingTaskConfiguration, dataAccessObject);
+            billingEngines.put(billingTaskName, billingEngine);
+        }
+        billingManager = this;
+    }
+
+    public BillingConfiguration getBillingConfiguration() {
+        return billingConfiguration;
+    }
+
+    public DataAccessObject getDataAccessObject() {
+        return dataAccessObject;
+    }
+
+    public BillingEngine getBillingEngine(String billingTaskName) {
+        return billingEngines.get(billingTaskName);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
new file mode 100644
index 0000000..403938f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
@@ -0,0 +1,203 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+
+public class BillingTenantMgtListenerImpl implements TenantMgtListener{
+
+    private static Log log = LogFactory.getLog(BillingTenantMgtListenerImpl.class);
+    /**
+     * Adds the subscription entry when the tenant is created
+     * @param tenantInfo Tenant information
+     * @throws StratosException if adding subscription failed
+     */
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException {
+        Customer customer = new Customer();
+        customer.setName(tenantInfo.getTenantDomain());
+        customer.setEmail(tenantInfo.getEmail());
+        customer.setStartedDate(new Date(tenantInfo.getCreatedDate().getTimeInMillis()));
+        customer.setFullName(tenantInfo.getFirstname() + " " + tenantInfo.getLastname());
+
+        customer.setId(tenantInfo.getTenantId());
+        Subscription subscription = new Subscription();
+        subscription.setCustomer(customer);
+        subscription.setActive(false);
+        subscription.setActiveSince(Calendar.getInstance().getTime());
+        subscription.setItem(new Item());
+        subscription.setSubscriptionPlan(tenantInfo.getUsagePlan());
+        try {
+            Util.getDataAccessManager().addSubscription(subscription);
+        } catch (Exception e) {
+            String msg = "Could not add new subscription for tenant: " +tenantInfo.getTenantDomain();
+            log.error( msg + e.getMessage(), e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException {
+        try {
+            if (tenantInfo.getUsagePlan() == null) {
+                return;
+            }
+            Subscription currentSubscription = Util.getDataAccessManager().
+                    getActiveSubscriptionOfCustomer(tenantInfo.getTenantId());
+            if (currentSubscription != null && currentSubscription.getSubscriptionPlan() != null) {
+                if (!currentSubscription.getSubscriptionPlan().equals(tenantInfo.getUsagePlan())) {
+                    boolean updated = Util.getDataAccessManager().
+                            changeSubscription(tenantInfo.getTenantId(), tenantInfo.getUsagePlan());
+                    if (updated) {
+                        log.info("Usage plan was changed successfully from " + currentSubscription.getSubscriptionPlan() +
+                                " to " + tenantInfo.getUsagePlan());
+                    }
+                }
+            }else{
+                //tenant does not have an active subscription. First we have to check whether the tenant
+                //is active. If he is active only we will add a new usage plan. Otherwise it is useless
+                //to add a usage plan to an inactive tenant
+                TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
+                Tenant tenant = tenantManager.getTenant(tenantInfo.getTenantId());
+                if(tenant.isActive()){
+                    //we add a new subscription
+                    Subscription subscription = new Subscription();
+                    subscription.setActive(true);
+                    subscription.setSubscriptionPlan(tenantInfo.getUsagePlan());
+                    subscription.setActiveSince(null);
+                    subscription.setActiveUntil(null);
+                    Customer customer = new Customer();
+                    customer.setName(tenantInfo.getTenantDomain());
+                    customer.setId(tenantInfo.getTenantId());
+                    subscription.setCustomer(customer);
+
+                    int subsId = Util.getDataAccessManager().addSubscription(subscription);
+                    if(subsId>0){
+                        log.info("Added a new " + subscription.getSubscriptionPlan() + " usage plan for the tenant " +
+                                tenantInfo.getTenantDomain());
+                    }
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while changing the subscription plan for tenant: " + tenantInfo.getTenantDomain();
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantRename(int tenantId, String oldDomainName, String newDomainName) throws StratosException {
+        //Nothing to be done
+    }
+
+    public void onTenantInitialActivation(int tenantId) throws StratosException {
+        onTenantActivation(tenantId);
+    }
+
+    public void onTenantActivation(int tenantId) throws StratosException {
+        //On tenant activation we need to activate the subscription
+
+        try {
+
+            Subscription subscription = Util.getDataAccessManager().getActiveSubscriptionOfCustomer(tenantId);
+
+            if (subscription != null) {
+                String msg = "Unable to activate the subscription for tenant: " + tenantId +
+                        ". An active subscription already exists";
+                log.info(msg);
+            } else {
+                List<Subscription> inactiveSubscriptions = Util.getDataAccessManager().getInactiveSubscriptionsOfCustomer(tenantId);
+                if (inactiveSubscriptions.size() == 1) {
+                    //This is the scenario where the tenant has registered, but not activated yet
+                    subscription = inactiveSubscriptions.get(0);
+                    boolean activated = Util.getDataAccessManager().activateSubscription(subscription.getId());
+                    if (activated) {
+                        log.info("Subscription was activated for tenant: " + tenantId);
+                    }
+                }else if(inactiveSubscriptions.size() > 1){
+                    //this is the scenario where the tenant has been deactivated by admin and
+                    //again activated. Here, I am adding a new active subscription which is similar to the
+                    //last existed one
+                    //inactiveSubscriptions.get(0) gives the latest inactive subscription
+                    Subscription subscriptionToAdd = inactiveSubscriptions.get(0);
+                    subscriptionToAdd.setActive(true);
+                    subscriptionToAdd.setActiveSince(null);
+                    subscriptionToAdd.setActiveUntil(null);
+
+                    int subsId = Util.getDataAccessManager().addSubscription(subscriptionToAdd);
+                    if(subsId>0){
+                        log.info("New subscription: " + subscriptionToAdd.getSubscriptionPlan() +
+                                " added and it was activated for tenant: " + tenantId);
+                    }
+                }else{
+                    //this means there are no subscriptions. Lets handle this later
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while activating the subscription for tenant: " +
+                    tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantDeactivation(int tenantId) throws StratosException {
+        try{
+            Subscription currentActiveSubscription = Util.getDataAccessManager().getActiveSubscriptionOfCustomer(tenantId);
+            if(currentActiveSubscription==null){
+                String msg = "There is no active subscription to deactivate for tenant: " +
+                        tenantId + " on tenant deactivation";
+                log.info(msg);
+            }else {
+                boolean deactivated = Util.getDataAccessManager().deactivateActiveSubscription(tenantId);
+                if(deactivated){
+                    log.info("Subscription deactivated on tenant deactivation");
+                }else{
+                    log.info("Subscription was not deactivated on tenant deactivation");
+                }
+            }
+        } catch (Exception e){
+            String msg = "Error occurred while deactivating the active subscription for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, String newPlan) throws StratosException {
+        //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    public int getListenerOrder() {
+        return 0;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
new file mode 100644
index 0000000..89cce4c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.List;
+
+
+public class DataAccessManager {
+
+    private static Log log = LogFactory.getLog(DataAccessManager.class);
+    private DataAccessObject dataAccessObject = null;
+
+    public DataAccessManager(DataSource dataSource) {
+        this.dataAccessObject = new DataAccessObject(dataSource);
+    }
+    
+    public DataAccessManager(DataAccessObject dao){
+        this.dataAccessObject = dao;
+    }
+
+    public void beginTransaction() throws BillingException {
+        dataAccessObject.beginTransaction();
+    }
+
+    public void commitTransaction() throws BillingException {
+        dataAccessObject.commitTransaction();
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        dataAccessObject.rollbackTransaction();
+    }
+
+    public int addSubscription(Subscription subscription) throws BillingException {
+        int subscriptionId = 0;
+        try {
+            beginTransaction();
+            subscriptionId = dataAccessObject.addSubscription(subscription,
+                                subscription.getSubscriptionPlan());
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding subscription: " + subscription.getSubscriptionPlan()+
+                            " for the customer " + subscription.getCustomer().getName() + " " + e.getMessage() ;
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptionId;
+    }
+
+    public void deleteBillingData(int tenantId) throws BillingException {
+        try {
+            beginTransaction();
+            dataAccessObject.deleteBillingData(tenantId);
+            commitTransaction();
+        } catch (Exception e) {
+            rollbackTransaction();
+            String msg = "Error occurred while deleting subscription for tenant id: " + tenantId ;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try {
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if (tenant != null) {
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        } catch (Exception e) {
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public Subscription getSubscription(int subscriptionId) throws BillingException {
+        Subscription subscription = null;
+        try {
+            beginTransaction();
+            subscription = dataAccessObject.getSubscription(subscriptionId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting subscription with id: " + subscriptionId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public Subscription getActiveSubscriptionOfCustomer(int customerId) throws BillingException {
+        Subscription subscription;
+        try {
+            beginTransaction();
+            subscription = dataAccessObject.getActiveSubscriptionOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscription for customer: "
+                            + customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public int getItemIdWithName(String name, int parentId) throws BillingException {
+        int itemId;
+        try {
+            beginTransaction();
+            itemId = dataAccessObject.getItemId(name, parentId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item id for item name: " + name +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return itemId;
+    }
+
+    public boolean changeSubscription(int customerId, String subscriptionPlan) throws BillingException {
+        boolean changed = false;
+        String oldSubscriptionPlan = null;
+
+        try {
+            beginTransaction();
+            Subscription oldSubscription = getActiveSubscriptionOfCustomer(customerId);
+            if(oldSubscription!=null){
+                oldSubscriptionPlan = oldSubscription.getSubscriptionPlan();
+            }
+            changed = dataAccessObject.changeSubscription(customerId, subscriptionPlan);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while changing subscription to: " + subscriptionPlan +
+                            " for customer: " + customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+
+        try {
+            // Notify Listeners about the subscription change
+            Util.alertTenantSubscriptionPlanChange(
+                    customerId, oldSubscriptionPlan, subscriptionPlan);
+        } catch (StratosException e) {
+            log.error(e.getMessage(), e);
+            throw new BillingException(e.getMessage(), e);
+        }
+
+        return changed;
+    }
+
+    public List<Subscription> getInactiveSubscriptionsOfCustomer(int customerId) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions = dataAccessObject.getInactiveSubscriptionsOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting inactive subscriptions of customer: " +
+                            customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+
+    }
+
+    public boolean activateSubscription(int subscriptionId) throws BillingException {
+        boolean activated = false;
+        try {
+            beginTransaction();
+            activated = dataAccessObject.activateSubscription(subscriptionId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while activating subscription with id: " + subscriptionId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return activated;
+    }
+
+    public boolean deactivateActiveSubscription(int tenantId) throws BillingException {
+        boolean deactivated = false;
+        try{
+            beginTransaction();
+            deactivated = dataAccessObject.deactivateCurrentSubscriptoin(tenantId);
+            commitTransaction();
+        }catch(Exception e){
+            rollbackTransaction();
+            String msg = "Error occurred while deactivating the active subscription of customer: " +
+                            tenantId;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return deactivated;
+    }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
new file mode 100644
index 0000000..04260fd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.beans;
+
+import java.util.Date;
+
+/**
+ * This class holds the data to be shown in the invoice summary page of all
+ * tenants
+ */
+public class OutstandingBalanceInfoBean {
+
+    private int invoiceId;
+    private String customerName;
+    private String subscription;
+    private String carriedForward;
+    private Date lastPaymentDate;
+    private Date lastInvoiceDate;
+    private String lastPaidAmount;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public String getCustomerName() {
+        return customerName;
+    }
+
+    public void setCustomerName(String customerName) {
+        this.customerName = customerName;
+    }
+
+    public String getSubscription() {
+        return subscription;
+    }
+
+    public void setSubscription(String subscription) {
+        this.subscription = subscription;
+    }
+
+    public String getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(String carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public Date getLastPaymentDate() {
+        return lastPaymentDate;
+    }
+
+    public void setLastPaymentDate(Date lastPaymentDate) {
+        this.lastPaymentDate = lastPaymentDate;
+    }
+
+    public String getLastPaidAmount() {
+        return lastPaidAmount;
+    }
+
+    public void setLastPaidAmount(String lastPaidAmount) {
+        this.lastPaidAmount = lastPaidAmount;
+    }
+
+    public Date getLastInvoiceDate() {
+        return lastInvoiceDate;
+    }
+
+    public void setLastInvoiceDate(Date lastInvoiceDate) {
+        this.lastInvoiceDate = lastInvoiceDate;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
new file mode 100644
index 0000000..68e968e
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
@@ -0,0 +1,52 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.beans;
+
+import org.wso2.carbon.utils.Pageable;
+
+import java.util.List;
+
+/**
+ * Class used paginating the invoice summaries of all tenants
+ */
+public class PaginatedBalanceInfoBean implements Pageable {
+
+    private OutstandingBalanceInfoBean[] balanceInfoBeans;
+    private int numberOfPages;
+
+    public OutstandingBalanceInfoBean[] getBalanceInfoBeans() {
+        return balanceInfoBeans;
+    }
+
+    public void setBalanceInfoBeans(OutstandingBalanceInfoBean[] balanceInfoBeans) {
+        this.balanceInfoBeans = balanceInfoBeans;
+    }
+
+    public int getNumberOfPages() {
+        return numberOfPages;
+    }
+
+    public void setNumberOfPages(int numberOfPages) {
+        this.numberOfPages = numberOfPages;
+    }
+
+    public <T> void set(List<T> items) {
+        this.balanceInfoBeans =
+                items.toArray(new OutstandingBalanceInfoBean[items.size()]);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
new file mode 100644
index 0000000..0027f16
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.conf;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.ndatasource.common.DataSourceException;
+
+import javax.sql.DataSource;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * This class reads the billing-config.xml file and
+ * keeps the billing task configurations in a map.
+ * There are two configurations, one for scheduled bill generation
+ * and the other for on-demand bill generation
+ */
+public class BillingConfiguration {
+    private static final Log log = LogFactory.getLog(BillingConfiguration.class);
+    DataSource dataSource;
+    Map<String, BillingTaskConfiguration> billingTaskConfigs = new HashMap<String, BillingTaskConfiguration>();
+
+    public BillingConfiguration(String billingConfigFile) throws BillingException {
+        try {
+            dataSource = (DataSource) Util.getDataSourceService().getDataSource(BillingConstants.WSO2_BILLING_DS).getDSObject();
+            OMElement billingConfig = buildOMElement(new FileInputStream(billingConfigFile));
+            deserialize(billingConfig);
+        } catch (FileNotFoundException e) {
+            String msg = "Unable to find the file responsible for billing task configs: "
+                            + billingConfigFile;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } catch (DataSourceException e) {
+            String msg = "Error retrieving Billing datasource from master-datasources.xml configuration.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    private OMElement buildOMElement(InputStream inputStream) throws BillingException {
+        XMLStreamReader parser;
+        try {
+            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+        } catch (XMLStreamException e) {
+            String msg = "Error in initializing the parser to build the OMElement.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+        return builder.getDocumentElement();
+    }
+    
+    /*
+       Deserialize the following
+       <billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+           <dbConfig>
+                ...
+           </dbConfig>
+           <tasks>
+                <task id="multitenancyScheduledTask">
+                    ...
+                </task>
+                <task id="multitenancyViewingTask">
+                    ...
+                </task>
+            </tasks>
+        </billingConfig>
+     */
+    private void deserialize(OMElement billingConfigEle) throws BillingException {
+        Iterator billingConfigChildIt = billingConfigEle.getChildElements();
+        
+        while (billingConfigChildIt.hasNext()) {
+            OMElement billingConfigChildEle = (OMElement) billingConfigChildIt.next();
+            
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.TASKS,
+                    BillingConstants.NS_PREFIX).equals(billingConfigChildEle.getQName())) {
+                //element is "tasks"
+                Iterator taskConfigChildIt = billingConfigChildEle.getChildElements();
+                while (taskConfigChildIt.hasNext()) {
+                    OMElement taskConfigEle = (OMElement) taskConfigChildIt.next();
+                    String id = taskConfigEle.getAttributeValue(new QName(BillingConstants.ATTR_ID));
+                    BillingTaskConfiguration taskConfig =
+                            new BillingTaskConfiguration(id, taskConfigEle);
+                    billingTaskConfigs.put(id, taskConfig);
+                }
+            } else {
+                String msg = "Unknown element in Billing Configuration: " +
+                                billingConfigChildEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }
+
+    /*
+     * Deserialise dbConfigElement (Given below) and initialize data source
+        <dbConfig>
+            <url>jdbc:mysql://localhost:3306/billing</url>
+            <userName>billing</userName>
+            <password>billing</password>
+            <driverName>com.mysql.jdbc.Driver</driverName>
+            <maxActive>80</maxActive>
+            <maxWait>60000</maxWait>
+            <minIdle>5</minIdle>
+            <validationQuery>SELECT 1</validationQuery>
+        </dbConfig>
+     */
+    /*private void initDataSource(OMElement dbConfigEle) throws BillingException {
+        // initializing the data source and load the database configurations
+        Iterator dbConfigChildIt = dbConfigEle.getChildElements();
+        dataSource = new BasicDataSource();
+        
+        while (dbConfigChildIt.hasNext()) {
+            
+            OMElement dbConfigChildEle = (OMElement) dbConfigChildIt.next();
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_URL,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setUrl(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_USER_NAME,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setUsername(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_PASSWORD,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setPassword(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_DRIVER_NAME,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setDriverClassName(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MAX_ACTIVE,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMaxActive(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MAX_WAIT,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMaxWait(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MIN_IDLE,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMinIdle(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, 
+                    BillingConstants.DBCONFIG_VALIDATION_QUERY, BillingConstants.NS_PREFIX)
+                    .equals(dbConfigChildEle.getQName())) {
+                dataSource.setValidationQuery(dbConfigChildEle.getText());
+            } else {
+                String msg = "Unknown element in DBConfig of Billing Configuration: " +
+                                dbConfigChildEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }*/
+
+    public Map<String, BillingTaskConfiguration> getBillingTaskConfigs() {
+        return billingTaskConfigs;
+    }
+
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
new file mode 100644
index 0000000..5530ed1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.conf;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+
+import javax.xml.namespace.QName;
+import java.util.*;
+
+public class BillingTaskConfiguration {
+    private static final Log log = LogFactory.getLog(BillingTaskConfiguration.class);
+
+    private String id;
+    private ScheduleHelper scheduleHelper = null;
+    private Map<String, String> schedulerHelperArgs;
+    private String schedulerServiceName;
+
+    private List<BillingHandler> billingHandlers = new ArrayList<BillingHandler>();
+    private List<HandlerConfigBean> handlerArgs = new ArrayList<HandlerConfigBean>(); //key - handler service name
+    private static Map<String, ScheduleHelper> schedulerServices =
+            new HashMap<String, ScheduleHelper>(); 
+    private static Map<String, BillingHandler> handlerServices =
+            new HashMap<String, BillingHandler>();
+
+    private class HandlerConfigBean {
+        public String name;
+        public boolean isServiceType;
+        public Map<String, String> constructorArgs;
+
+        public HandlerConfigBean(String name, boolean isServiceType, Map<String, String> constructorArgs){
+            this.name = name;
+            this.isServiceType = isServiceType;
+            this.constructorArgs = constructorArgs;
+        }
+    }
+
+    public BillingTaskConfiguration(String id, OMElement billingConfigEle) throws BillingException {
+        this.id = id;
+        deserialize(billingConfigEle);
+    }
+
+    /*
+     *  Deserialize following and creates tasks
+        <task id="multitenancyScheduledTask">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule scheduleHelperClass="package.ClassName">
+                ...
+            </schedule>
+            <handlers>
+                ...
+            </handlers>
+        </task>
+     */
+    private void deserialize(OMElement taskConfigEle) throws BillingException {
+        Iterator billingConfigChildIt = taskConfigEle.getChildElements();
+        
+        while (billingConfigChildIt.hasNext()) {
+            OMElement childEle = (OMElement) billingConfigChildIt.next();
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.SCHEDULE_CONF_KEY,
+                    BillingConstants.NS_PREFIX).equals(childEle.getQName())) {
+                deserializeSchedule(childEle);
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.HANDLERS,
+                    BillingConstants.NS_PREFIX).equals(childEle.getQName())) {
+                deserializeHandlers(childEle);
+            } else {
+                String msg = "Unknown element in task configuration for task " + id +
+                                ": " + childEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }
+
+    /*
+        <handlers>
+            <handler service="serviceName">
+            </handler>
+            <handler class="org.wso2.carbon.billing.core.handlers.EmailSendingHandler">
+                <parameter name="file">email-billing-notifications.xml</parameter>
+            </handler>
+        </handlers>
+     */
+    private void deserializeHandlers(OMElement handlersEle) throws BillingException {
+        // iterate through each billingHandlers
+        Iterator handlersChildIt = handlersEle.getChildElements();
+        
+        while (handlersChildIt.hasNext()) {
+            OMElement handlerEle = (OMElement) handlersChildIt.next();
+            if (!(new QName(BillingConstants.CONFIG_NS, BillingConstants.HANDLER,
+                    BillingConstants.NS_PREFIX).equals(handlerEle.getQName()))) {
+                String msg = "Unknown element in handler configuration for task " + id +
+                                ": " + handlerEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+
+            // get the parameters for handler
+            Iterator handlerParametersIt = handlerEle.getChildElements();
+            Map<String, String> constructorArgs = extractConstructorArgs(handlerParametersIt);
+            String handlerClassName =
+                    handlerEle.getAttributeValue(new QName(BillingConstants.HANDLER_CLASS_ATTR));
+            if (handlerClassName == null) {
+                // className is not given. So, it uses a handlerService
+                String handlerServiceName = handlerEle.getAttributeValue(
+                        new QName(BillingConstants.HANDLER_SERVICE_ATTR));
+                HandlerConfigBean bean = new HandlerConfigBean(handlerServiceName, true, constructorArgs);
+                handlerArgs.add(bean);
+            } else {
+                HandlerConfigBean bean = new HandlerConfigBean(handlerClassName, false, constructorArgs);
+                handlerArgs.add(bean);
+            }
+        }
+    }
+
+    /* 
+     * Deserialize following and creates scheduleHelper
+        <schedule scheduleHelperClass="package.ClassName">
+            <parameter name="dayToTriggerOn">1</parameter>
+            <parameter name="hourToTriggerOn">0</parameter>
+            <parameter name="timeZone">GMT-8:00</parameter>
+        </schedule>
+     */
+    private void deserializeSchedule(OMElement scheduleEle) throws BillingException {
+        Iterator scheduleHelperConfigChildIt = scheduleEle.getChildElements();
+        Map<String, String> constructorArgs = extractConstructorArgs(scheduleHelperConfigChildIt);
+        
+        // get the scheduleHelper class name
+        String className = scheduleEle.getAttributeValue(
+                new QName(BillingConstants.TRIGGER_CALCULATOR_CLASS_ATTR));
+        
+        if (className == null) {
+            //className is not given; it is using scheduler service
+            schedulerServiceName = scheduleEle.getAttributeValue(
+                    new QName(BillingConstants.TRIGGER_CALCULATOR_SERVICE_ATTR));
+            schedulerHelperArgs = constructorArgs;
+        } else {
+            //className is given; Construct the object
+            scheduleHelper = (ScheduleHelper) constructObject(className);
+            scheduleHelper.init(constructorArgs);
+        }
+    }
+
+    public ScheduleHelper getScheduleHelper() throws BillingException {
+        if (scheduleHelper == null && schedulerServiceName != null) {
+            scheduleHelper = schedulerServices.get(schedulerServiceName);
+            if (scheduleHelper == null) {
+                String msg = "The scheduler helper service: " + schedulerServiceName +
+                                " is not loaded.";
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+            scheduleHelper.init(schedulerHelperArgs);
+        }
+        return scheduleHelper;
+    }
+
+    public List<BillingHandler> getBillingHandlers() throws BillingException {
+        // We have to combine the handlers and handlerServices as a single list and return. When
+        // creating and initializing handerServices, remove them from the handelerArgs so that they
+        // will be included only once
+        if(!handlerArgs.isEmpty()){
+            for(HandlerConfigBean bean : handlerArgs){
+                if(bean.isServiceType){
+                    BillingHandler handlerService = handlerServices.get(bean.name);
+                    if (handlerService == null) {
+                        billingHandlers = null;
+                        String msg = "The handler service: " + bean.name + " is not loaded.";
+                        log.error(msg);
+                        throw new BillingException(msg);
+                    }
+                    handlerService.init(bean.constructorArgs);
+                    billingHandlers.add(handlerService);
+
+                } else {
+                    BillingHandler handler = (BillingHandler) constructObject(bean.name);
+                    handler.init(bean.constructorArgs);
+                    billingHandlers.add(handler);
+                }
+            }
+
+            //all the billing handler services are initialized properly, can clear handlerArgs
+            handlerArgs.clear();
+        }
+        return billingHandlers;
+    }
+
+    private static Object constructObject(String className) throws BillingException {
+        try {
+            return Class.forName(className).newInstance();
+        } catch (ClassNotFoundException e) {
+            String msg = "The class: " + className + " is not in the classpath.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } catch (Exception e) {
+            String msg = "Error in initializing the object for " + className + ".";
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    private static Map<String, String> extractConstructorArgs(Iterator parameterIt) {
+        Map<String, String> constructorArgs = new HashMap<String, String>();
+        
+        while (parameterIt.hasNext()) {
+            OMElement paramEle = (OMElement) parameterIt.next();
+            if (!new QName(BillingConstants.CONFIG_NS, BillingConstants.SCHEDULE_CONF_PARAM_KEY,
+                    BillingConstants.NS_PREFIX).equals(paramEle.getQName())) {
+                continue;
+            }
+            
+            String paramName = paramEle.getAttributeValue(
+                    new QName(BillingConstants.SCHEDULE_CONF_PARAM_NAME_KEY));
+            String paramValue = paramEle.getText();
+            constructorArgs.put(paramName, paramValue);
+        }
+        return constructorArgs;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    // the following two methods will be called when the services are available for the schedule
+    // helper and the billing handlers
+    public static void addScheduleHelper(ScheduleHelper scheduleHelper) {
+        schedulerServices.put(scheduleHelper.getClass().getName(), scheduleHelper);
+    }
+
+    public static void addBillingHandler(BillingHandler billingHandler) {
+        handlerServices.put(billingHandler.getClass().getName(), billingHandler);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
new file mode 100644
index 0000000..e9d760a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import org.wso2.carbon.billing.core.BillingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.regex.Pattern;
+
+
+public class Cash {
+    private static final Log log = LogFactory.getLog(Cash.class);
+    public static final String CURRENCY_USD = "$";
+    public static final String DEFAULT_CURRENCY = CURRENCY_USD;
+
+    public enum Sign {
+        POSITIVE, NEGATIVE
+    };
+
+    String currency;
+    int wholeNumber;
+    int decimalNumber;
+    Sign sign = Sign.POSITIVE; // true for positive
+
+    private static final String notNumbersRegEx = "[^0-9]";
+    private static final Pattern notNumbersPattern = Pattern.compile(notNumbersRegEx);
+
+    public Cash() {
+        // the default constructor for Cash
+    }
+
+    public Cash(Cash copyFrom) {
+        this.currency = copyFrom.getCurrency();
+        this.wholeNumber = copyFrom.getWholeNumber();
+        this.decimalNumber = copyFrom.getDecimalNumber();
+        this.sign = copyFrom.getSign();
+    }
+
+    public Cash(String cashString) throws BillingException {
+        if (cashString == null) {
+            cashString = "$0";
+        }
+        if (cashString.startsWith(CURRENCY_USD)) {
+            cashString = cashString.substring(CURRENCY_USD.length());
+            currency = CURRENCY_USD;
+        }
+        // possible other currencies
+        else {
+            currency = DEFAULT_CURRENCY;
+        }
+
+        if (cashString.startsWith("-")) {
+            sign = Sign.NEGATIVE;
+            cashString = cashString.substring(1);
+        } else if (cashString.startsWith("+")) {
+            sign = Sign.POSITIVE;
+            cashString = cashString.substring(1);
+        } else {
+            sign = Sign.POSITIVE;
+        }
+
+        if (cashString.contains(".")) {
+            String wholeNumberStr = cashString.substring(0, cashString.indexOf("."));
+            if (wholeNumberStr.trim().equals("")) {
+                String msg = "Whole number can not be empty";
+                throw new BillingException(msg);
+            }
+            if (notNumbersPattern.matcher(wholeNumberStr).find()) {
+                String msg = "The whole number expected to have only 0-9 characters.: " +
+                                wholeNumberStr + " is not a number. ";
+                throw new BillingException(msg);
+            }
+            
+            String decimalNumberStr = cashString.substring(cashString.indexOf(".") + 1);
+            if (notNumbersPattern.matcher(decimalNumberStr).find()) {
+                String msg = "The decimal number expected to have only 0-9 characters.: " +
+                                decimalNumberStr + " is not a number. ";
+                throw new BillingException(msg);
+            }
+            if (decimalNumberStr.length() == 0) {
+                String msg = "String after the decimal point is zero.";
+                throw new BillingException(msg);
+            } else if (decimalNumberStr.length() > 2) {
+                String msg = "String after the decimal point is greater than 2";
+                throw new BillingException(msg);
+            } else if (decimalNumberStr.length() == 1) {
+                decimalNumberStr += "0";
+            }
+            
+            wholeNumber = Integer.parseInt(wholeNumberStr);
+            decimalNumber = Integer.parseInt(decimalNumberStr);
+            
+        } else {
+            if (notNumbersPattern.matcher(cashString).find()) {
+                String msg = "The cash string to have only 0-9 characters.: " + cashString +
+                                " is not a number. ";
+                throw new BillingException(msg);
+            }
+            
+            wholeNumber = Integer.parseInt(cashString);
+            decimalNumber = 0;
+        }
+    }
+
+    public Sign getSign() {
+        return sign;
+    }
+
+    public void setSign(Sign sign) {
+        this.sign = sign;
+    }
+
+    public String getCurrency() {
+        return currency;
+    }
+
+    public void setCurrency(String currency) {
+        this.currency = currency;
+    }
+
+    public int getWholeNumber() {
+        return wholeNumber;
+    }
+
+    public void setWholeNumber(int wholeNumber) {
+        this.wholeNumber = wholeNumber;
+    }
+
+    public int getDecimalNumber() {
+        return decimalNumber;
+    }
+
+    public void setDecimalNumber(int decimalNumber) {
+        this.decimalNumber = decimalNumber;
+    }
+
+    public String serializeToString() {
+        String str = currency;
+        if (sign == Sign.NEGATIVE) {
+            str += "-";
+        }
+        str += wholeNumber + ".";
+        if (decimalNumber < 10) {
+            str += "0" + decimalNumber;
+        } else {
+            str += decimalNumber;
+        }
+        return str;
+    }
+
+    @Override
+    public String toString() {
+        return serializeToString();
+    }
+
+    public static Cash add(Cash a, Cash b) throws BillingException {
+        if (!a.getCurrency().equals(b.getCurrency())) {
+            // we still not support this.
+            String msg = "Can not add in-similar currencies: " + a.getCurrency() + "!=" +
+                            b.getCurrency() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        if (a.getSign() == Sign.POSITIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash b2 = new Cash(b);
+            b2.setSign(Sign.POSITIVE);
+            return subtract(a, b2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.POSITIVE) {
+            Cash a2 = new Cash(a);
+            a2.setSign(Sign.POSITIVE);
+            return subtract(b, a2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash a2 = new Cash(a);
+            Cash b2 = new Cash(b);
+            a2.setSign(Sign.POSITIVE);
+            b2.setSign(Sign.POSITIVE);
+            Cash c2 = add(a2, b2);
+            c2.setSign(Sign.NEGATIVE);
+            return c2;
+        }
+        
+        int decimalSum = a.getDecimalNumber() + b.getDecimalNumber();
+        int wholeSum = a.getWholeNumber() + b.getWholeNumber();
+
+        Cash cash = new Cash();
+        cash.setCurrency(a.getCurrency());
+        if (decimalSum >= 100) {
+            decimalSum -= 100;
+            wholeSum += 1;
+        }
+        cash.setDecimalNumber(decimalSum);
+        cash.setWholeNumber(wholeSum);
+        cash.setSign(Sign.POSITIVE);
+        return cash;
+    }
+
+    public static Cash subtract(Cash a, Cash b) throws BillingException {
+        if (!a.getCurrency().equals(b.getCurrency())) {
+            // we still not support this.
+            String msg = "Can not add in-similar currencies: " + a.getCurrency() + "!=" +
+                            b.getCurrency() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        if (a.getSign() == Sign.POSITIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash b2 = new Cash(b);
+            b2.setSign(Sign.POSITIVE);
+            return add(a, b2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.POSITIVE) {
+            Cash a2 = new Cash(a);
+            a2.setSign(Sign.POSITIVE);
+            Cash c2 = add(b, a2);
+            c2.setSign(Sign.NEGATIVE);
+            return c2;
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash a2 = new Cash(a);
+            Cash b2 = new Cash(b);
+            a2.setSign(Sign.POSITIVE);
+            b2.setSign(Sign.POSITIVE);
+            Cash c2 = subtract(a2, b2);
+            if (c2.getSign() == Sign.NEGATIVE) {
+                c2.setSign(Sign.POSITIVE);
+            } else {
+                c2.setSign(Sign.NEGATIVE);
+            }
+            return c2;
+        }
+        
+        int decimalSum = a.getDecimalNumber() - b.getDecimalNumber();
+        int wholeSum = a.getWholeNumber() - b.getWholeNumber();
+
+        if (wholeSum < 0 || (decimalSum < 0 && wholeSum == 0)) {
+            // then it is negative value
+            Cash c = subtract(b, a);
+            c.setSign(Sign.NEGATIVE);
+            return c;
+        }
+
+        Cash cash = new Cash();
+        cash.setCurrency(a.getCurrency());
+        if (decimalSum < 0) {
+            decimalSum += 100;
+            wholeSum -= 1;
+        }
+
+        cash.setDecimalNumber(decimalSum);
+        cash.setWholeNumber(wholeSum);
+        return cash;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (!(o instanceof Cash)) {
+            return false;
+        }
+        Cash otherCash = (Cash) o;
+        return otherCash.serializeToString().equals(this.serializeToString());
+    }
+
+    @Override
+    public int hashCode() {
+        return serializeToString().hashCode();
+    }
+
+    public Cash multiply(double multiplyBy) {
+        long answerInCent = (long) (wholeNumber * 100 * multiplyBy + decimalNumber * multiplyBy);
+        int newWholeNumber = (int) (answerInCent / 100);
+        int newDecimalNumber = (int) (answerInCent % 100);
+
+        Cash cash = new Cash();
+        cash.setCurrency(this.getCurrency());
+        if (newWholeNumber < 0) {
+            cash.setSign(Sign.NEGATIVE);
+        }
+        cash.setWholeNumber(newWholeNumber);
+        cash.setDecimalNumber(newDecimalNumber);
+        return cash;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
new file mode 100644
index 0000000..e12d5d2
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.Date;
+
+/**
+ * Customer class - This holds the information of tenants
+ * i.e. customer=tenant
+ */
+public class Customer {
+    private int id;
+    private String name;
+    private String context;
+    private String fullName;
+    private String email;
+    private Date startedDate;
+    private String address;
+    private Invoice activeInvoice;
+    private long totalBandwidth;
+    private long totalStorage;
+    private long totalCartridgeCPUHours;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getFullName() {
+        return fullName;
+    }
+
+    public void setFullName(String fullName) {
+        this.fullName = fullName;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getContext() {
+        return context;
+    }
+
+    public void setContext(String context) {
+        this.context = context;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public Date getStartedDate() {
+        return new Date(startedDate.getTime());
+    }
+
+    public void setStartedDate(Date startedDate) {
+        this.startedDate = new Date(startedDate.getTime());
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    /**
+     * This will be used by rules to retrieve the active invoice
+     *
+     * @return
+     */
+    public final Invoice getActiveInvoice() {
+        return activeInvoice;
+    }
+
+    public final void setActiveInvoice(Invoice invoice) {
+        this.activeInvoice = invoice;
+    }
+
+    public long getTotalBandwidth() {
+        return totalBandwidth;
+    }
+
+    public void setTotalBandwidth(long totalBandwidth) {
+        this.totalBandwidth = totalBandwidth;
+    }
+
+    public long getTotalStorage() {
+        return totalStorage;
+    }
+
+    public void setTotalStorage(long totalStorage) {
+        this.totalStorage = totalStorage;
+    }
+
+    public long getTotalCartridgeCPUHours() {
+        return totalCartridgeCPUHours;
+    }
+
+    public void setTotalCartridgeCPUHours(long totalCartridgeCPUHours) {
+        this.totalCartridgeCPUHours = totalCartridgeCPUHours;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Customer customer = (Customer) o;
+
+        if (id != customer.id) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return id;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
new file mode 100644
index 0000000..862b1fd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
@@ -0,0 +1,88 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.dataobjects;
+
+
+import java.util.Date;
+
+public class Discount {
+    
+    private int id;
+    private int tenantId;
+    private float percentage;
+    private float amount;
+    private Date startDate;
+    private Date endDate;
+    private boolean isPercentageType;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public float getPercentage() {
+        return percentage;
+    }
+
+    public void setPercentage(float percentage) {
+        this.percentage = percentage;
+    }
+
+    public float getAmount() {
+        return amount;
+    }
+
+    public void setAmount(float amount) {
+        this.amount = amount;
+    }
+
+    public Date getStartDate() {
+        return startDate;
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = startDate;
+    }
+
+    public Date getEndDate() {
+        return endDate;
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = endDate;
+    }
+
+    public boolean isPercentageType() {
+        return isPercentageType;
+    }
+
+    public void setPercentageType(boolean percentageType) {
+        isPercentageType = percentageType;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
new file mode 100644
index 0000000..697ae77
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Invoice class - holds the invoice information
+ */
+public class Invoice {
+    int id;
+    Date date;
+    Date startDate;
+    Date endDate;
+    Cash boughtForward;
+    Cash carriedForward;
+    Cash totalCost;
+    Cash totalPayment;
+    Customer customer;
+    List<Subscription> subscriptions = new ArrayList<Subscription>();
+    List<Payment> payments = new ArrayList<Payment>();
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getDate() {
+        return new Date(date.getTime());
+    }
+
+    public void setDate(Date date) {
+        this.date = new Date(date.getTime());
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public Cash getBoughtForward() {
+        return boughtForward;
+    }
+
+    public void setBoughtForward(Cash boughtForward) {
+        this.boughtForward = boughtForward;
+    }
+
+    public Cash getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(Cash carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public Cash getTotalCost() {
+        return totalCost;
+    }
+
+    public void setTotalCost(Cash totalCost) {
+        this.totalCost = totalCost;
+    }
+
+    public Cash getTotalPayment() {
+        return totalPayment;
+    }
+
+    public void setTotalPayment(Cash totalPayment) {
+        this.totalPayment = totalPayment;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public List<Payment> getPayments() {
+        return payments;
+    }
+
+    public void setPayments(List<Payment> payments) {
+        this.payments = payments;
+    }
+
+    public void addPayment(Payment payment) {
+        this.payments.add(payment);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
new file mode 100644
index 0000000..8c92238
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.List;
+
+public class Item {
+    private int id;
+    private String name;
+    private Cash cost;
+    private Cash creditLimit; //this is the credit limit defined by the billing rules
+    private int bandwidthLimit;
+    private Cash bandwidthOveruseCharge;
+    private int resourceVolumeLimit;
+    private Cash resourceVolumeOveruseCharge;
+    private int cartridgeCPUHourLimit;
+    private Cash cartridgeCPUOveruseCharge;
+    private String description;
+    private Item parent;
+    private List<? extends Item> children;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Cash getCost() {
+        return cost;
+    }
+
+    public void setCost(Cash cost) {
+        this.cost = cost;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public Item getParent() {
+        return parent;
+    }
+
+    public void setParent(Item parent) {
+        this.parent = parent;
+    }
+
+    public List<? extends Item> getChildren() {
+        return children;
+    }
+
+    public void setChildren(List<? extends Item> children) {
+        this.children = children;
+    }
+
+    public Cash getCreditLimit() {
+        return creditLimit;
+    }
+
+    public void setCreditLimit(Cash creditLimit) {
+        this.creditLimit = creditLimit;
+    }
+
+    public int getBandwidthLimit() {
+        return bandwidthLimit;
+    }
+
+    public void setBandwidthLimit(int bandwidthLimit) {
+        this.bandwidthLimit = bandwidthLimit;
+    }
+
+    public Cash getBandwidthOveruseCharge() {
+        return bandwidthOveruseCharge;
+    }
+
+    public void setBandwidthOveruseCharge(Cash bandwidthOveruseCharge) {
+        this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+    }
+
+    public int getResourceVolumeLimit() {
+        return resourceVolumeLimit;
+    }
+
+    public void setResourceVolumeLimit(int resourceVolumeLimit) {
+        this.resourceVolumeLimit = resourceVolumeLimit;
+    }
+
+    public Cash getResourceVolumeOveruseCharge() {
+        return resourceVolumeOveruseCharge;
+    }
+
+    public void setResourceVolumeOveruseCharge(Cash resourceVolumeOveruseCharge) {
+        this.resourceVolumeOveruseCharge = resourceVolumeOveruseCharge;
+    }
+
+    public int getCartridgeCPUHourLimit() {
+        return cartridgeCPUHourLimit;
+    }
+
+    public void setCartridgeCPUHourLimit(int cartridgeCPUHourLimit) {
+        this.cartridgeCPUHourLimit = cartridgeCPUHourLimit;
+    }
+
+    public Cash getCartridgeCPUOveruseCharge() {
+        return cartridgeCPUOveruseCharge;
+    }
+
+    public void setCartridgeCPUOveruseCharge(Cash cartridgeCPUOveruseCharge) {
+        this.cartridgeCPUOveruseCharge = cartridgeCPUOveruseCharge;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+
+        Item item = (Item) o;
+
+        if (name != null ? !name.equals(item.name) : item.name != null) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        return name != null ? name.hashCode() : 0;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
new file mode 100644
index 0000000..e99f5d7
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+public class Payment {
+    int id;
+    Date date;
+    Cash amount;
+    String description;
+    List<Subscription> subscriptions;
+    Invoice invoice;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getDate() {
+        if(date!=null){
+            return new Date(date.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setDate(Date date) {
+        if(date!=null){
+            this.date = new Date(date.getTime());
+        }else{
+            this.date = null;
+        }
+    }
+
+    public Cash getAmount() {
+        return amount;
+    }
+
+    public void setAmount(Cash amount) {
+        this.amount = amount;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public void addSubscription(Subscription subscription) {
+        if (this.subscriptions == null) {
+            this.subscriptions = new ArrayList<Subscription>();
+        }
+        subscriptions.add(subscription);
+    }
+
+    public Invoice getInvoice() {
+        return invoice;
+    }
+
+    public void setInvoice(Invoice invoice) {
+        this.invoice = invoice;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
new file mode 100644
index 0000000..0b9fbf3
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Subscription class - information on subscriptions which the users
+ * are subscribed to.
+ */
+public class Subscription {
+    int id;
+    Date activeSince;
+    Date activeUntil;
+    Item item;
+    Customer customer;
+    boolean active;
+    int invoiceSubscriptionId = -1; // requires only if associated with an invoice
+    List<Payment> payments;
+    String subscriptionPlan;        //i.e. multitenance-small, multitencay-medium .....
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public Date getActiveSince() {
+        if(activeSince!=null){
+            return  new Date(activeSince.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setActiveSince(Date activeSince) {
+        if(activeSince!=null){
+            this.activeSince = new Date(activeSince.getTime());
+        }else{
+            this.activeSince = null;
+        }
+
+    }
+
+    public Date getActiveUntil() {
+        if(activeUntil!=null){
+            return  new Date(activeUntil.getTime());
+        }else{
+            return null;
+        }
+    }
+
+    public void setActiveUntil(Date activeUntil) {
+        if(activeUntil!=null){
+            this.activeUntil = new Date(activeUntil.getTime());
+        }else{
+            this.activeUntil = null;
+        }
+
+    }
+
+    public Item getItem() {
+        return item;
+    }
+
+    public void setItem(Item item) {
+        this.item = item;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+    public int getInvoiceSubscriptionId() {
+        return invoiceSubscriptionId;
+    }
+
+    public void setInvoiceSubscriptionId(int invoiceSubscriptionId) {
+        this.invoiceSubscriptionId = invoiceSubscriptionId;
+    }
+
+    public List<Payment> getPayments() {
+        return payments;
+    }
+
+    public void setPayments(List<Payment> payments) {
+        this.payments = payments;
+    }
+
+    public String getSubscriptionPlan() {
+        return subscriptionPlan;
+    }
+
+    public void setSubscriptionPlan(String subscriptionPlan) {
+        this.subscriptionPlan = subscriptionPlan;
+    }
+}


[09/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreGenerator.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreGenerator.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreGenerator.java
new file mode 100644
index 0000000..9dc4a92
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreGenerator.java
@@ -0,0 +1,229 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt;
+
+import org.apache.axiom.om.util.UUIDGenerator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.bouncycastle.jce.X509Principal;
+import org.bouncycastle.jce.X509V3CertificateGenerator;
+import org.wso2.carbon.core.RegistryResources;
+import org.wso2.carbon.core.util.CryptoUtil;
+import org.wso2.carbon.keystore.mgt.util.RealmServiceHolder;
+import org.wso2.carbon.keystore.mgt.util.RegistryServiceHolder;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.security.SecurityConstants;
+import org.wso2.carbon.security.keystore.KeyStoreAdmin;
+import org.wso2.carbon.user.core.service.RealmService;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+/**
+ * This class is used to generate a key store for a tenant and store it in the governance registry.
+ */
+public class KeyStoreGenerator {
+
+    private static Log log = LogFactory.getLog(KeyStoreGenerator.class);
+    private UserRegistry govRegistry;
+    private int tenantId;
+    private String tenantDomain;
+    private String password;
+
+
+    public KeyStoreGenerator(int  tenantId) throws KeyStoreMgtException {
+        try {
+            this.tenantId = tenantId;
+            this.tenantDomain = getTenantDomainName();
+            this.govRegistry = RegistryServiceHolder.getRegistryService().
+                    getGovernanceSystemRegistry(tenantId);
+            if(govRegistry == null){
+                log.error("Governance registry instance is null");
+                throw new KeyStoreMgtException("Governance registry instance is null");
+            }
+        } catch (RegistryException e) {
+            String errorMsg = "Error while obtaining the governance registry for tenant : " +
+                      tenantId;
+            log.error(errorMsg, e);
+            throw new KeyStoreMgtException(errorMsg, e);
+        }
+    }
+
+
+    /**
+     * This method first generates the keystore, then persist it in the gov.registry of that tenant
+     *
+     * @throws KeyStoreMgtException Error when generating or storing the keystore
+     */
+    public void generateKeyStore() throws KeyStoreMgtException {
+        try {
+            password = generatePassword();
+            KeyStore keyStore = KeyStore.getInstance("JKS");
+            keyStore.load(null, password.toCharArray());
+            X509Certificate pubCert = generateKeyPair(keyStore);
+            persistKeyStore(keyStore, pubCert);
+        } catch (Exception e) {
+            String msg = "Error while instantiating a keystore";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+
+    /**
+     * This method generates the keypair and stores it in the keystore
+     *
+     * @param keyStore A keystore instance
+     * @return Generated public key for the tenant
+     * @throws KeyStoreMgtException Error when generating key pair
+     */
+    private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
+        try {
+            CryptoUtil.getDefaultCryptoUtil();
+            //generate key pair
+            KeyPairGenerator keyPairGenerator = null;
+            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+            keyPairGenerator.initialize(1024);
+            KeyPair keyPair = keyPairGenerator.generateKeyPair();
+
+            // Common Name and alias for the generated certificate
+            String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";
+
+            //generate certificates
+            X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
+            v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
+            v3CertGen.setIssuerDN(new X509Principal(commonName));
+            v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
+            v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
+            v3CertGen.setSubjectDN(new X509Principal(commonName));
+            v3CertGen.setPublicKey(keyPair.getPublic());
+            v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
+            X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());
+
+            //add private key to KS
+            keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
+                                 new java.security.cert.Certificate[]{PKCertificate});
+            return PKCertificate;
+        } catch (Exception ex) {
+            String msg = "Error while generating the certificate for tenant :" +
+                         tenantDomain + ".";
+            log.error(msg, ex);
+            throw new KeyStoreMgtException(msg, ex);
+        }
+
+    }
+
+    /**
+     * Persist the keystore in the gov.registry
+     *
+     * @param keyStore created Keystore of the tenant
+     * @param PKCertificate pub. key of the tenant
+     * @throws KeyStoreMgtException Exception when storing the keystore in the registry
+     */
+    private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate)
+            throws KeyStoreMgtException {
+        try {
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+            keyStore.store(outputStream, password.toCharArray());
+            outputStream.flush();
+            outputStream.close();
+
+            String keyStoreName = generateKSNameFromDomainName();
+            // Use the keystore using the keystore admin
+            KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry);
+            keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName,
+                                      password, " ", "JKS", password);
+            
+            //Create the pub. key resource
+            Resource pubKeyResource = govRegistry.newResource();
+            pubKeyResource.setContent(PKCertificate.getEncoded());
+            pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER,
+                                       generatePubKeyFileNameAppender());
+
+            govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource);
+
+            //associate the public key with the keystore
+            govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName,
+                                       RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE,
+                                       SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY);
+
+        } catch (RegistryException e) {
+            String msg = "Error when writing the keystore/pub.cert to registry";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+        catch (Exception e) {
+            String msg = "Error when processing keystore/pub. cert to be stored in registry";
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+
+    /**
+     * This method is used to generate a random password for the generated keystore
+     *
+     * @return generated password
+     */
+    private String generatePassword() {
+        SecureRandom random = new SecureRandom();
+        String randString = new BigInteger(130, random).toString(12);
+        return randString.substring(randString.length() - 10, randString.length());
+    }
+
+    /**
+     * This method is used to generate a file name appender for the pub. cert, e.g.
+     * example-com-343743.cert
+     * @return generated string to be used as a file name appender
+     */
+    private String generatePubKeyFileNameAppender(){
+        String uuid = UUIDGenerator.getUUID();
+        return uuid.substring(uuid.length() - 6, uuid.length()-1);
+    }
+
+    /**
+     * This method generates the key store file name from the Domain Name
+     * @return
+     */
+    private String generateKSNameFromDomainName(){
+        String ksName = tenantDomain.trim().replace(".", "-");
+        return (ksName + ".jks" );
+    }
+
+    private String getTenantDomainName() throws KeyStoreMgtException {
+        RealmService realmService = RealmServiceHolder.getRealmService();
+        if (realmService == null) {
+            String msg = "Error in getting the domain name, realm service is null.";
+            log.error(msg);
+            throw new KeyStoreMgtException(msg);
+        }
+        try {
+            return realmService.getTenantManager().getDomain(tenantId);
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Error in getting the domain name for the tenant id: " + tenantId;
+            log.error(msg, e);
+            throw new KeyStoreMgtException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreMgtException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreMgtException.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreMgtException.java
new file mode 100644
index 0000000..040fb1f
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeyStoreMgtException.java
@@ -0,0 +1,39 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt;
+
+/**
+ * This class is used to wrap the exceptions thrown from stratos keystore mgt component.
+ */
+public class KeyStoreMgtException extends Exception {
+    public KeyStoreMgtException() {
+    }
+
+    public KeyStoreMgtException(String message) {
+        super(message);
+    }
+
+    public KeyStoreMgtException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public KeyStoreMgtException(Throwable cause) {
+        super(cause);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeystoreTenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeystoreTenantMgtListener.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeystoreTenantMgtListener.java
new file mode 100644
index 0000000..6262806
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/KeystoreTenantMgtListener.java
@@ -0,0 +1,79 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt;
+
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This class is used to listen to the tenant creation events and fire the keystore creation event
+ */
+public class KeystoreTenantMgtListener implements TenantMgtListener {
+
+    private static Log log = LogFactory.getLog(KeystoreTenantMgtListener.class);
+    private static final int EXEC_ORDER = 20;
+
+    /**
+     * Generate the keystore when a new tenant is registered.
+     * @param tenantInfo Information about the newly created tenant
+     */
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException {
+        try {
+            KeyStoreGenerator ksGenerator = new KeyStoreGenerator(tenantInfo.getTenantId());
+            ksGenerator.generateKeyStore();
+        } catch (KeyStoreMgtException e) {
+            String message = "Error when generating the keystore";
+            log.error(message, e);
+            throw new StratosException(message, e);
+        }
+    }
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantRename(int tenantId, String oldDomainName,
+                             String newDomainName) throws StratosException {
+        // It is not required to implement this method for keystore mgt.
+    }
+
+    public int getListenerOrder() {
+        return EXEC_ORDER;
+    }
+
+    public void onTenantInitialActivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantActivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onTenantDeactivation(int tenantId) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException {
+        // It is not required to implement this method for keystore mgt. 
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/internal/KeyStoreMgtServiceComponent.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
new file mode 100644
index 0000000..9b094a8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/internal/KeyStoreMgtServiceComponent.java
@@ -0,0 +1,87 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.keystore.mgt.KeystoreTenantMgtListener;
+import org.wso2.carbon.keystore.mgt.util.RealmServiceHolder;
+import org.wso2.carbon.keystore.mgt.util.RegistryServiceHolder;
+
+/**
+ * @scr.component name="org.wso2.carbon.keystore.mgt"
+ * immediate="true"
+ * @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="user.realmservice.default" interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService"
+ * unbind="unsetRealmService"
+ */
+public class KeyStoreMgtServiceComponent {
+
+    private static Log log = LogFactory.getLog(KeyStoreMgtServiceComponent.class);
+
+
+    protected void activate(ComponentContext ctxt){
+        KeystoreTenantMgtListener keystoreTenantMgtListener = new KeystoreTenantMgtListener();
+        ctxt.getBundleContext().registerService(
+                org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
+                keystoreTenantMgtListener, null);
+        if (log.isDebugEnabled()) {
+            log.debug("*************Stratos Keystore mgt component is activated.**************");
+        }
+    }
+
+    protected void deactivate(ComponentContext ctxt) {
+        if(log.isDebugEnabled()){
+            log.debug("************Stratos keystore mgt component is decativated.*************");
+        }
+    }
+
+    protected void setRegistryService(RegistryService registryService){
+        RegistryServiceHolder.setRegistryService(registryService);
+        if (log.isDebugEnabled()) {
+            log.debug("Registry Service is set for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void unsetRegistryService(RegistryService registryService){
+        RegistryServiceHolder.setRegistryService(null);
+        if(log.isDebugEnabled()){
+            log.debug("Registry Service is unset for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void setRealmService(RealmService realmService){
+        RealmServiceHolder.setRealmService(realmService);
+        if (log.isDebugEnabled()) {
+            log.debug("Realm Service is set for KeyStoreMgtServiceComponent.");
+        }
+    }
+
+    protected void unsetRealmService(RealmService realmService){
+        RealmServiceHolder.setRealmService(null);
+        if(log.isDebugEnabled()){
+            log.debug("Realm Service is unset for KeyStoreMgtServiceComponent.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RealmServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RealmServiceHolder.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RealmServiceHolder.java
new file mode 100644
index 0000000..719036a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RealmServiceHolder.java
@@ -0,0 +1,33 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt.util;
+
+import org.wso2.carbon.user.core.service.RealmService;
+
+public class RealmServiceHolder {
+
+    private static RealmService realmServiceService;
+
+    public static RealmService getRealmService() {
+        return realmServiceService;
+    }
+
+    public static void setRealmService(RealmService realmService) {
+        RealmServiceHolder.realmServiceService = realmService;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RegistryServiceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RegistryServiceHolder.java b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RegistryServiceHolder.java
new file mode 100644
index 0000000..ec00c2a
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.keystore.mgt/2.1.0/src/main/java/org/wso2/carbon/keystore/mgt/util/RegistryServiceHolder.java
@@ -0,0 +1,33 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.keystore.mgt.util;
+
+import org.wso2.carbon.registry.core.service.RegistryService;
+
+public class RegistryServiceHolder {
+
+    private static RegistryService registryService;
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static void setRegistryService(RegistryService registryService) {
+        RegistryServiceHolder.registryService = registryService;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/pom.xml
new file mode 100644
index 0000000..4e9db31
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/pom.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+        
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.load.balance.agent</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Load Balance Agent</name>
+    <description>
+        Load Balance Agent - Facilitates Getting the System Properties for Load Balancing and Auto Scaling
+    </description>
+    <url>http://wso2.org</url>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <version>2.2</version>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-Vendor>WSO2 Inc</Bundle-Vendor>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Export-Package>
+                            org.wso2.carbon.load.balance.agent.*,
+                        </Export-Package>
+                        <Import-Package>
+                             *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+   <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/java/org/wso2/carbon/load/balance/agent/LoadBalanceAgentService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/java/org/wso2/carbon/load/balance/agent/LoadBalanceAgentService.java b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/java/org/wso2/carbon/load/balance/agent/LoadBalanceAgentService.java
new file mode 100644
index 0000000..2d6bded
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/java/org/wso2/carbon/load/balance/agent/LoadBalanceAgentService.java
@@ -0,0 +1,55 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+package org.wso2.carbon.load.balance.agent;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.lang.management.ManagementFactory;
+
+/**
+ * Agent to get the system properties of the instances. Hence will be used in auto scaling, and
+ * also potentially in load balancing. Instances will be scaling up and down based on these params.
+ */
+public class LoadBalanceAgentService {
+
+    private static final Log log = LogFactory.getLog(LoadBalanceAgentService.class);
+
+
+    /**
+     * gets the load average of the system
+     *
+     * @return load average. Returns zero if the load average couldn't be read.
+     * Zero is treated as load-average not read, in the relevant places and ignored in the
+     * load balancer and autoscalar algorithms appropriately.
+     */
+    public double getLoadAverage() {
+        double systemLoadAverage = 0;
+        try {
+            systemLoadAverage =
+                    ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
+        } catch (Exception e) {
+            if (log.isDebugEnabled()) {
+                log.debug("Error in retrieving the load average of the instance");
+            }
+        }
+        return systemLoadAverage;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..d7a29dc
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.load.balance.agent/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+    <service name="LoadBalanceAgentService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.load.balance.agent.LoadBalanceAgentService
+        </parameter>
+        <operation name="getLoadAverage"/>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.migration/2.1.0/pom.xml
new file mode 100644
index 0000000..e403b4c
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/pom.xml
@@ -0,0 +1,99 @@
+
+	<!--
+		# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights
+		Reserved. # # Licensed under the Apache License, Version 2.0 (the
+		"License"); # you may not use this file except in compliance with the
+		License. # You may obtain a copy of the License at # #
+		http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by
+		applicable law or agreed to in writing, software # distributed under
+		the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES
+		OR CONDITIONS OF ANY KIND, either express or implied. # See the
+		License for the specific language governing permissions and #
+		limitations under the License.
+	-->
+<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.wso2.carbon</groupId>
+		<artifactId>stratos-components</artifactId>
+		<version>2.1.0</version>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.wso2.carbon.migration</artifactId>
+	<packaging>bundle</packaging>
+	<name>WSO2 Stratos - Migration</name>
+
+	<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>
+						<Private-Package>
+							org.wso2.carbon.migration.*,
+                        </Private-Package>
+						<Import-Package>
+							org.wso2.carbon.registry.core.*;version=1.0.1,
+							org.wso2.carbon.registry.resource.*,
+							org.wso2.carbon.stratos.common.*,
+							!javax.xml.namespace,
+							javax.xml.namespace; version=0.0.0,
+							javax.servlet;version="${imp.pkg.version.javax.servlet}",
+							javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+							org.apache.axiom.*; version="${axiom.osgi.version.range}",
+							*;resolution:=optional
+                        </Import-Package>
+					</instructions>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<dependencies>
+
+		<dependency>
+			<groupId>org.apache.axis2.wso2</groupId>
+			<artifactId>axis2</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>log4j</groupId>
+			<artifactId>log4j</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.registry.core</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>commons-logging</groupId>
+			<artifactId>commons-logging</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.user.core</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.user.mgt</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.stratos.common</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.usage.agent</artifactId>
+		</dependency>
+	</dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/Alpha1.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/Alpha1.java b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/Alpha1.java
new file mode 100644
index 0000000..f975ac5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/Alpha1.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.migration.impl;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.constants.UsageConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.migration.util.Migrator;
+import org.wso2.carbon.migration.util.Util;
+import org.wso2.carbon.usage.agent.api.SystemMeteringAgent;
+
+public class Alpha1 implements Migrator {
+
+    public static final String OLD_BANDWIDTH_USE_STORE_PATH =
+            "/repository/components/org.wso2.carbon.bandwidth-use";
+    private static final Log log = LogFactory.getLog(Alpha1.class);
+
+    public void migrate() throws Exception {
+        // changes to the data model for the statics.
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        SystemMeteringAgent meteringAgent = Util.getSystemMeteringAgent();
+
+        //get super tenant governance registry
+        UserRegistry superTenantGovernanceRegistry = Util.getSuperTenantGovernanceSystemRegistry();
+        if (!superTenantGovernanceRegistry.resourceExists(OLD_BANDWIDTH_USE_STORE_PATH)) {
+            return;
+        }
+
+        Tenant[] tenants = tenantManager.getAllTenants();
+        // uses only the current year month 2010-july
+        String yearMonth = CommonUtil.getCurrentMonthString();
+        for (Tenant tenant : tenants) {
+            int tenantId = tenant.getId();
+            long incomingBw = getOldIncomingRegistryBandwidth(yearMonth, tenantId);
+            long outgoingBw = getOldOutgoingRegistryBandwidth(yearMonth, tenantId);
+
+            if (incomingBw != 0) {
+                meteringAgent.persistUsage(tenantId, yearMonth,
+                        UsageConstants.REGISTRY_INCOMING_BW, incomingBw + "");
+            }
+            if (outgoingBw != 0) {
+                meteringAgent.persistUsage(tenantId, yearMonth,
+                        UsageConstants.REGISTRY_OUTGOING_BW, outgoingBw + "");
+            }
+            log.info("Migrating registry bandwidth data to the new data model. tenant id: " +
+                    tenantId + ".");
+        }
+        superTenantGovernanceRegistry.delete(OLD_BANDWIDTH_USE_STORE_PATH);
+    }
+
+    public long getOldIncomingRegistryBandwidth(String yearMonth, int tenantId)
+            throws RegistryException {
+        UserRegistry superTenantGovernanceRegistry = Util.getSuperTenantGovernanceSystemRegistry();
+
+        String incomingBandwidthUserCollectionPath =
+                OLD_BANDWIDTH_USE_STORE_PATH + RegistryConstants.PATH_SEPARATOR + tenantId;
+        if (!superTenantGovernanceRegistry.resourceExists(incomingBandwidthUserCollectionPath)) {
+            return 0;
+        }
+
+        Resource incomingBandwidthUserCollectionR =
+                superTenantGovernanceRegistry.get(incomingBandwidthUserCollectionPath);
+        if (!(incomingBandwidthUserCollectionR instanceof Collection)) {
+            String msg = "incoming bandwidth user collection is not a collection";
+            log.error(msg);
+            throw new RegistryException(msg);
+        }
+
+        Collection incomingBandwidthUserCollection = (Collection) incomingBandwidthUserCollectionR;
+        String[] incomingBandwidthUserPaths = incomingBandwidthUserCollection.getChildren();
+
+        long totalIncomingBandwidth = 0;
+        for (String incomingBandwidthUserPath : incomingBandwidthUserPaths) {
+            String incomingBandwidthResourcePath =
+                    incomingBandwidthUserPath + RegistryConstants.PATH_SEPARATOR + yearMonth +
+                            RegistryConstants.PATH_SEPARATOR + StratosConstants.INCOMING_PATH_DIR;
+
+            if (!superTenantGovernanceRegistry.resourceExists(incomingBandwidthResourcePath)) {
+                return 0;
+            }
+            Resource incomingBandwidthResource =
+                    superTenantGovernanceRegistry.get(incomingBandwidthResourcePath);
+            if (incomingBandwidthResource instanceof Collection) {
+                String msg = "Incoming bandwidth is not stored as a non collection.";
+                log.error(msg);
+                throw new RegistryException(msg);
+            }
+            byte[] contentBytes = (byte[]) incomingBandwidthResource.getContent();
+            if (contentBytes != null) {
+                String contentStr = new String(contentBytes);
+                try {
+                    totalIncomingBandwidth += Integer.parseInt(contentStr);
+                } catch (NumberFormatException e) {
+                    String msg = "Error in parsing the integer string: " + contentStr;
+                    log.error(msg, e);
+                    throw new RegistryException(msg, e);
+                }
+            }
+        }
+        return totalIncomingBandwidth;
+    }
+
+    public long getOldOutgoingRegistryBandwidth(String yearMonth, int tenantId)
+            throws RegistryException {
+        UserRegistry superTenantGovernanceRegistry = Util.getSuperTenantGovernanceSystemRegistry();
+        String outgoingBandwidthUserCollectionPath =
+                OLD_BANDWIDTH_USE_STORE_PATH + RegistryConstants.PATH_SEPARATOR + tenantId;
+        if (!superTenantGovernanceRegistry.resourceExists(outgoingBandwidthUserCollectionPath)) {
+            return 0;
+        }
+
+        Resource outgoingBandwidthUserCollectionR =
+                superTenantGovernanceRegistry.get(outgoingBandwidthUserCollectionPath);
+        if (!(outgoingBandwidthUserCollectionR instanceof Collection)) {
+            String msg = "outgoing bandwidth user collection is not a collection";
+            log.error(msg);
+            throw new RegistryException(msg);
+        }
+
+        Collection outgoingBandwidthUserCollection = (Collection) outgoingBandwidthUserCollectionR;
+        String[] outgoingBandwidthUserPaths = outgoingBandwidthUserCollection.getChildren();
+
+        long totalOutgoingBandwidth = 0;
+        for (String outgoingBandwidthUserPath : outgoingBandwidthUserPaths) {
+            String outgoingBandwidthResourcePath =
+                    outgoingBandwidthUserPath + RegistryConstants.PATH_SEPARATOR + yearMonth +
+                            RegistryConstants.PATH_SEPARATOR + StratosConstants.OUTGOING_PATH_DIR;
+
+            if (!superTenantGovernanceRegistry.resourceExists(outgoingBandwidthResourcePath)) {
+                return 0;
+            }
+            Resource outgoingBandwidthResource =
+                    superTenantGovernanceRegistry.get(outgoingBandwidthResourcePath);
+            if (outgoingBandwidthResource instanceof Collection) {
+                String msg = "outgoing bandwidth is not stored as a non collection.";
+                log.error(msg);
+                throw new RegistryException(msg);
+            }
+            byte[] contentBytes = (byte[]) outgoingBandwidthResource.getContent();
+            String contentStr = new String(contentBytes);
+            try {
+                totalOutgoingBandwidth += Integer.parseInt(contentStr);
+            } catch (NumberFormatException e) {
+                String msg = "Error in parsing the integer string: " + contentStr;
+                log.error(msg, e);
+                throw new RegistryException(msg, e);
+            }
+        }
+        return totalOutgoingBandwidth;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/ManagementPermissionsAdder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/ManagementPermissionsAdder.java b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/ManagementPermissionsAdder.java
new file mode 100644
index 0000000..b440ce7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/impl/ManagementPermissionsAdder.java
@@ -0,0 +1,126 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.migration.impl;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.Registry;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+import org.wso2.carbon.utils.component.xml.Component;
+import org.wso2.carbon.utils.component.xml.ComponentConfigFactory;
+import org.wso2.carbon.utils.component.xml.builder.ManagementPermissionsBuilder;
+import org.wso2.carbon.utils.component.xml.config.ManagementPermission;
+import org.wso2.carbon.migration.util.Util;
+
+/**
+ * This behave similar to the
+ * carbon/core/org.wso2.carbon.user.mgt/ManagementPermissionsAdder, Except this
+ * add the permissions to all the tenants.
+ */
+public class ManagementPermissionsAdder implements BundleListener {
+    private static Log log = LogFactory.getLog(ManagementPermissionsAdder.class);
+    Tenant[] tenants;
+    List<Integer> tenantIds;
+
+    public ManagementPermissionsAdder() throws Exception {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        tenants = tenantManager.getAllTenants();
+        tenantIds = new ArrayList<Integer>();
+        for (int i = 0; i < tenants.length; i++) {
+            if (tenants[i].isActive()) {
+                tenantIds.add(tenants[i].getId());
+            }
+        }
+    }
+
+    public void bundleChanged(BundleEvent event) {
+        Bundle bundle = event.getBundle();
+        try {
+            if (event.getType() == BundleEvent.STARTED) {
+                addUIPermissionFromBundle(bundle);
+            }
+        } catch (Exception e) {
+            log.error(
+                    "Error occured when processing component xml in bundle " +
+                            bundle.getSymbolicName(), e);
+        }
+    }
+
+    public void addUIPermissionFromBundle(Bundle bundle) throws Exception {
+        BundleContext bundleContext = bundle.getBundleContext();
+        if (bundleContext == null) { // If the bundle got uninstalled, the
+                                     // bundleContext will be null
+            return;
+        }
+
+        URL url = bundleContext.getBundle().getEntry("META-INF/component.xml");
+        if (url == null) {
+            return;
+        }
+
+        InputStream xmlStream = url.openStream();
+        if (xmlStream == null) {
+            return;
+        }
+
+        if (log.isDebugEnabled()) {
+            log.debug("Adding permissions in bundle" + bundle.getSymbolicName());
+        }
+
+        Component component = ComponentConfigFactory.build(xmlStream);
+        ManagementPermission[] uiPermissions = null;
+        if (component != null) {
+            uiPermissions =
+                    (ManagementPermission[]) component
+                            .getComponentConfig(ManagementPermissionsBuilder.LOCALNAME_MGT_PERMISSIONS);
+        }
+
+        if (uiPermissions != null) {
+            for (int i = 0; i < tenantIds.size(); i++) {
+                Registry registry = Util.getRegistryService().getConfigSystemRegistry(tenantIds.get(i));
+                for (ManagementPermission uiPermission : uiPermissions) {
+                    if (uiPermission == null ||
+                            uiPermission.getResourceId() == null ||
+                            uiPermission.getResourceId().startsWith(
+                                    CarbonConstants.UI_PROTECTED_PERMISSION_COLLECTION) ||
+                            registry.resourceExists(uiPermission.getResourceId())) {
+                        continue;
+                    }
+                    Collection resource = registry.newCollection();
+                    resource.setProperty(UserMgtConstants.DISPLAY_NAME,
+                            uiPermission.getDisplayName());
+                    registry.put(uiPermission.getResourceId(), resource);
+                }
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/internal/MigrationServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/internal/MigrationServiceComponent.java b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/internal/MigrationServiceComponent.java
new file mode 100644
index 0000000..4282ebd
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/internal/MigrationServiceComponent.java
@@ -0,0 +1,81 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.migration.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.migration.impl.Alpha1;
+import org.wso2.carbon.migration.impl.ManagementPermissionsAdder;
+import org.wso2.carbon.migration.util.Util;
+
+/**
+ * @scr.component name="org.wso2.carbon.migration" immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ */
+public class MigrationServiceComponent {
+    private static Log log = LogFactory.getLog(MigrationServiceComponent.class);
+
+    protected void activate(ComponentContext context) {
+        try {
+            new Alpha1().migrate();
+            ManagementPermissionsAdder uiPermissionAdder = new ManagementPermissionsAdder();
+            context.getBundleContext().addBundleListener(uiPermissionAdder);
+            Bundle[] bundles = context.getBundleContext().getBundles();
+            for (Bundle bundle : bundles) {
+                if (bundle.getState() == Bundle.ACTIVE) {
+                    uiPermissionAdder.addUIPermissionFromBundle(bundle);
+                }
+            }
+            
+            log.debug("******* Migration bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Migration bundle failed to activate ******* ");
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Migration is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Migrator.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Migrator.java b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Migrator.java
new file mode 100644
index 0000000..8ea8521
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Migrator.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.migration.util;
+
+public interface Migrator {
+    public void migrate() throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Util.java b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Util.java
new file mode 100644
index 0000000..392e004
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.migration/2.1.0/src/main/java/org/wso2/carbon/migration/util/Util.java
@@ -0,0 +1,72 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.migration.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.ServiceRegistration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.UserRealm;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.usage.agent.api.SystemMeteringAgent;
+
+public class Util {
+
+    private static final Log log = LogFactory.getLog(Util.class);
+    private static int JOB_INTERVAL = 15; // in mins
+    private static String TASK_ID = "taskId";
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static ServiceRegistration redirectorServiceRegistration = null;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static UserRealm getUserRealm(int tenantId) throws RegistryException {
+        return registryService.getUserRealm(tenantId);
+    }
+
+    public static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+    public static SystemMeteringAgent getSystemMeteringAgent() throws RegistryException {
+        return new SystemMeteringAgent(getSuperTenantGovernanceSystemRegistry());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
new file mode 100644
index 0000000..db3e774
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.cloud.controller/2.1.3/pom.xml
@@ -0,0 +1,324 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+       <artifactId>stratos-components</artifactId>
+       <version>2.1.0</version>
+       <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.stratos.cloud.controller</artifactId>
+    <packaging>bundle</packaging>
+    <version>2.1.3</version>
+    <name>WSO2 Carbon - Stratos Cloud Controller</name>
+    <url>http://wso2.org</url>
+
+    <build>
+        <plugins>
+            <!--plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <version>1.7.1</version>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                        <configuration>
+                            <artifactSet>
+                                <includes>
+                                    <include>org.jclouds:*</include>
+                                    <include>org.jclouds.*:*</include>
+                                </includes>
+                            </artifactSet>
+                            <filtering>true</filtering>
+                            <filters>
+                                <filter>
+                                    <artifact>org.jclouds*:*</artifact>
+                                    <includes>
+                                        <include>META-INF/services/org.jclouds.apis.ApiMetadata</include>
+                                        <include>META-INF/services/org.jclouds.providers.ProviderMetadata</include>
+                                    </includes>
+                                </filter>
+                            </filters>
+                            <transformers>
+                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer">
+                                </transformer>
+                            </transformers>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin-->
+            <!--plugin>
+                <groupId>org.apache.axis2</groupId>
+                <artifactId>axis2-aar-maven-plugin</artifactId>
+                <version>1.4</version>
+                <extensions>true</extensions>
+            </plugin-->
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-scr-plugin</artifactId>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <version>1.4.0</version>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.wso2.carbon.stratos.cloud.controller.interfaces.*,
+                            org.wso2.carbon.stratos.cloud.controller.publisher.*,
+                            org.wso2.carbon.stratos.cloud.controller.topic.*,
+                            org.wso2.carbon.stratos.cloud.controller.iaases.*,
+                            org.wso2.carbon.stratos.cloud.controller.util.*
+                        </Export-Package>
+                        <Private-Package>
+                            org.wso2.carbon.stratos.cloud.controller.*,
+                            !org.wso2.carbon.stratos.cloud.controller.interfaces,
+                            !org.wso2.carbon.stratos.cloud.controller.publisher,
+                            !org.wso2.carbon.stratos.cloud.controller.topic,
+                            !org.wso2.carbon.stratos.cloud.controller.iaases 
+                        </Private-Package>
+                        <Import-Package>
+                        	  !org.apache.commons.logging,
+                            org.apache.commons.logging; version=0.0.0,
+                            org.wso2.carbon.utils.*,
+                            <!--org.jclouds.compute*;version="${jclouds.version}";resolution:=optional,
+                            org.jclouds*;version="${jclouds.version}",-->
+                            *; resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                        
+                        <Axis2Deployer>CloudControllerDeployer</Axis2Deployer>
+                        
+                        <Axis2Deployer>CartridgeDeployer</Axis2Deployer>
+                        
+                        <Axis2Deployer>ServiceDeployer</Axis2Deployer>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.securevault</artifactId>
+            <version>${wso2carbon.version}</version>
+        </dependency>
+        <dependency>
+    		<groupId>org.hectorclient.wso2</groupId>
+	    	<artifactId>hector-core</artifactId>
+		    <version>1.1.0.wso2v1</version>
+	        <exclusions>
+	            <exclusion>
+	                <groupId>com.google.guava.wso2</groupId>
+	                <artifactId>guava</artifactId>
+	            </exclusion>
+	        </exclusions>
+
+		</dependency>
+        <dependency>
+            <groupId>com.google.guava.wso2</groupId>
+	        <artifactId>guava</artifactId>
+            <version>${google.guava.wso2.version}</version>
+        </dependency>
+        <dependency>
+                <groupId>org.wso2.andes.wso2</groupId>
+                <artifactId>andes-client</artifactId>
+                <version>0.13.wso2v3</version>
+            </dependency>
+        <dependency>
+                <groupId>org.apache.geronimo.specs.wso2</groupId>
+                <artifactId>geronimo-jms_1.1_spec</artifactId>
+                <version>${orbit.version.geronimo-jms_1.1_spec}</version>
+            </dependency>
+        
+        <dependency>
+        	<groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.analytics.hive.stub</artifactId>
+   			<version>4.1.0</version>
+        </dependency> 
+	
+        <!--  Jclouds dependencies -->
+       <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-core</artifactId>
+           <version>${jclouds.version}</version>
+          </dependency>
+        <dependency>
+           <groupId>org.jclouds</groupId>
+           <artifactId>jclouds-compute</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+	 <dependency>
+            <groupId>org.jclouds.api</groupId>
+            <artifactId>vcloud</artifactId>
+            <version>1.6.0-wso2v1</version>
+        </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-bouncycastle</artifactId>
+           <version>${jclouds.version}</version>
+           <exclusions>
+              <exclusion>
+                 <groupId>org.bouncycastle</groupId>
+                 <artifactId>bcprov-jdk16</artifactId>
+              </exclusion>
+           </exclusions>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-sshj</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-log4j</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.driver</groupId>
+           <artifactId>jclouds-enterprise</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.provider</groupId>
+           <artifactId>aws-ec2</artifactId>
+           <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-nova</artifactId>
+           <version>${jclouds.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>org.jclouds.api</groupId>
+           <artifactId>openstack-keystone</artifactId>
+           <version>${jclouds.wso2.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>org.jclouds</groupId>
+            <artifactId>jclouds-scriptbuilder</artifactId>
+              <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>org.jclouds.common</groupId>
+            <artifactId>aws-common</artifactId>
+              <version>${jclouds.version}</version>
+         </dependency>
+         <dependency>
+             <groupId>com.jamesmurty.utils.wso2</groupId>
+             <artifactId>java-xmlbuilder</artifactId>
+             <version>0.4.wso2v1</version>
+         </dependency>
+        <dependency>
+            <groupId>org.jclouds.api</groupId>
+            <artifactId>vcloud</artifactId>
+            <version>1.6.0-wso2v1</version>
+        </dependency>
+         <dependency>
+           <groupId>com.google.code.gson</groupId>
+           <artifactId>gson</artifactId>
+           <version>${gson2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.google.guice.wso2</groupId>
+           <artifactId>guice</artifactId>
+           <version>${google.guice.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.google.guice.assistedinject.wso2</groupId>
+           <artifactId>guice-assistedinject</artifactId>
+           <version>${com.google.guice.assistedinject.wso2.version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.sun.jersey</groupId>
+           <artifactId>jersey-core</artifactId>
+           <version>${sun.jersey.version}</version>
+         </dependency>
+         <dependency>
+          <groupId>net.oauth.core</groupId>
+          <artifactId>oauth</artifactId>
+          <version>20100527</version>
+         </dependency>
+         <dependency>
+           <groupId>commons-io.wso2</groupId>
+           <artifactId>commons-io</artifactId>
+           <version>2.0.0.wso2v1</version>
+         </dependency>
+         <dependency>
+           <groupId>rhino.wso2</groupId>
+           <artifactId>js</artifactId>
+           <version>1.7.0.R1-wso2v3</version>
+         </dependency>
+         <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.cartridge.messages</artifactId>
+           <version>2.1.1</version>
+         </dependency>
+         <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.databridge.agent.thrift</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ntask.core</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+    </dependencies>
+    <properties>
+        <gson2.version>2.2</gson2.version>
+        <jclouds.version>1.5.0-beta.5</jclouds.version>
+        <jclouds.wso2.version>1.5.0-beta.5.wso2v1</jclouds.wso2.version>
+        <com.google.guice.assistedinject.wso2.version>3.0.wso2v1</com.google.guice.assistedinject.wso2.version>
+        <sun.jersey.version>1.12</sun.jersey.version>
+    </properties>
+</project>
+


[41/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/js/account_mgt.js
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/js/account_mgt.js b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/js/account_mgt.js
new file mode 100644
index 0000000..c957312
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/js/account_mgt.js
@@ -0,0 +1,214 @@
+function deactivate(domain) {
+    sessionAwareFunction(function() {
+        CARBON.showConfirmationDialog("Are you sure you want to deactivate the domain: " +
+                                      domain + ".", function() {
+            var submitForm = document.getElementById("deactivate_form");
+            submitForm.submit();
+        });
+    }, "Session timed out. Please login again.");
+}
+
+function checkDomain(nname)
+{
+
+    var error = "";
+    error += validateEmpty(nname, "Domain");
+    if (error != "") {
+        return error;
+    }
+    //var arr = new Array(
+    //'.com','.net','.org','.biz','.coop','.info','.museum','.name',
+    //'.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
+    //'.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
+    //'.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
+    //'.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
+    //'.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
+    //'.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
+    //'.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
+    //'.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
+    //'.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
+    //'.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
+    //'.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
+    //'.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
+    //'.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
+    //'.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
+    //'.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
+    //'.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
+    //'.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
+    //'.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
+    //'.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
+    //'.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
+    //'.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
+    //'.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
+    //'.wf','.ye','.yt','.yu','.za','.zm','.zw');
+
+    var mai = nname.value;
+
+    var val = true;
+    var dot = mai.lastIndexOf(".");
+    var dname = mai.substring(0, dot);
+    var ext = mai.substring(dot, mai.length);
+    //alert(ext);
+
+    if (ext.indexOf("-trial") >= 0 || ext.indexOf("-unverified") >= 0) {
+        // we are not allowing to create a domain with -trial or -unverified is in the extension
+        return "The domain name you entered is not valid. Please enter a valid domain name.";
+    }
+
+    if (ext.indexOf("/") >= 0 || ext.indexOf("\\") >= 0) {
+        return "The '/' and '\\' is not allowed in a domain name";
+    }
+
+    if (dot > 1 && dot < 57)
+    {
+        //	for(var i=0; i<arr.length; i++)
+        //	{
+        //	  if(ext == arr[i])
+        //	  {
+        //	 	val = true;
+        //		break;
+        //	  }
+        //	  else
+        //	  {
+        //	 	val = false;
+        //	  }
+        //	}
+        if (!val)
+        {
+            error = "Your domain extension " + ext + " is not correct";
+            return error;
+        }
+        else
+        {
+            for (var j = 0; j < dname.length; j++)
+            {
+                var dh = dname.charAt(j);
+                var hh = dh.charCodeAt(0);
+                if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46)
+                {
+                    if ((j == 0 || j == dname.length - 1) && hh == 45)
+                    {
+                        error = "Domain name should not begin and end with '-'";
+                        return error;
+                    }
+                }
+                else {
+                    error = "Your domain name should not have special characters";
+                    return error;
+                }
+            }
+        }
+    }
+    else
+    {
+        error = "Your Domain name is too short/long or you should have an extension to your domain.";
+        return error;
+    }
+
+    return error;
+}
+
+function clearDomainConfirmationMsg() {
+    var domain_confirmation_div = document.getElementById("domain-confirmation-msg");
+    domain_confirmation_div.innerHTML = "";
+}
+
+
+function domainSelected() {
+    var domain = document.getElementById('domainToValidate');
+
+    var reason = validateEmpty(domain, "Domain");
+    if (reason == "") {
+        reason += checkDomain(domain);
+    }
+
+    if (reason != "") {
+        CARBON.showWarningDialog(reason);
+        return false;
+    }
+    sessionAwareFunction(function() {
+        var validateDomainForm = document.getElementById('validateDomainForm');
+        validateDomainForm.submit();
+    }, "Session timed out. Please login again.");
+
+}
+
+function updateContact() {
+    var email = document.getElementById("email");
+    var oldEmail = document.getElementById("old-email");
+    var reason = "";
+    if (reason == "") {
+        reason += validateEmpty(email, "Email");
+    }
+    if (reason == "") {
+        reason += validateEmail(email);
+    }
+
+    if (reason == "" && email.value == oldEmail.innerHTML) {
+        reason += "You have not updated your email yet."
+    }
+
+    if (reason != "") {
+        CARBON.showWarningDialog(reason);
+        return;
+    }
+    // now call the updateContact.
+
+    sessionAwareFunction(function() {
+        debugger;
+        var busyContactPlaceHolder = document.getElementById("busyContact");
+        busyContactPlaceHolder.innerHTML = "<img src=\"images/ajax-loader.gif\"/>";
+
+        new Ajax.Request('../account-mgt/update_contact_ajaxprocessor.jsp',
+        {
+            method:'post',
+            parameters: {email: email.value},
+
+            onSuccess: function(transport) {
+                var returnValue = transport.responseText;
+                busyContactPlaceHolder.innerHTML = "";
+
+                if (returnValue.search(/----failed----/) == -1) {
+                    CARBON.showWarningDialog("We have sent an email to validate the contact details you just entered. Please follow " +
+                                             "the instructions in there to submit the updated contact details");
+                }
+                else {
+                    CARBON.showWarningDialog("Updating the contact information failed.");
+                }
+            },
+
+            onFailure: function(transport) {
+                busyContactPlaceHolder.innerHTML = "";
+                CARBON.showWarningDialog("Updating the contact information failed.");
+            }
+        });
+    }, "Session timed out. Please login again.");
+}
+
+
+function updateProfile() {
+    var update_profile_form = document.getElementById("update_profile_form");
+    var firstname = document.getElementById("firstname");
+    var oldFirstname = document.getElementById("old-firstname");
+    var lastname = document.getElementById("lastname");
+    var oldLastname = document.getElementById("old-lastname");
+
+    var reason = "";
+
+    if (reason == "") {
+        reason += validateEmpty(firstname, "First Name");
+    }
+    if (reason == "") {
+        reason += validateEmpty(lastname, "Last Name");
+
+        if ((reason == "" && firstname.value == oldFirstname.innerHTML) &&
+            (reason == "" && lastname.value == oldLastname.innerHTML)) {
+            reason += "You have not updated your firstname or last name yet.";
+        }
+    }
+    if (reason != "") {
+        CARBON.showWarningDialog(reason);
+        return;
+    }
+    update_profile_form.submit();
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_contact_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_contact_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_contact_ajaxprocessor.jsp
new file mode 100644
index 0000000..58a323b
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_contact_ajaxprocessor.jsp
@@ -0,0 +1,35 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+AccountMgtClient client;
+try {
+    String email = request.getParameter("email");
+    client = new AccountMgtClient(config, session);
+    client.updateContact(email);
+
+} catch (RegistryException e) {
+%>
+----failed----
+<%
+    return;
+}
+
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_profile_processor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_profile_processor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_profile_processor.jsp
new file mode 100644
index 0000000..d0158c9
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_profile_processor.jsp
@@ -0,0 +1,62 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.utils.Util" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<carbon:jsi18n
+		resourceBundle="org.wso2.carbon.register.ui.i18n.JSResources"
+		request="<%=request%>" />
+<link href="css/update_profile.css" rel="stylesheet" type="text/css" media="all"/>
+
+
+<%
+    Boolean isUpdated;
+
+    try {
+    isUpdated = Util.updateFullname(request, config, session);
+    }
+    catch (Exception e) {
+    isUpdated  = false;
+    }
+
+%>
+<%        if (isUpdated) { %>
+
+    <div id="middle">
+
+       <h2>
+           Profile Successfully Updated.
+       </h2>
+
+
+   <%   }  else { %>
+
+    <div id="middle">
+
+       <h2>
+           Profile Update Failed
+       </h2>
+
+        <% } %>
+        <p>
+            Go to  <a href="../admin/index.jsp"> home page. </a>
+        </p>
+      </div>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier.jsp
new file mode 100644
index 0000000..2b35fc3
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier.jsp
@@ -0,0 +1,56 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.utils.Util" %>
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.EmailValidationClient" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.register.ui.i18n.JSResources"
+        request="<%=request%>" />
+<%
+    String data = (String)session.getAttribute("intermediate-data");
+        
+    Util.readIntermediateData(request, data);
+
+    EmailValidationClient client;
+    String email;
+    String domain;
+    try {
+        email = (String)request.getAttribute("email");
+        domain = (String)request.getAttribute("tenantDomain");
+        String confirmationKey = (String)request.getAttribute("confirmationKey");
+
+        client = new EmailValidationClient(config, session);
+        client.proceedUpdateContact(domain, email, confirmationKey);
+    } catch (RegistryException e) {
+    %>
+      <div>Error in validating the contact.</div>
+    <%
+        return;
+    }
+
+%>
+
+<div style="margin:20px">You have successfully validated your email address and the contact information associated with your WSO2
+    Cloud Services account is updated. Click <a href="../admin/index.jsp">here</a> to access WSO2 Cloud Manager.    
+</div>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier_redirector_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier_redirector_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier_redirector_ajaxprocessor.jsp
new file mode 100644
index 0000000..cb5beae
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/update_verifier_redirector_ajaxprocessor.jsp
@@ -0,0 +1,30 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.account.mgt.ui.utils.Util" %>
+<%@ page import="org.wso2.carbon.utils.multitenancy.MultitenantConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+//this jsp is used just to redirect to the correct update verifier.
+
+String data = (String)session.getAttribute("intermediate-data");
+
+Util.readIntermediateData(request, data);
+String domain = (String)request.getAttribute("tenantDomain");
+String contextPath = "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + domain;
+response.sendRedirect("../account-mgt/update_verifier.jsp");
+%>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validate_domain_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validate_domain_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validate_domain_ajaxprocessor.jsp
new file mode 100644
index 0000000..71da4bd
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validate_domain_ajaxprocessor.jsp
@@ -0,0 +1,29 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+%@ page import="org.wso2.carbon.registry.core.RegistryConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar" prefix="carbon" %>
+<%
+
+String domainToValidate = request.getParameter("domain");
+
+
+response.sendRedirect("../validate-domain/validate_domain_logged_in.jsp?domain=" + domainToValidate);
+
+%>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validation_success_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validation_success_ajaxprocessor.jsp b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validation_success_ajaxprocessor.jsp
new file mode 100644
index 0000000..15aec9b
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt.ui/2.1.0/src/main/resources/web/account-mgt/validation_success_ajaxprocessor.jsp
@@ -0,0 +1,49 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page import="org.wso2.carbon.account.mgt.ui.clients.AccountMgtClient" %>
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.utils.multitenancy.MultitenantConstants" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+try {
+    String domainToRegister = (String)session.getAttribute("temp-domain-to-register");
+    String successKey = (String)session.getAttribute("validate-domain-success-key");
+    AccountMgtClient client = new AccountMgtClient(config, session);
+    if (client.finishedDomainValidation(domainToRegister, successKey)) {
+
+        //session.setAttribute(MultitenantConstants.TENANT_DOMAIN, domainToRegister);
+        session.setAttribute("domain-validation-success", "true");
+        // redirect to the login page with new domain name
+        response.sendRedirect("/t/" + domainToRegister + "/carbon/account-mgt/account_mgt.jsp");
+        return;
+    } else {
+        session.removeAttribute("temp-domain-to-register");
+        session.removeAttribute("validate-domain-success-key");
+
+        // now redirect to the account_mgt.js with the failure
+        session.setAttribute("domain-validation-failure", "true");
+        response.sendRedirect("../account-mgt/account_mgt.jsp");
+        return;
+    }
+} catch (RegistryException e) {
+%>
+  <div>Error in finishing the validation.</div>
+<%
+    return;
+}
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/pom.xml b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/pom.xml
new file mode 100644
index 0000000..28fe6f9
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/pom.xml
@@ -0,0 +1,88 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>account-mgt-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.account.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Account Management</name>
+
+    <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>
+                        <Private-Package>
+                            org.wso2.carbon.account.mgt.*,
+                        </Private-Package>
+                        <Import-Package>
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.email.verification</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.tenant.mgt</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>atlassian-jira</artifactId>
+            <version>1.0.0.wso2v1</version>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/beans/AccountInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/beans/AccountInfoBean.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/beans/AccountInfoBean.java
new file mode 100644
index 0000000..ca03e48
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/beans/AccountInfoBean.java
@@ -0,0 +1,40 @@
+/*
+ *  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.account.mgt.beans;
+
+public class AccountInfoBean {
+    private String firstname;
+    private String lastname;
+
+    public String getFirstname() {
+        return firstname;
+    }
+
+    public void setFirstname(String firstname) {
+        this.firstname = firstname;
+    }
+
+    public String getLastname() {
+        return lastname;
+    }
+
+    public void setLastname(String lastname) {
+        this.lastname = lastname;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/internal/AccountMgtServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/internal/AccountMgtServiceComponent.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/internal/AccountMgtServiceComponent.java
new file mode 100644
index 0000000..4707b02
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/internal/AccountMgtServiceComponent.java
@@ -0,0 +1,139 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.account.mgt.internal;
+
+import org.wso2.carbon.account.mgt.util.Util;
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.osgi.service.component.ComponentContext;
+
+/**
+ * @scr.component name="org.wso2.carbon.account.mgt" immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ * @scr.reference name="emailverification.service" interface=
+ *                "org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setEmailVerificationService"
+ *                unbind="unsetEmailVerificationService"
+ * @scr.reference name="org.wso2.carbon.tenant.mgt.listener.service"
+ *                interface="org.wso2.carbon.stratos.common.listeners.TenantMgtListener"
+ *                cardinality="0..n" policy="dynamic"
+ *                bind="setTenantMgtListenerService"
+ *                unbind="unsetTenantMgtListenerService"
+ * @scr.reference name="default.tenant.billing.service"
+ *                interface="org.wso2.carbon.stratos.common.TenantBillingService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setTenantBillingService"
+ *                unbind="unsetTenantBillingService"
+ */
+public class AccountMgtServiceComponent {
+    private static Log log = LogFactory.getLog(AccountMgtServiceComponent.class);
+    private static ConfigurationContextService configContextService = null;
+    private static TenantBillingService billingService = null;
+    
+    protected void activate(ComponentContext context) {
+        try {
+            Util.loadEmailVerificationConfig();
+            log.debug("******* Stratos account management bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Stratos account management bundle failed activating ****", e);
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Stratos account managment bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Setting the ConfigurationContext");
+        }
+        configContextService = contextService;
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        if (log.isDebugEnabled()) {
+            log.debug("Unsetting the ConfigurationContext");
+        }
+    }
+
+    protected void setEmailVerificationService(EmailVerifcationSubscriber emailService) {
+        Util.setEmailVerificationService(emailService);
+    }
+
+    protected void unsetEmailVerificationService(EmailVerifcationSubscriber emailService) {
+        Util.setEmailVerificationService(null);
+    }
+
+    protected void setTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.addTenantMgtListenerService(tenantMgtListener);
+    }
+
+    protected void unsetTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        Util.removeTenantMgtListenerService(tenantMgtListener);
+    }
+    
+    protected void setTenantBillingService(TenantBillingService tenantBillingService) {
+        billingService = tenantBillingService;
+    }
+    
+    protected void unsetTenantBillingService(TenantBillingService tenantBilling) {
+        setTenantBillingService(null);
+    }
+    
+    public static TenantBillingService getBillingService() {
+        return billingService;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/AccountMgtService.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/AccountMgtService.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/AccountMgtService.java
new file mode 100644
index 0000000..17b83e4
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/AccountMgtService.java
@@ -0,0 +1,416 @@
+/*
+ * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.account.mgt.services;
+
+import org.wso2.carbon.account.mgt.beans.AccountInfoBean;
+import org.wso2.carbon.account.mgt.util.Util;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.tenant.mgt.util.TenantMgtUtil;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Account Management Service Class
+ */
+public class AccountMgtService extends AbstractAdmin {
+    private static final Log log = LogFactory.getLog(AccountMgtService.class);
+
+    /**
+     * Updates the contact email.
+     *
+     * @param contactEmail email
+     * @throws Exception, if update contact failed.
+     */
+    public void updateContact(String contactEmail) throws Exception {
+        EmailVerifcationSubscriber emailverifier = Util.getEmailVerificationService();
+
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information for the tenant id: " +
+                    tenantId + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // generating the confirmation key
+        String confirmationKey = UUIDGenerator.generateUUID();
+        UserRegistry superTenantSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        Resource resource;
+        String emailVerificationPath = StratosConstants.ADMIN_EMAIL_VERIFICATION_FLAG_PATH +
+                RegistryConstants.PATH_SEPARATOR + tenantId;
+        if (superTenantSystemRegistry.resourceExists(emailVerificationPath)) {
+            resource = superTenantSystemRegistry.get(emailVerificationPath);
+        } else {
+            resource = superTenantSystemRegistry.newResource();
+        }
+        resource.setContent(confirmationKey);
+        superTenantSystemRegistry.put(emailVerificationPath, resource);
+
+        try {
+            Map<String, String> datatostore = new HashMap<String, String>();
+            datatostore.put("first-name",
+                    ClaimsMgtUtil.getFirstName(Util.getRealmService(), tenantId));
+            datatostore.put("email", contactEmail);
+            datatostore.put("userName", tenant.getAdminName());
+            datatostore.put("tenantDomain", tenant.getDomain());
+            datatostore.put("confirmationKey", confirmationKey);
+            emailverifier.requestUserVerification(datatostore, Util.getEmailVerifierConfig());
+        } catch (Exception e) {
+            String msg = "Error in adding tenant, tenant domain: " + tenant.getDomain() + ".";
+            log.error(msg);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * gets the contact of the tenant admin
+     *
+     * @throws Exception, if getting the contact email address failed.
+     * @return, the contact email address
+     */
+    public String getContact() throws Exception {
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+        // get the tenant information from the tenant manager
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information for the tenant id: " +
+                    tenantId + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return tenant.getEmail();
+    }
+
+    /**
+     * Updates the fullname information
+     *
+     * @param accountInfoBean profile information stored in AccountInfoBean
+     * @return true, if updated successfully.
+     * @throws Exception UserStoreException.
+     */
+    public boolean updateFullname(AccountInfoBean accountInfoBean) throws Exception {
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+        // get the tenant information from the tenant manager
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information for the tenant id: " +
+                    tenantId + ".";
+            log.info(msg, e);
+            throw new Exception(msg, e);
+        }
+        RealmService realmService = Util.getRealmService();
+        try {
+            Map<String, String> claimsMap = new HashMap<String, String>();
+            claimsMap.put(UserCoreConstants.ClaimTypeURIs.GIVEN_NAME,
+                    accountInfoBean.getFirstname());
+            claimsMap.put(UserCoreConstants.ClaimTypeURIs.SURNAME, accountInfoBean.getLastname());
+            UserStoreManager userStoreManager =
+                    (UserStoreManager) realmService.getTenantUserRealm(tenantId)
+                            .getUserStoreManager();
+            userStoreManager.setUserClaimValues(
+                    ClaimsMgtUtil.getAdminUserNameFromTenantId(realmService, tenantId),
+                    claimsMap, UserCoreConstants.DEFAULT_PROFILE);
+            log.info("FirstName: " + accountInfoBean.getFirstname() +
+                    " has been updated to the tenant admin " +
+                    ClaimsMgtUtil.getAdminUserNameFromTenantId(realmService, tenantId) + " of " +
+                    tenant.getDomain());
+            
+            //Notify tenant update to all listeners
+            TenantInfoBean tenantInfoBean = new TenantInfoBean();
+            tenantInfoBean.setTenantId(tenantId);
+            tenantInfoBean.setFirstname(accountInfoBean.getFirstname());
+            tenantInfoBean.setLastname(accountInfoBean.getLastname());
+            Util.alertTenantUpdate(tenantInfoBean);
+            
+            return true;
+        } catch (Exception e) {
+            // this is expected, as many users haven't given their fullnames
+            // during their registration.
+            String msg =
+                    "Error in updating the firstname: " + accountInfoBean.getFirstname() +
+                            " for the tenant admin: " +
+                            ClaimsMgtUtil.getAdminUserNameFromTenantId(realmService, tenantId);
+            log.info(msg);
+            throw new Exception(msg, e);
+        }
+    }
+
+    /**
+     * gets the profile information - saved as claims -
+     * currently saved claims are first name and last name - hence the profile so far is a fullname.
+     *
+     * @return AccountInfoBean - Currently depicts the fullname as an object.
+     * @throws Exception, UserStoreException
+     */
+    public AccountInfoBean getFullname() throws Exception {
+
+        String firstname = "", lastname = "";
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+        // get the tenant information from the tenant manager
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information for the tenant id: " +
+                    tenantId + ".";
+            log.info(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        // getting the other parameters from the claims.
+        try {
+            firstname = ClaimsMgtUtil.getFirstName(Util.getRealmService(), tenantId);
+
+        } catch (Exception e) {
+            String msg = "Error in retrieving the firstname for the admin of the domain " +
+                    tenant.getDomain();
+            log.info(msg);
+        }
+        try {
+            lastname = ClaimsMgtUtil.getLastName(Util.getRealmService(), tenantId);
+        } catch (Exception e) {
+            // this is expected, as many users haven't given their lastnames
+            // during their registration.
+            String msg = "Error in retrieving the Lastname for the admin of the domain " +
+                    tenant.getDomain();
+            log.info(msg);
+        }
+
+        AccountInfoBean accountInfoBean = new AccountInfoBean();
+        accountInfoBean.setFirstname(firstname);
+        accountInfoBean.setLastname(lastname);
+        return accountInfoBean;
+    }
+
+
+    /**
+     * deactivates the tenant
+     *
+     * @throws Exception, if deactivating the tenant failed.
+     */
+    public void deactivate() throws Exception {
+        // The one who have a proper permission will be able to deactivate the tenant.
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+        try {
+            tenantManager.deactivateTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in deactivating the tenant id: " + tenantId + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+
+        //Notify tenant deactivation to Listeners
+        Util.alertTenantDeactivation(tenantId);
+    }
+
+    /**
+     * checks whether the domain is validated.
+     *
+     * @return true, if the domain has been validated.
+     * @throws Exception, if the domain validation failed.
+     */
+    public boolean isDomainValidated() throws Exception {
+        // first we will get the current domain name
+        TenantManager tenantManager = Util.getTenantManager();
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+        // get the tenant information from the tenant manager
+        Tenant tenant;
+        try {
+            tenant = (Tenant) tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg = "Error in retrieving the tenant information for the tenant id: " +
+                    tenantId + ".";
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        String domainName = tenant.getDomain();
+        TenantMgtUtil.validateDomain(domainName);
+
+        String domainValidationPath = StratosConstants.TENANT_DOMAIN_VERIFICATION_FLAG_PATH +
+                RegistryConstants.PATH_SEPARATOR + tenantId;
+        UserRegistry superTenantRegistry = Util.getGovernanceSystemRegistry(
+                MultitenantConstants.SUPER_TENANT_ID);
+        if (superTenantRegistry.resourceExists(domainValidationPath)) {
+            Resource validationFlagR = superTenantRegistry.get(domainValidationPath);
+            return "true".equals(validationFlagR.getProperty(domainName));
+        }
+        return false;
+    }
+
+    /**
+     * If the domain validation has been completed.
+     *
+     * @param validatedDomain the domain being validated.
+     * @param successKey      success key
+     * @return true, if the domain has been validated successfully.
+     * @throws Exception, if the domain validation failed.
+     */
+    public boolean finishedDomainValidation(
+            String validatedDomain, String successKey) throws Exception {
+        // create a flag on domain validation, so that we can move the content
+        // of the current domain name to the new validated domain name
+        if (!CommonUtil.validateDomainFromSuccessKey(Util.getGovernanceSystemRegistry(
+                MultitenantConstants.SUPER_TENANT_ID), validatedDomain, successKey)) {
+            String msg = "Domain: " + validatedDomain + " is not validated against successKey: " +
+                    successKey + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+
+        // we keep an entry about domain validation here.
+
+        // first we will get the current domain name
+        UserRegistry registry = (UserRegistry) getGovernanceRegistry();
+        if (registry == null) {
+            // we can't continue without having a valid registry in the session
+            String msg = "Error in retrieving the registry for the login tenant.";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+        int tenantId = registry.getTenantId();
+
+        // keep the domain validation path.
+
+        String domainValidationPath = StratosConstants.TENANT_DOMAIN_VERIFICATION_FLAG_PATH +
+                RegistryConstants.PATH_SEPARATOR + tenantId;
+        UserRegistry superTenantRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        Resource validationFlagR = superTenantRegistry.newResource();
+        validationFlagR.setProperty(validatedDomain, "true");
+        superTenantRegistry.put(domainValidationPath, validationFlagR);
+
+        return true;
+    }
+
+    /**
+     * Check whether the domain is available.
+     *
+     * @param domainName domain name
+     * @return true, if the domain is available to register.
+     * @throws Exception, if the domain validation failed.
+     */
+    public boolean checkDomainAvailability(String domainName) throws Exception {
+        TenantManager tenantManager = Util.getTenantManager();
+        int tenantId = tenantManager.getTenantId(domainName);
+        return tenantId < 0;
+    }
+
+    /**
+     * check whether the email has been validated.
+     *
+     * @throws Exception, if the validation failed.
+     * @return, true if already validated.
+     */
+    public boolean isEmailValidated() throws Exception {
+        UserRegistry userRegistry = (UserRegistry) getGovernanceRegistry();
+        if (userRegistry.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) {
+            // no email validation step required for super tenant
+            return true;
+        }
+
+        String email = getContact();
+        UserRegistry superTenantSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        String emailVerificationPath = StratosConstants.ADMIN_EMAIL_VERIFICATION_FLAG_PATH +
+                RegistryConstants.PATH_SEPARATOR +
+                userRegistry.getTenantId();
+        if (!superTenantSystemRegistry.resourceExists(emailVerificationPath)) {
+            // the confirmation key should exist,otherwise fail registration
+            return false;
+        }
+        Resource resource = superTenantSystemRegistry.get(emailVerificationPath);
+
+        return "true".equals(resource.getProperty(email));
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/EmailValidationService.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/EmailValidationService.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/EmailValidationService.java
new file mode 100644
index 0000000..a8af206
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/services/EmailValidationService.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.account.mgt.services;
+
+import org.wso2.carbon.account.mgt.internal.AccountMgtServiceComponent;
+import org.wso2.carbon.account.mgt.util.Util;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Email Validation Service
+ */
+public class EmailValidationService {
+    private static final Log log = LogFactory.getLog(EmailValidationService.class);
+
+    /**
+     * Proceed updating the contact email address
+     *
+     * @param domain          tenant domain
+     * @param email           email address
+     * @param confirmationKey confirmation key.
+     * @throws Exception, RegistryException.
+     */
+    public void proceedUpdateContact(String domain, String email, String confirmationKey)
+            throws Exception {
+
+        TenantManager tenantManager = Util.getTenantManager();
+        int tenantId;
+
+        try {
+            tenantId = tenantManager.getTenantId(domain);
+        } catch (UserStoreException e) {
+            String msg = "Error in adding tenant, tenant domain: " + domain + ".";
+            log.error(msg);
+            throw new RegistryException(msg, e);
+        }
+
+        UserRegistry superTenantSystemRegistry = Util.getGovernanceSystemRegistry(
+                MultitenantConstants.SUPER_TENANT_ID);
+        String emailVerificationPath =
+                StratosConstants.ADMIN_EMAIL_VERIFICATION_FLAG_PATH +
+                RegistryConstants.PATH_SEPARATOR + tenantId;
+        if (!superTenantSystemRegistry.resourceExists(emailVerificationPath)) {
+            // the confirmation key should exist,otherwise fail registraion
+            String msg = "The confirmationKey doesn't exist in service.";
+            log.error(msg);
+            throw new RegistryException(msg);
+        }
+        Resource resource = superTenantSystemRegistry.get(emailVerificationPath);
+        String actualConfirmationKey = null;
+        Object content = resource.getContent();
+        if (content instanceof String) {
+            actualConfirmationKey = (String) content;
+        } else if (content instanceof byte[]) {
+            actualConfirmationKey = new String((byte[]) content);
+        }
+
+        if (actualConfirmationKey == null || !actualConfirmationKey.equals(confirmationKey)) {
+            // validation will fail.
+            String msg = "The email confirmation key is not matching";
+            log.error(msg);
+            throw new RegistryException(msg);
+        }
+
+        resource.setProperty(email, "true");
+
+        // now we will really update the tenant email
+        Tenant tenant;
+        try {
+            tenant = tenantManager.getTenant(tenantId);
+        } catch (UserStoreException e) {
+            String msg =
+                    "Error in retrieving the tenant information for the tenant id: " + tenantId +
+                    ".";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+
+        // If TenantActivation is moderated, the mail address associated with the validation link
+        // would not be the tenant email. Otherwise, the validation mail would be the tenant email.
+        if (!CommonUtil.isTenantActivationModerated()) {
+            tenant.setEmail(email);
+        }
+
+        try {
+            tenantManager.updateTenant(tenant);
+        } catch (UserStoreException e) {
+            String msg =
+                    "Error in updating the tenant information for the tenant id: " + tenantId + ".";
+            log.error(msg, e);
+            throw new RegistryException(msg, e);
+        }
+
+        // activate the tenant on successful validation of the email, if it is not already activated.
+        if ("false".equals(resource.getProperty(StratosConstants.IS_EMAIL_VALIDATED))) {
+            tenantManager.activateTenant(tenantId);
+            // set the registry flag
+            resource.editPropertyValue(StratosConstants.IS_EMAIL_VALIDATED, "false", "true");
+
+            if (log.isDebugEnabled()) {
+                log.debug("Tenant : " + tenantId + " is activated after validating the " +
+                          "email of the tenant admin.");
+            }
+            
+            //Notify all the listeners that tenant has been activated for the first time
+            Util.alertTenantInitialActivation(tenantId);
+
+            //Activating the usage plan
+            try{
+                AccountMgtServiceComponent.getBillingService().activateUsagePlan(domain);
+            }catch(Exception e){
+                log.error("Error occurred while activating the usage plan for tenant: " + domain
+                        + " tenant Id: " + tenantId, e);
+            }
+
+        }
+        
+        //This is considered an update. Hence notify the update to all listeners
+        TenantInfoBean tenantInfoBean = new TenantInfoBean();
+        tenantInfoBean.setTenantId(tenantId);
+        tenantInfoBean.setTenantDomain(domain);
+        tenantInfoBean.setEmail(email);
+        Util.alertTenantUpdate(tenantInfoBean);
+
+        // update the registry
+        superTenantSystemRegistry.put(emailVerificationPath, resource);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/util/Util.java b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/util/Util.java
new file mode 100644
index 0000000..25f7673
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/java/org/wso2/carbon/account/mgt/util/Util.java
@@ -0,0 +1,173 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.account.mgt.util;
+
+import org.wso2.carbon.email.verification.util.EmailVerifcationSubscriber;
+import org.wso2.carbon.email.verification.util.EmailVerifierConfig;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import org.apache.axis2.context.MessageContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+/**
+ * Util methods for AccountMgt
+ */
+public class Util {
+
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+    private static EmailVerifcationSubscriber emailVerificationService = null;
+    private static EmailVerifierConfig emailVerfierConfig = null;
+    private static List<TenantMgtListener> tenantMgtListeners = new ArrayList<TenantMgtListener>();
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static synchronized void setEmailVerificationService(EmailVerifcationSubscriber service) {
+        if (emailVerificationService == null) {
+            emailVerificationService = service;
+        }
+    }
+
+    public static EmailVerifcationSubscriber getEmailVerificationService() {
+        return emailVerificationService;
+    }
+
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static HttpSession getRequestSession() throws RegistryException {
+        MessageContext messageContext = MessageContext.getCurrentMessageContext();
+        if (messageContext == null) {
+            String msg = "Could not get the user's session. Message context not found.";
+            log.error(msg);
+            throw new RegistryException(msg);
+        }
+
+        HttpServletRequest request =
+                (HttpServletRequest) messageContext.getProperty("transport.http.servletRequest");
+
+        return request.getSession();
+    }
+
+    public static void loadEmailVerificationConfig() {
+        String configXml = CarbonUtils.getCarbonConfigDirPath()+ File.separator
+                           + StratosConstants.EMAIL_CONFIG +File.separator +"email-update.xml";
+        emailVerfierConfig = org.wso2.carbon.email.verification.util.Util.loadeMailVerificationConfig(configXml);
+    }
+
+    public static EmailVerifierConfig getEmailVerifierConfig() {
+        return emailVerfierConfig;
+    }
+
+    public static void addTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.add(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+
+    public static void removeTenantMgtListenerService(TenantMgtListener tenantMgtListener) {
+        tenantMgtListeners.remove(tenantMgtListener);
+        sortTenantMgtListeners();
+    }
+    
+    private static void sortTenantMgtListeners() {
+        Collections.sort(tenantMgtListeners, new Comparator<TenantMgtListener>() {
+            public int compare(TenantMgtListener o1, TenantMgtListener o2) {
+                return o1.getListenerOrder() - o2.getListenerOrder();
+            }
+        });
+    }
+    
+    public static void alertTenantRenames(int tenantId, String oldName, 
+                                          String newName) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onTenantRename(tenantId, oldName, newName);
+        }
+    }
+    
+    public static void alertTenantDeactivation(int tenantId) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onTenantDeactivation(tenantId);
+        }
+    }
+    
+    public static void alertTenantInitialActivation(int tenantId) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onTenantInitialActivation(tenantId);
+        }
+    }
+    
+    public static void alertTenantUpdate(TenantInfoBean tenantInfoBean) throws StratosException {
+
+        for (TenantMgtListener tenantMgtLister : tenantMgtListeners) {
+            tenantMgtLister.onTenantUpdate(tenantInfoBean);
+        }
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..e399648
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+  ~
+  ~  Licensed under the Apache License, Version 2.0 (the "License");
+  ~  you may not use this file except in compliance with the License.
+  ~  You may obtain a copy of the License at
+  ~
+  ~       http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~  Unless required by applicable law or agreed to in writing, software
+  ~  distributed under the License is distributed on an "AS IS" BASIS,
+  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~  See the License for the specific language governing permissions and
+  ~  limitations under the License.
+  -->
+
+<component xmlns="http://products.wso2.org/carbon">
+    <ManagementPermissions>
+        <ManagementPermission>
+            <DisplayName>Configure</DisplayName>
+            <ResourceId>/permission/admin/configure</ResourceId>
+        </ManagementPermission>
+        <ManagementPermission>
+            <DisplayName>Account</DisplayName>
+            <ResourceId>/permission/admin/configure/account</ResourceId>
+        </ManagementPermission>
+    </ManagementPermissions>
+</component>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..8b52fd8
--- /dev/null
+++ b/components/stratos/account-mgt/org.wso2.carbon.account.mgt/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,80 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+
+    <service name="AccountMgtService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.account.mgt.services.AccountMgtService
+        </parameter>
+
+        <operation name="updateContact">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="getContact">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="updateFullname">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="getFullname">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="deactivate">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="isDomainValidated">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="finishedDomainValidation">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="checkDomainAvailability">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+
+        <operation name="isEmailValidated">
+            <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+        </operation>
+        <parameter name="adminService" locked="true">true</parameter>
+    </service>
+
+    <service name="EmailValidationService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.account.mgt.services.EmailValidationService
+        </parameter>
+
+        <operation name="proceedUpdateContact">
+        </operation>
+    </service>
+
+    <parameter name="hiddenService" locked="true">true</parameter>
+
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/account-mgt/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/account-mgt/pom.xml b/components/stratos/account-mgt/pom.xml
new file mode 100644
index 0000000..c58b0a4
--- /dev/null
+++ b/components/stratos/account-mgt/pom.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>account-mgt-parent</artifactId>
+    <packaging>pom</packaging>
+    <name>WSO2 Stratos - Account  Management Parent Module</name>
+    <description>WSO2 Stratos Account Management Parent Module</description>
+    <url>http://wso2.org</url>
+
+    <modules>
+        <module>org.wso2.carbon.account.mgt/2.1.0</module>
+        <module>org.wso2.carbon.account.mgt.ui/2.1.0</module>
+    </modules>
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/pom.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/pom.xml
new file mode 100644
index 0000000..5396a74
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/pom.xml
@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights 
+	Reserved. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); 
+	~ you may not use this file except in compliance with the License. ~ You 
+	may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 
+	~ ~ Unless required by applicable law or agreed to in writing, software ~ 
+	distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT 
+	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the 
+	License for the specific language governing permissions and ~ limitations 
+	under the License. -->
+<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.wso2.carbon</groupId>
+		<artifactId>adc-mgt</artifactId>
+		<version>2.1.0</version>
+                <relativePath>../../pom.xml</relativePath>
+	</parent>
+
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.wso2.carbon.adc.mgt.cli</artifactId>
+        <version>2.1.3</version>
+	<packaging>jar</packaging>
+	<name>WSO2 Carbon - ADC Management CLI</name>
+	<description>ADC management CLI bundle</description>
+	<url>http://wso2.org</url>
+	
+	<properties>
+		<slf4j.version>1.7.5</slf4j.version>
+	</properties>
+
+	<dependencies>
+		<!-- <dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.ui</artifactId>
+		</dependency> -->
+		<!-- Adding HttpClient dependencies. Those were resolved with above one -->
+		<dependency>
+			<groupId>commons-httpclient</groupId>
+			<artifactId>commons-httpclient</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.securevault</groupId>
+			<artifactId>org.wso2.securevault</artifactId>
+			<version>1.0.0-wso2v2</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.httpcomponents.wso2</groupId>
+			<artifactId>httpcore</artifactId>
+			<version>4.1.0-wso2v1</version>
+		</dependency>
+		<dependency>
+			<groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.adc.mgt.stub</artifactId>
+			<version>4.1.3</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-cli</groupId>
+			<artifactId>commons-cli</artifactId>
+			<version>1.2</version>
+		</dependency>
+		<dependency>
+			<groupId>jline</groupId>
+			<artifactId>jline</artifactId>
+			<version>2.11</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+			<version>3.1</version>
+		</dependency>
+		<dependency>
+			<groupId>commons-validator</groupId>
+			<artifactId>commons-validator</artifactId>
+			<version>1.4.0</version>
+		</dependency>
+		<!-- Logging -->
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-api</artifactId>
+			<version>${slf4j.version}</version>
+		</dependency>
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-log4j12</artifactId>
+			<version>${slf4j.version}</version>
+			<scope>runtime</scope>
+		</dependency>
+		<dependency>
+			<groupId>com.google.code.gson</groupId>
+			<artifactId>gson</artifactId>
+			<version>2.1</version>
+		</dependency>
+	</dependencies>
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<configuration>
+					<archive>
+						<manifest>
+							<mainClass>org.wso2.carbon.adc.mgt.cli.CliTool</mainClass>
+						</manifest>
+					</archive>
+					<descriptors>
+						<descriptor>src/main/assembly/src.xml</descriptor>
+					</descriptors>
+				</configuration>
+				<executions>
+					<execution>
+						<id>make-assembly</id> <!-- this is used for inheritance merges -->
+						<phase>package</phase> <!-- bind to the packaging phase -->
+						<goals>
+							<goal>single</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/assembly/src.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
new file mode 100644
index 0000000..80e2e06
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/assembly/src.xml
@@ -0,0 +1,33 @@
+<!--
+  ~ Copyright 2005-2011 WSO2, Inc. (http://wso2.com)
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~ http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+	<id>Tool</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<dependencySets>
+		<dependencySet>
+			<outputDirectory>/</outputDirectory>
+			<useProjectArtifact>true</useProjectArtifact>
+			<unpack>true</unpack>
+			<scope>runtime</scope>
+		</dependencySet>
+	</dependencySets>
+</assembly>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CliTool.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CliTool.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CliTool.java
new file mode 100644
index 0000000..1ff4f91
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/CliTool.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import static org.wso2.carbon.adc.mgt.cli.utils.CliConstants.STRATOS_DIR;
+
+import java.io.File;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is used for input the commands through CLITool, command prompt.
+ */
+public class CliTool {
+
+	private static final Logger logger = LoggerFactory.getLogger(CliTool.class);
+
+	/**
+	 * Main executable method used to call from CLI.
+	 * 
+	 */
+	public static void main(final String[] args) {
+		CliTool cliTool = new CliTool();
+		cliTool.createConfigDirectory();
+		cliTool.handleConsoleInputs(args);
+	}
+
+	/**
+	 * Here is the place all the command line inputs get processed
+	 * 
+	 * @param arguments
+	 *            passed to CLI tool.
+	 */
+	private void handleConsoleInputs(String[] arguments) {
+		if (logger.isInfoEnabled()) {
+			logger.info("Stratos CLI Started...");
+		}
+		StratosApplication application = new StratosApplication();
+		application.start(arguments);
+	}
+
+	private void createConfigDirectory() {
+		File stratosFile = new File(System.getProperty("user.home"), STRATOS_DIR);
+		if (stratosFile.exists()) {
+			if (logger.isInfoEnabled()) {
+				logger.info("Using directory: {}", stratosFile.getPath());
+			}
+		} else {
+			if (stratosFile.mkdir()) {
+				if (logger.isInfoEnabled()) {
+					logger.info("Created directory: {}", stratosFile.getPath());
+				}
+			} else if (logger.isWarnEnabled()) {
+				logger.warn("Failed to created directory: {}", stratosFile.getPath());
+			}
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/Command.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/Command.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/Command.java
new file mode 100644
index 0000000..5e3a250
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.mgt.cli/2.1.3/src/main/java/org/wso2/carbon/adc/mgt/cli/Command.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2013, WSO2, Inc. http://wso2.org
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package org.wso2.carbon.adc.mgt.cli;
+
+import org.apache.commons.cli.Options;
+import org.wso2.carbon.adc.mgt.cli.exception.CommandException;
+
+public interface Command<T extends CommandContext> {
+
+	/**
+	 * @return The name of the command
+	 */
+	String getName();
+
+	/**
+	 * Information about the command
+	 * 
+	 * @return The description of the command
+	 */
+	String getDescription();
+
+	/**
+	 * This should return the syntax required for the command.
+	 * 
+	 * Used to display help.
+	 * 
+	 * @return The syntax for this command
+	 */
+	String getArgumentSyntax();
+
+	/**
+	 * The options accepted by the command
+	 * 
+	 * @return The Options for the commands
+	 */
+	Options getOptions();
+
+	/**
+	 * Executing the commands. Returns a code
+	 * 
+	 * @param context
+	 *            The context assoicated with the Command Line Application
+	 * @param args
+	 *            The arguments for the command
+	 * @return The status code
+	 * @throws CommandException
+	 *             if any errors occur when executing the command
+	 */
+	int execute(T context, String[] args) throws CommandException;
+
+}


[25/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
new file mode 100644
index 0000000..9b4f609
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.test;
+
+import junit.framework.TestCase;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+public class TriggerTest extends TestCase {
+    private static final String BILLING_CONFIG = "billing-config.xml";
+    private static final String SELLER_ID = "carbonHome2TestShop";
+    private BillingEngine billingEngine;
+
+    public void setUp() throws Exception {
+        /*RuleServerManager ruleServerManager = new RuleServerManager();
+        RuleServerConfiguration configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+        Util.setRuleEngineConfigService(ruleServerManager);
+
+        String carbonHome = "src/test/resources/carbonhome2";
+        System.setProperty("carbon.home", carbonHome);
+        System.setProperty("carbon.config.dir.path", carbonHome + "/repository/conf");
+
+        SessionDescription sessionDescription = new SessionDescription();
+        sessionDescription.setSessionType(SessionDescription.STATEFUL_SESSION);
+        ruleServerManager = new RuleServerManager();// TODO to get from a OSGI service
+        configuration = new RuleServerConfiguration(new JSR94BackendRuntimeFactory());
+        ruleServerManager.init(configuration);
+
+        Util.setRuleEngineConfigService(ruleServerManager);
+        */
+
+        String configFile = CarbonUtils.getCarbonConfigDirPath() + "/" + BILLING_CONFIG;
+        BillingConfiguration billingConfiguration = new BillingConfiguration(configFile);
+
+        DataSource dataSource = billingConfiguration.getDataSource();
+        assertNotNull("data should be not null", dataSource);
+        try {
+            if (BillingManager.getInstance() != null) {
+                BillingManager.destroyInstance();
+            }
+        } catch (Exception e) {
+
+        }
+        BillingManager billingManager = new BillingManager(billingConfiguration);
+        //billingManager.scheduleBilling();
+        billingEngine = billingManager.getBillingEngine(SELLER_ID);
+    }
+
+    public void testEngine() throws BillingException {
+        TestUtils.deleteAllTables();
+        // first enter some items
+        String[] itemNames = {"item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8"};
+        Cash[] itemCosts = {new Cash("$1.2"), new Cash("$2.12"), new Cash("$3.24"), new Cash("$4.34"),
+                new Cash("$5.82"), new Cash("$6.92"), new Cash("$7.11"), new Cash("$8.01")};
+        List<Item> items = new ArrayList<Item>();
+        boolean succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (int i = 0; i < Math.min(itemNames.length, itemCosts.length); i++) {
+                String itemName = itemNames[i];
+                Cash itemCost = itemCosts[i];
+                Item item = new Item();
+                item.setName(itemName);
+                item.setCost(itemCost);
+                List<Item> existingItems = billingEngine.getItemsWithName(itemName);
+                for (Item existingItem : existingItems) {
+                    //billingEngine.deleteItem(existingItem.getId());
+                }
+                billingEngine.addItem(item);
+                items.add(item);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        String[] customerNames = {"customer-1", "customer-2", "customer-3", "customer-4", "customer-5", "customer-6"};
+        List<Customer> customers = new ArrayList<Customer>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            for (String customerName : customerNames) {
+                Customer customer = new Customer();
+                customer.setName(customerName);
+
+                List<Customer> existingCustomers = billingEngine.getCustomersWithName(customerName);
+                for (Customer existingCustomer : existingCustomers) {
+                    //billingEngine.deleteCustomer(existingCustomer.getId());
+                }
+
+                //billingEngine.addCustomer(customer);
+                customers.add(customer);
+            }
+            succeeded = true;
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        // adding the subscriptions
+        List<Subscription> subscriptions = new ArrayList<Subscription>();
+        succeeded = false;
+        try {
+            billingEngine.beginTransaction();
+            // first we clean the subscription table
+
+            int[] subIdToItemId = {0, 3, 2, 1, 4, 7, 6, 5, 2, 3, 1, 1, 4, 6, 5, 0};
+            int[] subIdToCustomerId = {0, 3, 2, 1, 4, 1, 0, 5, 2, 3, 1, 1, 4, 0, 5, 0};
+            String[] payment1 = {"$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8",
+                    "$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2", "$5", "$0.2"};
+            String[] payment2 = {"$5", "$2", "$3.2", "$1", "$1.2", "$4", "0.2",
+                    "$5", "$0.2", "$0.5", "$3.2", "$2", "$1.8", "$4", "1", "0.8"};
+
+            // then get some customers subscribed to items
+            Calendar calendarToStart = Calendar.getInstance();
+            calendarToStart.set(Calendar.YEAR, 2010);
+            calendarToStart.set(Calendar.MONTH, Calendar.JANUARY);
+            calendarToStart.set(Calendar.DAY_OF_MONTH, 20);
+            calendarToStart.set(Calendar.HOUR_OF_DAY, 12);
+            calendarToStart.set(Calendar.MINUTE, 10);
+            calendarToStart.set(Calendar.SECOND, 20);
+            long timestampToStart = calendarToStart.getTimeInMillis();
+            for (int i = 0; i < 15; i++) {
+                long startTime = (10000 * i) % 60000 + timestampToStart;
+                long duration = (5000 * i) % 40000;
+                long endTime = startTime + duration;
+                Customer customer = customers.get(subIdToCustomerId[i]);
+                Item item = items.get(subIdToItemId[i]);
+                Subscription subscription = new Subscription();
+                subscription.setCustomer(customer);
+                subscription.setItem(item);
+                subscription.setActive(true);
+
+                subscription.setActiveSince(new Date(startTime));
+                subscription.setActiveUntil(new Date(endTime));
+
+                billingEngine.addSubscription(subscription);
+                subscriptions.add(subscription);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder1 = new Payment();
+                purchaseOrder1.addSubscription(subscription);
+                purchaseOrder1.setAmount(new Cash(payment1[i]));
+                billingEngine.addPayment(purchaseOrder1);
+
+                // adding purchase order - purchase order1
+                Payment purchaseOrder2 = new Payment();
+                purchaseOrder2.addSubscription(subscription);
+                purchaseOrder2.setAmount(new Cash(payment2[i]));
+                billingEngine.addPayment(purchaseOrder2);
+            }
+
+            succeeded = true;
+
+        } finally {
+            if (succeeded) {
+                billingEngine.commitTransaction();
+            } else {
+                billingEngine.rollbackTransaction();
+            }
+        }
+
+        //billingEngine.generateBill();
+        // instead of calling the billing engine we are triggering the scheduler
+        billingEngine.scheduleBilling();
+
+        // now get the invoice of each customers
+        Cash[] totalCosts = {new Cash("$0.20"), new Cash("$2.12"), new Cash("$3.24"),
+                new Cash("$4.34"), new Cash("$5.82"), new Cash("$6.92")};
+        Cash[] totalPayments = {new Cash("$5.50"), new Cash("$2.80"), new Cash("$5.20"),
+                new Cash("$5.20"), new Cash("$5.20"), new Cash("$10.00")};
+        Cash[] carriedForward = {new Cash("$-4.30"), new Cash("$-0.68"), new Cash("$-1.96"),
+                new Cash("$-0.86"), new Cash("$0.62"), new Cash("$-3.08")};
+
+        assertEquals(6, customers.size());
+        try {
+            Thread.currentThread().sleep(14000);
+        } catch (InterruptedException e) {
+            assertTrue(false);
+        }
+        assertEquals(2, FiveSecondTriggerTester.getCount());
+
+        for (int i = 0; i < customers.size(); i++) {
+
+            Customer customer = customers.get(i);
+            List<Invoice> invoices = billingEngine.getAllInvoices(customer);
+            assertEquals(1, invoices.size());
+            Invoice invoice = invoices.get(0);
+            //Invoice invoice = billingEngine.getLastInvoice(customer);
+            assertEquals(totalCosts[i], invoice.getTotalCost());
+            assertEquals(totalPayments[i], invoice.getTotalPayment());
+            assertEquals(carriedForward[i], invoice.getCarriedForward());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml
new file mode 100644
index 0000000..af722bd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml
@@ -0,0 +1,83 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+    <dbConfig>
+        <url>jdbc:mysql://localhost:3306/billing_test1</url>
+        <userName>billing</userName>
+        <password>billing</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>80</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+    <tasks>
+        <task id="carbonHome1TestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule
+                    scheduleHelperClass="org.wso2.carbon.billing.core.scheduler.scheduleHelpers.OneTimeScheduleHelper">
+                <parameter name="dayToTriggerOn">1</parameter>
+                <parameter name="hourToTriggerOn">0</parameter>
+                <parameter name="timeZone">GMT-8:00</parameter>
+            </schedule>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <!--<handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">multitenancy-billing-rule.xml</parameter>
+                </handler> -->
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+
+        <task id="ruleTestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+    </tasks>
+</billingConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
new file mode 100644
index 0000000..1905308
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
@@ -0,0 +1,15 @@
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+rule customerOneSpecial
+when
+$customer : Customer(name == "customer-1" )
+
+then
+
+Invoice invoice = $customer.getActiveInvoice();
+Cash total = invoice.getTotalCost();
+invoice.setTotalCost(Cash.subtract(total, new Cash("$1")));
+
+end

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
new file mode 100644
index 0000000..c2fcd09
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
@@ -0,0 +1,31 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <subject>WSO2 Governance as a Service - Registration completed</subject>
+    <body>
+        Hi {admin-name},
+        Congratulations!. You have successfully crated an account in WSO2 Governance as a Service.
+        Now you can access your account by visiting the following URL. Please bookmark this URL for
+        the later visits.
+
+        Your account url: https://governance.stratoslive.wso2.com/t/{domain-name}
+
+        Thanks,
+        WSO2 Governance as a Service Team
+    </body>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml
new file mode 100644
index 0000000..3a3f22d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Registration confirmation</subject>
+    <body>
+        Hi,
+        Thank you for registering for an account in WSO2 Governance as a Service. In order to
+        activate your account, Please click the following link and verfiy your email.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../tenant-register/tenant_add_ajaxprocessor.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml
new file mode 100644
index 0000000..3f3b8ea
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml
@@ -0,0 +1,34 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Updating the contact email address</subject>
+    <body>
+        Hi,
+        We got a request to change the contact email address of WSO2 Governance as a Service
+        account. In order to update the contact details, Please click the following link and verfiy
+        your email address.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../account-mgt/update_verifier.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
new file mode 100644
index 0000000..3bde368
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
@@ -0,0 +1,41 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration xmlns="http://www.wso2.org/products/rule/drools">
+    <executionSet uri="simpleItemRuleXML">
+        <source key="file:{conf-dir}/billing-rules1.drl"/>
+
+        <!-- <source>
+
+       <x><![CDATA[
+        rule InvokeABC
+        // rules inbuilt to the rule conf
+        end
+
+        ]]>
+       </x>
+       </source> -->
+        <creation>
+            <property name="source" value="drl"/>
+
+        </creation>
+    </executionSet>
+    <session type="stateless"/>
+    <input name="facts" type="billing" key="dataContext"></input>
+
+    <output name="results" type="billing" key="dataContext"></output>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
new file mode 100644
index 0000000..7dc9d8b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
@@ -0,0 +1,88 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="Demo">
+        <users>
+            <limit>5</limit>
+            <charge>0</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>1000</limit>
+            <!-- mb per user -->
+            <overuseCharge>0</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="SMB">
+        <users>
+            <limit>10</limit>
+            <charge>10</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>25</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+        <userLimit>10</userLimit>
+    </package>
+    <package name="Professional">
+        <users>
+            <limit>50</limit>
+            <charge>50</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="Enterprise">
+        <users>
+            <limit>unlimited</limit>
+            <charge>5000</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>4000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+</packages>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml
new file mode 100644
index 0000000..25e09e8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml
@@ -0,0 +1,23 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!-- configure the notifications -->
+<Notifications>
+    <enabled>true</enabled>
+    <host>http://localhost/feed.xml?product={product}&amp;build={build}&amp;instance={instance.id}&amp;tenant={tenant}</host>
+</Notifications>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml
new file mode 100644
index 0000000..abd2f55
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml
@@ -0,0 +1,86 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+    <dbConfig>
+        <url>jdbc:mysql://localhost:3306/billing_test1</url>
+        <userName>billing</userName>
+        <password>billing</password>
+        <driverName>com.mysql.jdbc.Driver</driverName>
+        <maxActive>80</maxActive>
+        <maxWait>60000</maxWait>
+        <minIdle>5</minIdle>
+    </dbConfig>
+    <tasks>
+        <task id="carbonHome2TestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule
+                    scheduleHelperClass="org.wso2.carbon.billing.test.FiveSecondTriggerCalculator">
+                <parameter name="countUpToLimit">2</parameter>
+            </schedule>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <!--<handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">multitenancy-billing-rule.xml</parameter>
+                </handler> -->
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.test.FiveSecondTriggerTester">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+
+        <task id="ruleTestShop">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <handlers>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.DefaultSubscriptionFeedingHandler">
+                </handler>
+                <handler
+                        class="org.wso2.carbon.billing.core.handlers.SubscriptionTreeBuildingHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.InvoiceCalculationHandler">
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.RuleHandler">
+                    <parameter name="file">billing-rules1.drl</parameter>
+                </handler>
+                <handler class="org.wso2.carbon.billing.core.handlers.DefaultFinalizingHandler">
+                </handler>
+            </handlers>
+			<!--
+            <billDelivery>
+                <email config="multitenancy-bill-email-config.xml"/>
+            </billDelivery>
+			-->
+        </task>
+    </tasks>
+</billingConfig>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
new file mode 100644
index 0000000..1905308
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
@@ -0,0 +1,15 @@
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Invoice;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+
+rule customerOneSpecial
+when
+$customer : Customer(name == "customer-1" )
+
+then
+
+Invoice invoice = $customer.getActiveInvoice();
+Cash total = invoice.getTotalCost();
+invoice.setTotalCost(Cash.subtract(total, new Cash("$1")));
+
+end

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
new file mode 100644
index 0000000..c2fcd09
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
@@ -0,0 +1,31 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <subject>WSO2 Governance as a Service - Registration completed</subject>
+    <body>
+        Hi {admin-name},
+        Congratulations!. You have successfully crated an account in WSO2 Governance as a Service.
+        Now you can access your account by visiting the following URL. Please bookmark this URL for
+        the later visits.
+
+        Your account url: https://governance.stratoslive.wso2.com/t/{domain-name}
+
+        Thanks,
+        WSO2 Governance as a Service Team
+    </body>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml
new file mode 100644
index 0000000..3a3f22d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Registration confirmation</subject>
+    <body>
+        Hi,
+        Thank you for registering for an account in WSO2 Governance as a Service. In order to
+        activate your account, Please click the following link and verfiy your email.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../tenant-register/tenant_add_ajaxprocessor.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml
new file mode 100644
index 0000000..3f3b8ea
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml
@@ -0,0 +1,34 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration>
+    <targetEpr>https://localhost:9443/carbon/email-verification/validator_ajaxprocessor.jsp
+    </targetEpr>
+    <subject>WSO2 Governance as a Service - Updating the contact email address</subject>
+    <body>
+        Hi,
+        We got a request to change the contact email address of WSO2 Governance as a Service
+        account. In order to update the contact details, Please click the following link and verfiy
+        your email address.
+    </body>
+    <footer>
+        Thanks,
+        WSO2 Governance Team
+        http://governance.stratoslive.wso2.com
+    </footer>
+    <redirectPath>../account-mgt/update_verifier.jsp</redirectPath>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
new file mode 100644
index 0000000..3bde368
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
@@ -0,0 +1,41 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<configuration xmlns="http://www.wso2.org/products/rule/drools">
+    <executionSet uri="simpleItemRuleXML">
+        <source key="file:{conf-dir}/billing-rules1.drl"/>
+
+        <!-- <source>
+
+       <x><![CDATA[
+        rule InvokeABC
+        // rules inbuilt to the rule conf
+        end
+
+        ]]>
+       </x>
+       </source> -->
+        <creation>
+            <property name="source" value="drl"/>
+
+        </creation>
+    </executionSet>
+    <session type="stateless"/>
+    <input name="facts" type="billing" key="dataContext"></input>
+
+    <output name="results" type="billing" key="dataContext"></output>
+</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
new file mode 100644
index 0000000..0239204
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
@@ -0,0 +1,88 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="multitenancy-free">
+        <users>
+            <limit>5</limit>
+            <charge>0</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>1000</limit>
+            <!-- mb per user -->
+            <overuseCharge>0</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-small">
+        <users>
+            <limit>10</limit>
+            <charge>10</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>25</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+        <userLimit>10</userLimit>
+    </package>
+    <package name="multitenancy-medium">
+        <users>
+            <limit>50</limit>
+            <charge>50</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>2000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-large">
+        <users>
+            <limit>unlimited</limit>
+            <charge>5000</charge>
+            <!-- $ per user per month -->
+        </users>
+        <resourceVolume>
+            <limit>100</limit>
+            <!--mb per user -->
+        </resourceVolum>
+        <bandwidth>
+            <limit>4000</limit>
+            <!-- mb per user -->
+            <overuseCharge>.1</overuseCharse>
+            <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+</packages>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml
new file mode 100644
index 0000000..25e09e8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml
@@ -0,0 +1,23 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<!-- configure the notifications -->
+<Notifications>
+    <enabled>true</enabled>
+    <host>http://localhost/feed.xml?product={product}&amp;build={build}&amp;instance={instance.id}&amp;tenant={tenant}</host>
+</Notifications>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..e2162ab
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/pom.xml
@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>billing-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.billing.mgt.ui</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Billing - User Interface</name>
+
+    <build>
+
+        <plugins>
+
+            <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.wso2.carbon.billing.mgt.ui.*,
+                        </Export-Package>
+                        <Import-Package>
+                        	org.wso2.carbon.billing.mgt.stub.services.*; version="${carbon.platform.package.import.version.range}",
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,                            
+                            org.apache.lucene.*,
+                            *;resolution:=optional
+                        </Import-Package>
+                        <Carbon-Component>UIBundle</Carbon-Component>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.common.ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.eclipse.equinox</groupId>
+            <artifactId>javax.servlet</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
+            <artifactId>axiom</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+			<artifactId>org.wso2.carbon.billing.mgt.stub</artifactId>
+			<version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.json.wso2</groupId>
+          <artifactId>json</artifactId>
+          <version>1.0.0.wso2v1</version>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/clients/BillingServiceClient.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/clients/BillingServiceClient.java b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/clients/BillingServiceClient.java
new file mode 100644
index 0000000..82b57fe
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/clients/BillingServiceClient.java
@@ -0,0 +1,122 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.ui.clients;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.CarbonConstants;
+import org.wso2.carbon.billing.mgt.stub.beans.xsd.*;
+import org.wso2.carbon.billing.mgt.stub.services.MultitenancyBillingServiceStub;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.ui.CarbonUIUtil;
+import org.wso2.carbon.utils.ServerConstants;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+
+public class BillingServiceClient {
+     private static final Log log = LogFactory.getLog(BillingServiceClient.class);
+
+    private MultitenancyBillingServiceStub stub;
+    private String epr;
+
+    public BillingServiceClient(
+            String cookie, String backendServerURL, ConfigurationContext configContext)
+            throws RegistryException {
+
+        epr = backendServerURL + "MultitenancyBillingService";
+
+        try {
+            stub = new MultitenancyBillingServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate BillingService service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public BillingServiceClient(ServletConfig config, HttpSession session)
+            throws RegistryException {
+
+        String cookie = (String)session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+        String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+        ConfigurationContext configContext = (ConfigurationContext) config.
+                getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+        epr = backendServerURL + "MultitenancyBillingService";
+
+        try {
+            stub = new MultitenancyBillingServiceStub(configContext, epr);
+
+            ServiceClient client = stub._getServiceClient();
+            Options option = client.getOptions();
+            option.setManageSession(true);
+            option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+
+        } catch (AxisFault axisFault) {
+            String msg = "Failed to initiate BillingService service client. " + axisFault.getMessage();
+            log.error(msg, axisFault);
+            throw new RegistryException(msg, axisFault);
+        }
+    }
+
+    public BillingPeriod[] getAvailableBillingPeriods() throws Exception {
+        return stub.getAvailableBillingPeriods();
+    }
+    
+    public BillingPeriod[] getBillingPeriodsBySuperTenant(String tenantDomain) throws Exception {
+        return stub.getAvailableBillingPeriodsBySuperTenant(tenantDomain);
+    }
+
+    public MultitenancyInvoice getPastInvoice(int invoiceId) throws Exception {
+        return stub.getPastInvoice(invoiceId);
+    }
+
+    public MultitenancyInvoice getCurrentInvoice() throws Exception {
+        return stub.getCurrentInvoice();    
+    }
+
+    public int addPayment(Payment payment, String amount) throws Exception{
+        return stub.addPayment(payment, amount);
+    }
+    
+    public int makeAdjustment(Payment payment, String amount) throws Exception {
+        return stub.makeAdjustment(payment, amount);
+    }
+
+    public PaginatedBalanceInfoBean getPaginatedBalanceInfo(int pageNumber) throws Exception {
+        return stub.getPaginatedBalances(pageNumber);    
+    }
+
+    public OutstandingBalanceInfoBean[] getOutstandingBalance(String tenantDomain) throws Exception {
+        return stub.getOutstandingBalance(tenantDomain);
+    }
+    
+    public boolean addDiscount(Discount discount, String tenantDomain) throws Exception {
+        return stub.addDiscount(discount, tenantDomain);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/utils/BillingUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/utils/BillingUtil.java b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/utils/BillingUtil.java
new file mode 100644
index 0000000..97f4e18
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/utils/BillingUtil.java
@@ -0,0 +1,182 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.billing.mgt.ui.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.mgt.stub.beans.xsd.*;
+import org.wso2.carbon.billing.mgt.ui.clients.BillingServiceClient;
+import org.wso2.carbon.registry.common.ui.UIException;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.http.HttpSession;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+public class BillingUtil {
+    private static final Log log = LogFactory.getLog(BillingUtil.class);
+
+    public static BillingPeriod[] getAvailableBillingPeriods(
+            ServletConfig config, HttpSession session) throws UIException {
+        try {
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.getAvailableBillingPeriods();
+        } catch (Exception e) {
+            String msg = "Failed to get available billing periods.";
+            log.error(msg, e);
+            throw new UIException(msg, e);
+        }
+    }
+    
+    public static BillingPeriod[] getAvailableBillingPeriodsBySuperTenant(
+            ServletConfig config, HttpSession session, String tenantDomain) throws UIException {
+
+        try{
+            BillingServiceClient client = new BillingServiceClient(config, session);
+            return client.getBillingPeriodsBySuperTenant(tenantDomain);
+        }catch(Exception e){
+            String msg = "Error occurred while getting available invoice dates for tenant: " +
+                    tenantDomain;
+            log.error(msg, e);
+            throw new UIException(msg, e);
+        }
+    }
+
+    public static String[] getAvailableBillingMonths(ServletConfig config,
+                                 HttpSession session) throws UIException{
+        return getAvailableBillingMonths(getAvailableBillingPeriods(config, session));
+    }
+
+    public static MultitenancyInvoice getPastInvoice(
+            ServletConfig config, HttpSession session, int invoiceId) throws UIException {
+        //int invoiceId = (Integer)session.getAttribute("invoiceId");
+
+        try {
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.getPastInvoice(invoiceId);
+        } catch (Exception e) {
+            String msg = "Failed to get past invoice for invoice id:" + invoiceId + ".";
+            log.error(msg, e);
+            throw new UIException(msg, e);
+        }
+    }
+
+    public static MultitenancyInvoice getCurrentInvoice(
+            ServletConfig config, HttpSession session) throws UIException {
+        try {
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.getCurrentInvoice();
+        } catch (java.lang.Exception e) {
+            String msg = "Failed to get the current invoice.";
+            log.error(msg, e);
+            throw new UIException(msg, e);
+        }
+    }
+
+    public static String[] getAvailableBillingMonths(BillingPeriod[] billingPeriods){
+
+        if(billingPeriods==null || billingPeriods.length==0){
+            return new String[0];
+        }
+
+        String[] billingMonths = new String[billingPeriods.length];
+        DateFormat yearMonthFormat = new SimpleDateFormat("yyyy-MMM-dd");
+        int index = 0;
+        for(BillingPeriod period : billingPeriods){
+            billingMonths[index++] = yearMonthFormat.format(period.getInvoiceDate());
+        }
+        return billingMonths;
+    }
+
+    public static int addPaymentDetails(ServletConfig config, HttpSession session,
+                                        Payment payment, String amount) throws UIException {
+        try{
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.addPayment(payment, amount);
+        }catch (Exception exp){
+            String msg = "Failed to add the payment record " + payment.getDescription();
+            log.error(msg, exp);
+            throw new UIException(msg, exp);
+        }
+    }
+
+    public static int makeAdjustment(ServletConfig config, HttpSession session,
+                                        Payment payment, String amount) throws UIException {
+        try{
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.makeAdjustment(payment, amount);
+        }catch (Exception exp){
+            String msg = "Failed to add the payment record " + payment.getDescription();
+            log.error(msg, exp);
+            throw new UIException(msg, exp);
+        }
+    }
+
+    public static PaginatedBalanceInfoBean getPaginatedBalanceInfo(ServletConfig config, HttpSession session,
+                                                                   int pageNumber) throws UIException{
+        try{
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.getPaginatedBalanceInfo(pageNumber);
+        }catch (Exception exp){
+            String msg = "Failed to get paginated balance info ";
+            log.error(msg, exp);
+            throw new UIException(msg, exp);
+        }
+    }
+
+    public static OutstandingBalanceInfoBean[] getOutstandingBalance(
+            ServletConfig config, HttpSession session, String tenantDomain) throws UIException{
+        try{
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.getOutstandingBalance(tenantDomain);
+        }catch (Exception exp){
+            String msg = "Failed to get balance info for domain: " + tenantDomain;
+            log.error(msg, exp);
+            throw new UIException(msg, exp);
+        }
+    }
+
+    public static boolean addDiscount(
+            ServletConfig config, HttpSession session, Discount discount, String tenantDomain) throws UIException{
+
+        try{
+            BillingServiceClient serviceClient = new BillingServiceClient(config, session);
+            return serviceClient.addDiscount(discount, tenantDomain);
+        }catch (Exception exp){
+            String msg = "Failed to failed to add the discount for tenant: " + discount.getTenantId();
+            log.error(msg, exp);
+            throw new UIException(msg, exp);
+        }
+    }
+
+   /* public static String getModifiedSubscriptionPlan(String plan){
+        if("multitenancy-free".equals(plan)){
+            return StratosConstants.MULTITENANCY_FREE_PLAN;
+        }else if("multitenancy-small".equals(plan)){
+            return StratosConstants.MULTITENANCY_SMALL_PLAN;
+        }else if("multitenancy-medium".equals(plan)){
+            return StratosConstants.MULTITENANCY_MEDIUM_PLAN;
+        }else if("multitenancy-large".equals(plan)){
+            return StratosConstants.MULTITENANCY_LARGE_PLAN;
+        }else{
+            return "Undefined";
+        }
+    }*/
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..1b8a348
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
@@ -0,0 +1,100 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<component xmlns="http://products.wso2.org/carbon">
+    <!-- sample menu configuration -->
+    <menus>
+        <menu>
+            <id>multitenancy_billing_menu</id>
+            <i18n-key>billing.menu</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu></parent-menu>
+            <link>#</link>
+            <region>region4</region>
+            <style-class>home</style-class>
+            <order>23</order>
+            <icon>../services/images/services.gif</icon>
+	        <require-permission>/permission/admin/billing/invoice</require-permission>
+        </menu>
+        <menu>
+            <id>multitenancy_invoice_menu</id>
+            <i18n-key>view.invoice.menu</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>multitenancy_billing_menu</parent-menu>
+            <link>../tenant-billing/past_invoice.jsp</link>
+            <region>region4</region>
+            <order>50</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-billing/images/view-invoice.gif</icon>
+            <require-permission>/permission/admin/billing/invoice</require-permission>
+            <require-not-super-tenant>true</require-not-super-tenant>
+        </menu>
+        <menu>
+            <id>multitenancy_balance_menu</id>
+            <i18n-key>view.balance.menu</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>multitenancy_billing_menu</parent-menu>
+            <link>../tenant-billing/view_balance.jsp</link>
+            <region>region4</region>
+            <order>51</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-billing/images/view-invoice.gif</icon>
+            <require-permission>/permission/admin/billing/invoice</require-permission>
+            <require-super-tenant>true</require-super-tenant>
+        </menu>
+        <menu>
+            <id>adjustment_menu</id>
+            <i18n-key>adjustment.menu</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>multitenancy_billing_menu</parent-menu>
+            <link>../tenant-billing/adjustments.jsp</link>
+            <region>region4</region>
+            <order>52</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-billing/images/view-invoice.gif</icon>
+            <require-permission>/permission/admin/billing/invoice</require-permission>
+            <require-super-tenant>true</require-super-tenant>
+        </menu>
+        <menu>
+            <id>discount_menu</id>
+            <i18n-key>discount.menu</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>multitenancy_billing_menu</parent-menu>
+            <link>../tenant-billing/discounts.jsp</link>
+            <region>region4</region>
+            <order>53</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-billing/images/view-invoice.gif</icon>
+            <require-permission>/permission/admin/billing/invoice</require-permission>
+            <require-super-tenant>true</require-super-tenant>
+        </menu>
+        <menu>
+            <id>multitenancy_interim_invoice_menu</id>
+            <i18n-key>interim.invoice</i18n-key>
+            <i18n-bundle>org.wso2.carbon.billing.mgt.ui.i18n.Resources</i18n-bundle>
+            <parent-menu>multitenancy_billing_menu</parent-menu>
+            <link>../tenant-billing/interim_invoice.jsp</link>
+            <region>region4</region>
+            <order>60</order>
+            <style-class>manage</style-class>
+            <icon>../tenant-billing/images/view-invoice.gif</icon>
+            <require-permission>/permission/admin/billing/invoice</require-permission>
+            <require-not-super-tenant>true</require-not-super-tenant>
+        </menu>
+    </menus>
+
+</component>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/JSResources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/JSResources.properties b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/JSResources.properties
new file mode 100644
index 0000000..bf90999
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/JSResources.properties
@@ -0,0 +1 @@
+empty=To make sure the js properties file is not empty

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/Resources.properties
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/Resources.properties b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/Resources.properties
new file mode 100644
index 0000000..7d0bbbc
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/Resources.properties
@@ -0,0 +1,52 @@
+view.invoice.menu=Invoices
+view.balance.menu=View Balance
+billing.menu=Billing & Metering
+interim.invoice=Interim Invoice
+view.invoice=View Invoice
+invoice.information=Invoice Information for
+invoice.information.head=Invoice Information
+start.date=Invoice period start date
+end.date=Invoice period end date
+invoice.date=Invoice Date
+invoice.summary=Invoice Summary
+subscription=Subscription
+active.since=Active since
+active.until=Active until
+payment=Payment
+transaction.id=Transaction Id
+payment.id=id
+payment.date=Payment Date
+paid.amount=Paid amount
+charges.subscriptions=Charges for Subscriptions
+payment.details=Payment details
+brought.forward=Brought forward
+carried.forward=Carried forward
+total.cost=Total cost
+total.payments=Total payments
+no.invoice.information=Invoice information not available
+no.invoice.information.details=Invoice information is not available because you have not subscribed to any paid packages.
+no.invoice.at.the.moment=Invoice information is not available yet.
+select.billing.month=Select the month
+select.invoice=Select the Invoice
+invoice=Invoice
+month=Month
+enter.tenant.domain=Enter the Tenant Domain
+this.is.active.subscription=This is your current active subscription
+adjustment.menu=Adjustments
+invoice.adjustments=Invoice Adjustments
+find.invoices=Find Invoices
+adjustment.information=Adjustment Information
+submit=Submit
+cancel=Cancel
+amount=Amount $
+description=Description
+discounts=Discounts
+discount.percentage=Discount Percentage
+discount.start.date=Start Date (YYYY-MM-DD)
+discount.end.date=End Date (YYYY-MM-DD)
+discounts.table.title=Discount Information
+discount.menu=Discounts
+tenant.domain=Tenant Domain
+discount.type=Discount Type
+type.percentage=Percentage
+type.amount=Amount
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp
new file mode 100644
index 0000000..3821477
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp
@@ -0,0 +1,66 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="java.util.Date" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Discount" %>
+<%@ page import="java.text.DateFormat" %>
+<%@ page import="java.text.SimpleDateFormat" %>
+<%
+
+    String tenantDomain = request.getParameter("tenantDomain");
+    String percentageStr = request.getParameter("percentage");
+    String amountStr = request.getParameter("amount");
+    String startDateStr = request.getParameter("startDate");
+    String endDateStr = request.getParameter("endDate");
+    String discountType = request.getParameter("discountType");
+
+    Discount discount = new Discount();
+    
+    if("percentage".equals(discountType)){
+        discount.setPercentageType(true);
+        discount.setPercentage(Float.parseFloat(percentageStr));
+    }else if("amount".equals(discountType)){
+        discount.setPercentageType(false);
+        discount.setAmount(Float.parseFloat(amountStr));
+    }
+
+    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
+    discount.setStartDate(df.parse(startDateStr));
+    if(endDateStr!=null){
+        discount.setEndDate(df.parse(endDateStr));
+    }
+    
+    boolean added = false;
+    try{
+        added = BillingUtil.addDiscount(config, session, discount, tenantDomain);
+    }catch (Exception e){
+        e.printStackTrace();
+    }
+
+    if(added){
+        session.setAttribute("discountAdded", "true");
+    }else{
+        session.setAttribute("discountAdded", "false");
+    }
+
+
+%>
+
+<jsp:forward page="discounts.jsp"/>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp
new file mode 100644
index 0000000..25badd8
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp
@@ -0,0 +1,56 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<%@ page import="org.json.JSONObject" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Invoice" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="java.util.Date" %>
+<%
+    String amount = request.getParameter("amount");
+    String transactionId = request.getParameter("transactionId");
+    String invoiceId = request.getParameter("invoiceId");
+
+    Payment payment = new Payment();
+
+    Invoice invoice = new Invoice();
+    invoice.setId(Integer.parseInt(invoiceId));
+    payment.setInvoice(invoice);
+
+    //We set the transaction id as the description
+    payment.setDescription(transactionId);
+    payment.setDate(new Date(System.currentTimeMillis()));
+
+    try{
+        int paymentId = BillingUtil.addPaymentDetails(config, session, payment, amount);
+
+        JSONObject obj = new JSONObject();
+        obj.put("paymentId", paymentId);
+        if(paymentId>0){
+            obj.put("status", "success");
+            obj.put("amount", amount);
+            obj.put("transactionId", transactionId);
+            obj.put("invoiceId", invoiceId);
+        }else{
+            obj.put("status", "fail");
+        }
+        out.write(obj.toString());
+    }catch (Exception e){
+        e.printStackTrace();
+    }
+%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp
new file mode 100644
index 0000000..987a946
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp
@@ -0,0 +1,79 @@
+<%--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8" %>
+<%@ page import="org.apache.axis2.AxisFault" %>
+<%@ page import="org.apache.axis2.client.Options" %>
+<%@ page import="org.apache.axis2.client.ServiceClient" %>
+<%@ page import="org.apache.axis2.context.ConfigurationContext" %>
+<%@ page import="org.json.JSONObject" %>
+<%@ page import="org.wso2.carbon.CarbonConstants" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.beans.xsd.Payment" %>
+<%@ page import="org.wso2.carbon.billing.mgt.stub.services.MultitenancyBillingServiceStub" %>
+<%@ page import="org.wso2.carbon.billing.mgt.ui.utils.BillingUtil" %>
+<%@ page import="org.wso2.carbon.registry.core.exceptions.RegistryException" %>
+<%@ page import="org.wso2.carbon.stratos.common.util.CommonUtil" %>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil" %>
+<%@ page import="org.wso2.carbon.utils.CarbonUtils" %>
+<%@ page import="org.wso2.carbon.utils.ServerConstants" %>
+<%@ page import="java.util.Date" %>
+<%
+    String amount = request.getParameter("amount");
+    String usagePlan = request.getParameter("usagePlan");
+    String regDomain = session.getAttribute("regTenantDomain").toString();
+    String transactionId = request.getParameter("transactionId");
+
+    Payment payment = new Payment();
+    payment.setDescription(regDomain + " " + transactionId);
+    payment.setDate(new Date(System.currentTimeMillis()));
+
+    // Stub to call the billing service in order to add the registration payment record. 
+    MultitenancyBillingServiceStub stub;
+    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
+    String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+    ConfigurationContext configContext = (ConfigurationContext) config.
+            getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
+    String epr = backendServerURL + "MultitenancyBillingService";
+    String adminUserName = CommonUtil.getAdminUserName();
+    String adminPassword = CommonUtil.getAdminPassword();
+
+    try {
+        stub = new MultitenancyBillingServiceStub(configContext, epr);
+
+        ServiceClient client = stub._getServiceClient();
+        Options option = client.getOptions();
+        option.setManageSession(true);
+        option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
+        CarbonUtils.setBasicAccessSecurityHeaders(adminUserName, adminPassword, client);
+        int paymentId = stub.addRegistrationPayment(payment, amount, usagePlan);
+
+        JSONObject obj = new JSONObject();
+        obj.put("paymentId", paymentId);
+        if (paymentId > 0) {
+            obj.put("status", "success");
+            obj.put("amount", amount);
+        } else {
+            obj.put("status", "fail");
+        }
+        out.write(obj.toString());
+
+    } catch (Exception ex) {
+        String msg = "Failed to initiate BillingService service client. " + ex.getMessage();
+        throw new Exception(msg, ex);
+    }
+
+%>


[18/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_template.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_template.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_template.jsp
new file mode 100644
index 0000000..0372c92
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_domain_template.jsp
@@ -0,0 +1,204 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<%@ page
+	import="org.wso2.carbon.validate.domain.ui.clients.ValidateDomainClient"%>
+<%@ page import="org.wso2.carbon.validate.domain.ui.utils.Util"%>
+<%@ page import="org.wso2.carbon.ui.CarbonUIUtil"%>
+<%@ page
+	import="org.wso2.carbon.utils.multitenancy.MultitenantConstants"%>
+<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
+<%@ taglib uri="http://wso2.org/projects/carbon/taglibs/carbontags.jar"
+	prefix="carbon"%>
+<link rel="stylesheet" type="text/css" href="../yui/assets/yui.css">
+<link rel="stylesheet" type="text/css"
+	href="../yui/build/menu/assets/skins/sam/menu.css" />
+<link rel="stylesheet" type="text/css"
+	href="../yui/build/button/assets/skins/sam/button.css" />
+<link rel="stylesheet" type="text/css"
+	href="../yui/build/container/assets/skins/sam/container.css" />
+<link rel="stylesheet" type="text/css"
+	href="../yui/build/autocomplete/assets/skins/sam/autocomplete.css" />
+<link rel="stylesheet" type="text/css"
+	href="../yui/build/editor/assets/skins/sam/editor.css" />
+<link rel="stylesheet" type="text/css"
+	href="../validate-domain/css/validate_domain.css" />
+<jsp:include
+	page="../registry_common/registry_common-i18n-ajaxprocessor.jsp" />
+<script type="text/javascript"
+	src="../registry_common/js/registry_validation.js"></script>
+<script type="text/javascript"
+	src="../registry_common/js/registry_common.js"></script>
+<script type="text/javascript" src="../ajax/js/prototype.js"></script>
+<carbon:jsi18n
+        resourceBundle="org.wso2.carbon.validate.domain.ui.i18n.JSResources"
+        request="<%=request%>" namespace="org.wso2.carbon.validate.domain.ui"/>
+
+<script type="text/javascript" src="../validate-domain/js/validate_domain.js"></script>
+
+<fmt:bundle
+	basename="org.wso2.carbon.validate.domain.ui.i18n.Resources">
+	<%
+	    String domain = request.getParameter("domain");
+		String status = request.getParameter("status");
+	        // get the validation key
+	        ValidateDomainClient client =
+	                Util.getValidateDomainClient(request, config, session);
+	        String domainValidationKey = client.getDomainValidationKey(domain);
+	        if ("unavailable".equals(domainValidationKey)) {
+           %>
+               <script type="text/javascript">
+                   jQuery(document).ready(function() {
+                       CARBON.showErrorDialog('The domain you are trying to validate ' +
+                               'is already taken. Please retry with another domain.');
+                   });
+               </script>
+
+           <%
+               }
+	        //String serverUrl = CarbonUIUtil.getServerURL(config.getServletContext(), session);
+	        String adminConsoleURL = CarbonUIUtil.getAdminConsoleURL("/");
+	        String serverUrl = adminConsoleURL.replace("carbon","services");
+	        // remove the services directory.
+	        String serverRoot =
+	                serverUrl.substring(0, serverUrl.length() - "/services/".length());
+	        // we have to remove the port as well.
+	        if (serverRoot == null) {
+	            serverRoot = "stratoslive.wso2.com";
+	        }
+	        // server root without https
+	        serverRoot = serverRoot.substring(8);
+	        int semiCol = serverRoot.indexOf(':');
+	        if (semiCol >= 0) {
+	            // need to remove the port
+	            serverRoot = serverRoot.substring(0, semiCol);
+	        }
+
+	        // we have additional statement
+	        String statementToIgnoreValidate = "";
+	        if (session.getAttribute(MultitenantConstants.TENANT_DOMAIN) == null) {
+	            statementToIgnoreValidate =
+	                    "or <input type='button' onclick='gotoRegister()' value='Skip the validation step'/>";
+	        }
+	%>
+	<div id="middle">
+
+    <carbon:breadcrumb label="validate"
+        resourceBundle="org.wso2.carbon.validate.domain.ui.i18n.Resources"
+        topPage="false" request="<%=request%>" />
+    
+	<div id="workArea">
+	<h2><fmt:message key="domain.ownership.validation" /></h2>
+
+	<div id="validation-introduction">
+	<p>You can validate your domain using the following method <%=statementToIgnoreValidate%></p>
+	<ul>
+		<li class="catagory">Creating a text file in the domain web
+		ROOT</li>
+<!-- 		<li class="catagory">2. Setting up a CNAME entry in your DNS</li> -->
+	</ul>
+	</div>
+
+	<div id="with-text">
+
+	<table class="styledLeft">
+		<thead>
+			<tr>
+				<th>Validate domain using a text file</th>
+			</tr>
+		</thead>
+		<tbody>
+			<tr>
+				<td>
+				<p>Add a text file inside the web root of your domain with the following configuration:</p>
+				<div class="conf-info">
+				<%
+				    // the filename is hard coded now, a change in this need to be reflected at validateDomainService.jsp
+				%>
+				<p>Filename: <strong>wso2multitenancy.txt</strong></p>
+				<p>Text content: <strong><%=domainValidationKey%></strong></p>
+				</div>
+				<p class="validate-button"><em> Click the 'Validate'
+				button, after you complete the above step </em> <input type="button"
+					value="Validate" onclick="validateWithText('<%=domain%>', '<%=status%>')" /> <span
+					id="busyText"></span></p>
+				<p>
+				<div id="with-text-msg"></div>
+				</p>
+				<p>
+				<div id="with-text-continue" style="visibility: hidden">
+				<form id="validateWithTextForm"
+					onsubmit="return submitValidateWithTextForm('<%=status%>');" 
+					action="submit_validate_domain_ajaxprocessor.jsp" method="post">
+				<input type="hidden" id="with-text-success-key" name="successKey"
+					value="" /> <input type="hidden" name="domain" value="<%=domain%>" />
+				<input type="hidden" id="with-text-status" name="status" value="<%=status%>"/>
+				<input type="submit" value="Continue" /></form>
+				</div>
+				</p>
+				</td>
+			</tr>
+		</tbody>
+	</table>
+	</div>
+
+
+<!-- 	<div id="with-dns"> -->
+
+<!-- 	<table class="styledLeft"> -->
+<!-- 		<thead> -->
+<!-- 			<tr> -->
+<!-- 				<th>Validate domain using a CName entry</th> -->
+<!-- 			</tr> -->
+<!-- 		</thead> -->
+<!-- 		<tbody> -->
+<!-- 			<tr> -->
+<!-- 				<td> -->
+<!-- 				<p>Put a CNAME entry in your DNS with following configuration: -->
+<!-- 				(Note that if you refresh this page, the parameters will be changed) -->
+<!-- 				</p> -->
+<!-- 				<div class="conf-info"> -->
+<%-- 				<p>Name: <strong><%=domainValidationKey%>.<%=domain%></strong></p> --%>
+<!-- 				<p>Type: <strong>CNAME</strong></p> -->
+<%-- 				<p>Value: <strong><%=serverRoot%></strong></p> --%>
+<!-- 				</div> -->
+<!-- 				<p class="validate-button"><em> Click the 'Validate' -->
+<!-- 				button, after you finish setting the CNAME entry </em> <input -->
+<!-- 					type="button" value="Validate" -->
+<%-- 					onclick="validateWithDNS('<%=domain%>', '<%=status%>')" /> <span id="busyDNS"></span> --%>
+<!-- 				</p> -->
+<!-- 				<p> -->
+<!-- 				<div id="with-dns-msg"></div> -->
+<!-- 				</p> -->
+<!-- 				<p> -->
+<!-- 				<div id="with-dns-continue" style="visibility: hidden"> -->
+<!-- 				<form id="validateWithDNSForm" -->
+<!-- 					action="submit_validate_domain_ajaxprocessor.jsp" -->
+<%-- 					onsubmit="return submitValidateWithDNSForm('<%=status%>');" method="post"> --%>
+<!-- 				<input type="hidden" id="with-dns-success-key" name="successKey" -->
+<%-- 					value="" /> <input type="hidden" name="domain" value="<%=domain%>" /> --%>
+<%-- 				<input type="hidden" id="with-dns-status" name="status" value="<%=status%>"/> --%>
+<!-- 				<input type="submit" value="Continue" /></form> -->
+<!-- 				</div> -->
+<!-- 				</p> -->
+<!-- 				</td> -->
+<!-- 			</tr> -->
+<!-- 		</tbody> -->
+<!-- 	</table> -->
+<!-- 	</div> -->
+	</div>
+</fmt:bundle>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_dns_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_dns_ajaxprocessor.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_dns_ajaxprocessor.jsp
new file mode 100644
index 0000000..a2bea9a
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_dns_ajaxprocessor.jsp
@@ -0,0 +1,22 @@
+<%@ page import="org.wso2.carbon.validate.domain.ui.clients.ValidateDomainClient" %>
+<%@ page import="org.wso2.carbon.validate.domain.ui.utils.Util" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+    String domain = request.getParameter("domain");
+    String validationSuccessKey;
+
+    try {
+        ValidateDomainClient client = Util.getValidateDomainClient(request, config, session);
+        validationSuccessKey = client.validateByDNSEntry(domain);
+    } catch (Exception e) {
+        validationSuccessKey = null;
+    }
+
+    if (validationSuccessKey == null || validationSuccessKey.equals("") ||
+            validationSuccessKey.equals("false") || validationSuccessKey.equals("null")) {
+        validationSuccessKey = "----false----";
+    }
+    else if (validationSuccessKey.equals("unavailable")) {
+        validationSuccessKey = "----unavailable----";
+    }
+%><%=validationSuccessKey%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_text_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_text_ajaxprocessor.jsp b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_text_ajaxprocessor.jsp
new file mode 100644
index 0000000..1105363
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain.ui/2.1.0/src/main/resources/web/validate-domain/validate_with_text_ajaxprocessor.jsp
@@ -0,0 +1,22 @@
+<%@ page import="org.wso2.carbon.validate.domain.ui.clients.ValidateDomainClient" %>
+<%@ page import="org.wso2.carbon.validate.domain.ui.utils.Util" %>
+<%@ page contentType="text/html;charset=UTF-8" language="java" %>
+<%
+    String domain = request.getParameter("domain");
+    String validationSuccessKey;
+
+    try {
+        ValidateDomainClient client = Util.getValidateDomainClient(request, config, session);
+        validationSuccessKey = client.validateByTextInRoot(domain);
+    } catch (Exception e) {
+        validationSuccessKey = null;
+    }
+
+    if (validationSuccessKey == null || validationSuccessKey.equals("") ||
+            validationSuccessKey.equals("false") || validationSuccessKey.equals("null")) {
+        validationSuccessKey = "----false----";
+    }
+    else if (validationSuccessKey.equals("unavailable")) {
+        validationSuccessKey = "----unavailable----";
+    }
+%><%=validationSuccessKey%>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/pom.xml b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/pom.xml
new file mode 100644
index 0000000..89d1f73
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/pom.xml
@@ -0,0 +1,80 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>domain-validator-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.validate.domain</artifactId>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Validate domains</name>
+
+    <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.wso2.carbon.validate.domain.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/internal/ValidateDomainServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/internal/ValidateDomainServiceComponent.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/internal/ValidateDomainServiceComponent.java
new file mode 100644
index 0000000..eb792f9
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/internal/ValidateDomainServiceComponent.java
@@ -0,0 +1,87 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.validate.domain.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.validate.domain.util.Util;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="org.wso2.carbon.validate.domain"
+ *                immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ *                interface="org.wso2.carbon.utils.ConfigurationContextService"
+ *                cardinality="1..1" policy="dynamic"
+ *                bind="setConfigurationContextService"
+ *                unbind="unsetConfigurationContextService"
+ */
+public class ValidateDomainServiceComponent {
+    private static Log log = LogFactory.getLog(ValidateDomainServiceComponent.class);
+    private static ConfigurationContextService configContextService;
+    
+    protected void activate(ComponentContext context) {
+        log.debug("******* Governance domain validation bundle is activated ******* ");
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Governance domain validation bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+    
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        ValidateDomainServiceComponent.configContextService = contextService;
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+        ValidateDomainServiceComponent.configContextService = null;
+    }
+
+    public static ConfigurationContextService getConfigContextService() {
+        return configContextService;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainAdminService.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainAdminService.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainAdminService.java
new file mode 100644
index 0000000..05f885a
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainAdminService.java
@@ -0,0 +1,39 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.validate.domain.services;
+
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.validate.domain.util.Util;
+
+/**
+ * The service allow users to validate domains before sign in.
+ */
+public class ValidateDomainAdminService extends AbstractAdmin {
+
+    public String getDomainValidationKey(String domain) throws Exception {
+        return Util.getDomainValidationKeyWithLogin(domain);
+    }
+
+    public String validateByDNSEntry(String domain)  throws Exception {
+        return Util.validateByDNSEntry(domain);
+    }
+
+    public String validateByTextInRoot(String domain) throws Exception {
+        return Util.validateByTextInRoot(domain);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainService.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainService.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainService.java
new file mode 100644
index 0000000..53cef09
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/services/ValidateDomainService.java
@@ -0,0 +1,82 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.validate.domain.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.validate.domain.util.Util;
+
+/**
+ * The service allow users to validate domains before sign in.
+ */
+public class ValidateDomainService {
+    private static final Log log = LogFactory.getLog(ValidateDomainService.class);
+
+    /**
+     * get domain validation key
+     *
+     * @param domain - tenant domain
+     * @return domain validation key
+     * @throws Exception, if getting the validation key failed.
+     */
+    public String getDomainValidationKey(String domain) throws Exception {
+        // for the non admin case, we are not issuing validation keys if the domain already exists.
+
+        // Now we register first, before coming to the domain validation.
+//        if (!Util.checkDomainAvailability(domain)) {
+//            String msg = "Domain " + domain + " is already taken.";
+//            log.info(msg);
+//            return "unavailable";
+//        }
+        return Util.getDomainValidationKeyWithoutLogin(domain);
+    }
+
+    /**
+     * Validate by DNS Entry
+     *
+     * @param domain - tenant domain
+     * @throws Exception, if validation failed.
+     * @return, successkey
+     */
+    public String validateByDNSEntry(String domain) throws Exception {
+//        if (!Util.checkDomainAvailability(domain)) {
+//            String msg = "Domain " + domain + " is already taken.";
+//            log.info(msg);
+//            return "unavailable";
+//        }
+        return Util.validateByDNSEntry(domain);
+    }
+
+    /**
+     * Validate by Text in root
+     *
+     * @param domain, tenant domain
+     * @throws Exception, if validation failed.
+     * @return, successkey
+     */
+    public String validateByTextInRoot(String domain) throws Exception {
+        if (!Util.checkDomainAvailability(domain)) {
+            String msg = "Domain " + domain + " is already taken.";
+            log.info(msg);
+            return "unavailable";
+        }
+        return Util.validateByTextInRoot(domain);
+    }
+}
+
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/util/Util.java b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/util/Util.java
new file mode 100644
index 0000000..cb42b32
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/java/org/wso2/carbon/validate/domain/util/Util.java
@@ -0,0 +1,320 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.validate.domain.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.ResourceImpl;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.registry.core.utils.RegistryUtils;
+import org.wso2.carbon.registry.core.utils.UUIDGenerator;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.validate.domain.internal.ValidateDomainServiceComponent;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+/**
+ * Util methods for domain validationn
+ */
+public class Util {
+
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static RegistryService registryService;
+    private static RealmService realmService;
+
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    /**
+     * validate the content
+     *
+     * @param sourceURL - url of the source
+     * @param content   - String content
+     * @throws RegistryException, if validation failed.
+     * @return, true if validated.
+     */
+    public static boolean validateContent(String sourceURL, String content)
+            throws RegistryException {
+        URL url;
+        try {
+            if (sourceURL != null && sourceURL.toLowerCase().startsWith("file:")) {
+                String msg = "The source URL must not be file in the server's local file system";
+                throw new RegistryException(msg);
+            }
+            url = new URL(sourceURL);
+        } catch (MalformedURLException e) {
+            String msg = "Given source URL " + sourceURL + "is not valid.";
+            throw new RegistryException(msg, e);
+        }
+
+        try {
+            URLConnection uc = url.openConnection();
+            InputStream in = uc.getInputStream();
+            byte[] inByteArr = RegistryUtils.getByteArray(in);
+            String onlineContent = new String(inByteArr);
+            return onlineContent.startsWith(content);
+
+        } catch (IOException e) {
+
+            String msg = "Could not read from the given URL: " + sourceURL;
+            throw new RegistryException(msg, e);
+        }
+    }
+
+    /**
+     * Checks whether the domain is available to register.
+     *
+     * @param domainName domain name
+     * @throws RegistryException, if failed.
+     * @return, true if avaiable to register.
+     */
+    public static boolean checkDomainAvailability(String domainName) throws RegistryException {
+        TenantManager tenantManager = Util.getTenantManager();
+        int tenantId;
+       
+        try {
+            tenantId = tenantManager.getTenantId(domainName);
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Error in checking the domain availability.";
+            log.error(msg);
+            // we are instead send the tenant id.
+            tenantId = -1;
+        }
+        return tenantId < 0;
+    }
+
+    /**
+     * Check whether the domain name entered is valid
+     *
+     * @param domain tenant domain
+     * @return true, if valid.
+     */
+    public static boolean checkDomainValidity(String domain) {
+        // domains with '/' will be seen as possible characters, but they need to be avoided..
+        return !(domain.contains("/") || domain.contains("\\"));
+    }
+
+
+    /**
+     * Get Domain Validation Key without Login.
+     * If the user is generating the validation key without login, we will be serving them a
+     * different keys for each refreshes of the page.
+     *
+     * @param domain - tenant domain
+     * @return generated domain validation key.
+     * @throws RegistryException, if failed in generating the domain validation key.
+     */
+    public static String getDomainValidationKeyWithoutLogin(String domain)
+            throws RegistryException {
+        return generateDomainValidateKey(domain);
+    }
+
+    /**
+     * Get the domain validation key with login
+     * If the user is generating the validation key with login, we will be serving them the same key
+     *
+     * @param domain - tenant domain.
+     * @return generated domain validation key.
+     * @throws RegistryException, if failed in generating the domain validation key.
+     */
+    public static String getDomainValidationKeyWithLogin(String domain) throws RegistryException {
+        // get the super tenant system registry
+        UserRegistry governanceSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        String domainValidatorInfoPath = StratosConstants.DOMAIN_VALIDATOR_INFO_PATH +
+                                         RegistryConstants.PATH_SEPARATOR +
+                                         domain + RegistryConstants.PATH_SEPARATOR +
+                                         StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        if (governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+            Object contentObj = resource.getContent();
+            if (contentObj instanceof String) {
+                return (String) contentObj;
+            } else if (contentObj instanceof byte[]) {
+                return new String((byte[]) contentObj);
+            }
+        }
+
+        // otherwise we will generate the key
+        return generateDomainValidateKey(domain);
+    }
+
+    private static String generateDomainValidateKey(String domain) throws RegistryException {
+        // get the super tenant system registry
+        UserRegistry governanceSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        String domainValidatorInfoPath = StratosConstants.DOMAIN_VALIDATOR_INFO_PATH +
+                                         RegistryConstants.PATH_SEPARATOR + domain +
+                                         RegistryConstants.PATH_SEPARATOR +
+                                         StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+
+        // we have to reset the domain validation key everytime 
+        String domainValidationKey = UUIDGenerator.generateUUID();
+        Resource resource = governanceSystemRegistry.newResource();
+        resource.setContent(domainValidationKey);
+        ((ResourceImpl) resource).setVersionableChange(false);
+        governanceSystemRegistry.put(domainValidatorInfoPath, resource);
+        CommonUtil.setAnonAuthorization(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH +
+                                        domainValidatorInfoPath,
+                                        governanceSystemRegistry.getUserRealm());
+
+        return domainValidationKey;
+    }
+
+    /**
+     * validate by DNS Entry.
+     *
+     * @param domain - tenant domain
+     * @return successkey.
+     * @throws RegistryException, if validation failed.
+     */
+    public static String validateByDNSEntry(String domain) throws RegistryException {
+        if (!Util.checkDomainValidity(domain)) {
+            return "false";
+        }
+        // get the super tenant system registry
+        UserRegistry governanceSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        String domainValidatorInfoPath = StratosConstants.DOMAIN_VALIDATOR_INFO_PATH +
+                                         RegistryConstants.PATH_SEPARATOR +
+                                         domain + RegistryConstants.PATH_SEPARATOR +
+                                         StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        
+        String domainValidationKey = "";
+        if (!governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            return "false";
+        }
+        Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+        Object content = resource.getContent();
+        if (content instanceof String) {
+            domainValidationKey = (String) content;
+        } else if (content instanceof byte[]) {
+            domainValidationKey = new String((byte[]) content);
+        }
+        
+        int httpPort = CarbonUtils.getTransportPort(ValidateDomainServiceComponent.getConfigContextService(), "http");
+        int httpProxyPort =
+            CarbonUtils.getTransportProxyPort(ValidateDomainServiceComponent.getConfigContextService().getServerConfigContext(),
+                                              "http");
+
+
+        // check whether this is running on a different port
+        int portValue = httpProxyPort != -1 ? httpProxyPort : httpPort;
+
+        // we are forming the resource http url to access the domainValidationKey
+        String domainValidatorInfoAbsolutePath = RegistryUtils.getAbsolutePath(governanceSystemRegistry.getRegistryContext(),
+                                                                RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH +
+                                                                domainValidatorInfoPath);
+
+        String sourceUrl = "http://" + domainValidationKey + "." + domain + ":"+ portValue +
+                           RegistryConstants.PATH_SEPARATOR + "registry" +
+                           RegistryConstants.PATH_SEPARATOR + "resource" + domainValidatorInfoAbsolutePath;
+        if (Util.validateContent(sourceUrl, domainValidationKey)) {
+            // the validation success, so we will create the success key
+            // (this is a temporary key that we keep the session
+            String successKey = UUIDGenerator.generateUUID();
+            resource.setProperty("successKey", successKey);
+            ((ResourceImpl) resource).setVersionableChange(false);
+            governanceSystemRegistry.put(domainValidatorInfoPath, resource);
+            return successKey;
+        }
+        return "false";
+    }
+
+    /**
+     * Validate by text in root
+     *
+     * @param domain - tenant domain
+     * @return successkey
+     * @throws RegistryException, if validation failed.
+     */
+    public static String validateByTextInRoot(String domain) throws RegistryException {
+        if (!Util.checkDomainValidity(domain)) {
+            return "false";
+        }
+
+        UserRegistry governanceSystemRegistry =
+                Util.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
+        String domainValidatorInfoPath = StratosConstants.DOMAIN_VALIDATOR_INFO_PATH +
+                                         RegistryConstants.PATH_SEPARATOR +
+                                         domain + RegistryConstants.PATH_SEPARATOR +
+                                         StratosConstants.VALIDATION_KEY_RESOURCE_NAME;
+        String domainValidationKey = "";
+        if (!governanceSystemRegistry.resourceExists(domainValidatorInfoPath)) {
+            return "false";
+        }
+        Resource resource = governanceSystemRegistry.get(domainValidatorInfoPath);
+        Object content = resource.getContent();
+        if (content instanceof String) {
+            domainValidationKey = (String) content;
+        } else if (content instanceof byte[]) {
+            domainValidationKey = new String((byte[]) content);
+        }
+
+
+        // the filename is hard coded now, a change in this need to be reflected at
+        //  validate_domain.jsp
+        String sourceUrl = "http://" + domain + "/wso2multitenancy.txt";
+        if (Util.validateContent(sourceUrl, domainValidationKey)) {
+            // the validation success, so we will create the success key
+            // this is a temporary key that we keep the session
+            String successKey = UUIDGenerator.generateUUID();
+            resource.setProperty("successKey", successKey);
+            ((ResourceImpl) resource).setVersionableChange(false);
+            governanceSystemRegistry.put(domainValidatorInfoPath, resource);
+            return successKey;
+        }
+        return "false";
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..39fa82f
--- /dev/null
+++ b/components/stratos/domain-validator/org.wso2.carbon.validate.domain/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright 2006 The Apache Software Foundation.
+ !
+ ! Licensed under the Apache License, Version 2.0 (the "License");
+ ! you may not use this file except in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ !      http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing, software
+ ! distributed under the License is distributed on an "AS IS" BASIS,
+ ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ! See the License for the specific language governing permissions and
+ ! limitations under the License.
+ !-->
+<serviceGroup>
+
+    <service name="ValidateDomainService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.validate.domain.services.ValidateDomainService
+        </parameter>
+    </service>
+    <service name="ValidateDomainAdminService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.validate.domain.services.ValidateDomainAdminService
+        </parameter>
+        <parameter name="adminService" locked="true">true</parameter>
+        <parameter name="AuthorizationAction" locked="true">/permission/admin/configure/account</parameter>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/domain-validator/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/domain-validator/pom.xml b/components/stratos/domain-validator/pom.xml
new file mode 100644
index 0000000..aff23aa
--- /dev/null
+++ b/components/stratos/domain-validator/pom.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>domain-validator-parent</artifactId>
+    <packaging>pom</packaging>
+    <name>WSO2 Stratos - Domain Validator Parent Module</name>
+    <description>WSO2 Stratos Domain Validator Parent Module</description>
+    <url>http://wso2.org</url>
+
+    <modules>
+        <module>org.wso2.carbon.validate.domain/2.1.0</module>
+        <module>org.wso2.carbon.validate.domain.ui/2.1.0</module>
+    </modules>
+
+</project>
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/pom.xml b/components/stratos/org.wso2.carbon.activation/2.1.0/pom.xml
new file mode 100644
index 0000000..a024242
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/pom.xml
@@ -0,0 +1,94 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>stratos-components</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>org.wso2.carbon.activation</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Stratos - Activation</name>
+
+    <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>
+                        <Axis2Module>${project.artifactId}-${project.version}</Axis2Module>
+                        <Bundle-Name>${project.artifactId}</Bundle-Name>
+                        <Export-Package>
+                            org.wso2.carbon.activation.*,
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.stratos.common.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+	    <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.stratos.common</artifactId>
+        </dependency>
+    </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
new file mode 100644
index 0000000..e3fb386
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/internal/ActivationServiceComponent.java
@@ -0,0 +1,152 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.internal;
+
+import org.apache.axis2.AxisFault;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.activation.service.ActivationService;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+
+/**
+ * The Declarative Service Component for the Service Activation Module for Tenants.
+ *
+ * @scr.component name="org.wso2.carbon.metering" immediate="true"
+ * @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="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="config.context.service"
+ * interface="org.wso2.carbon.utils.ConfigurationContextService"
+ * cardinality="0..1" policy="dynamic"  bind="setConfigurationContextService"
+ * unbind="unsetConfigurationContextService"
+ */
+@SuppressWarnings({"JavaDoc", "unused"})
+public class ActivationServiceComponent {
+
+    private static final Log log = LogFactory.getLog(ActivationServiceComponent.class);
+
+    private static ServiceRegistration registration = null;
+
+    /**
+     * Activates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void activate(ComponentContext context) {
+        try {
+            ActivationManager.startCacheCleaner();
+            if (registration == null) {
+                registration = context.getBundleContext().registerService(
+                        ActivationService.class.getName(), new ActivationService(), null);
+            }
+            log.debug("******* Stratos Activation bundle is activated ******* ");
+        } catch (Exception e) {
+            log.error("******* Stratos Activation bundle failed activating ****", e);
+        }
+    }
+
+    /**
+     * Deactivates the Registry Kernel bundle.
+     *
+     * @param context the OSGi component context.
+     */
+    protected void deactivate(ComponentContext context) {
+        registration.unregister();
+        registration = null;
+        ActivationManager.stopCacheCleaner();
+        log.debug("******* Stratos Activation bundle is deactivated ******* ");
+    }
+
+    /**
+     * Method to set the registry service used. This will be used when accessing the registry. This
+     * method is called when the OSGi Registry Service is available.
+     *
+     * @param registryService the registry service.
+     */
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    /**
+     * This method is called when the current registry service becomes un-available.
+     *
+     * @param registryService the current registry service instance, to be used for any
+     *                        cleaning-up.
+     */
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    /**
+     * Method to set the realm service used. This will be used when accessing the user realm. This
+     * method is called when the OSGi Realm Service is available.
+     *
+     * @param realmService the realm service.
+     */
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    /**
+     * This method is called when the current realm service becomes un-available.
+     *
+     * @param realmService the current realm service instance, to be used for any cleaning-up.
+     */
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    /**
+     * Method to set the configuration context service used. This method is called when the OSGi
+     * ConfigurationContext Service is available.
+     *
+     * @param contextService the configuration context service.
+     */
+    protected void setConfigurationContextService(ConfigurationContextService contextService) {
+        try {
+            if (contextService.getServerConfigContext() != null &&
+                    contextService.getServerConfigContext().getAxisConfiguration() != null) {
+                contextService.getServerConfigContext().getAxisConfiguration().engageModule(
+                        "activation");
+            } else {
+                log.error("Failed to engage Activation Module.");
+            }
+        } catch (AxisFault e) {
+            log.error("Failed to engage Activation Module", e);
+        }
+    }
+
+    /**
+     * This method is called when the current configuration context service becomes un-available.
+     *
+     * @param contextService the current configuration context service instance, to be used for any
+     *                       cleaning-up.
+     */
+    protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
new file mode 100644
index 0000000..4f1a1ca
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationHandler.java
@@ -0,0 +1,154 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.module;
+
+import javax.xml.namespace.QName;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.soap.SOAPBody;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.Handler;
+import org.apache.axis2.handlers.AbstractHandler;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
+import org.wso2.carbon.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.ServerConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+public class ActivationHandler extends AbstractHandler implements Handler {
+
+    private static final Log log = LogFactory.getLog(ActivationHandler.class);
+
+    private String name = "ActivationHandler";
+
+    /**
+     * {@inheritDoc}
+     */
+    public InvocationResponse invoke(MessageContext messageContext) throws AxisFault {
+        if(log.isDebugEnabled()){
+            log.debug("Starting Activation Handler invocation. Incoming Message: " +
+                    messageContext.getEnvelope().toString());
+        }
+
+        AxisService service = messageContext.getAxisService();
+        int tenantId = getTenantId(messageContext);
+        if (service != null && "ActivationService".equals(service.getName())) {
+            log.debug("Granted access to the Activation Service");
+            if (tenantId > 0) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+            }
+            return InvocationResponse.CONTINUE;
+        }
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            log.debug("Granted access for super tenant");
+            return InvocationResponse.CONTINUE;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            if (ActivationManager.getActivation(tenantId)) {
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            } else {
+                if (log.isWarnEnabled()) {
+                    String serviceName = Util.getServiceName();
+                    log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+                }
+                return InvocationResponse.ABORT;
+            }
+        }
+        String serviceName = Util.getServiceName();
+        try {
+            if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+                log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+                ActivationManager.setActivation(tenantId, true);
+                TenantAxisUtils.getTenantAxisConfiguration(getTenantDomain(messageContext),
+                        messageContext.getConfigurationContext());
+                log.debug("Loaded Tenant Configuration");
+                return InvocationResponse.CONTINUE;
+            }
+        } catch (Exception e) {
+            throw new AxisFault("Failed to determine Activation status.", e);
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return InvocationResponse.ABORT;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Method to set the name of the activation handler.
+     *
+     * @param name the name.
+     */
+    @SuppressWarnings("unused")
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    private String getTenantDomain(MessageContext messageContext) {
+        return PrivilegedCarbonContext.getCurrentContext(messageContext).getTenantDomain(true);
+    }
+
+    private int getTenantId(MessageContext messageContext) {
+        PrivilegedCarbonContext carbonContext =
+                PrivilegedCarbonContext.getCurrentContext(messageContext);
+        int tenantId = carbonContext.getTenantId();
+        if (tenantId > -1 || tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return tenantId;
+        }
+        String domain = carbonContext.getTenantDomain();
+        if (domain == null) {
+            SOAPBody soapBody = messageContext.getEnvelope().getBody();
+            if (soapBody != null && soapBody.getFirstElement() != null) {
+                OMElement usernameElem = soapBody.getFirstElement().getFirstChildWithName(
+                        new QName(ServerConstants.AUTHENTICATION_SERVICE_NS,
+                                ServerConstants.AUTHENTICATION_SERVICE_USERNAME));
+                if (usernameElem != null) {
+                    String userName = usernameElem.getText();
+                    domain = MultitenantUtils.getTenantDomain(userName);
+                }
+            }
+        }
+        if (domain != null) {
+            try {
+                tenantId = Util.getRealmService().getTenantManager().getTenantId(domain);
+            } catch (org.wso2.carbon.user.api.UserStoreException e) {
+                log.error("An error occurred while obtaining the tenant id.", e);
+            }
+        }
+        return tenantId;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
new file mode 100644
index 0000000..9cfbee5
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/module/ActivationModule.java
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.module;
+
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.description.AxisDescription;
+import org.apache.axis2.description.AxisModule;
+import org.apache.axis2.modules.Module;
+import org.apache.neethi.Assertion;
+import org.apache.neethi.Policy;
+
+/**
+ * Module used to engage the activation handler.
+ */
+public class ActivationModule implements Module {
+
+    /**
+     * {@inheritDoc}
+     */
+    public void init(ConfigurationContext configurationContext, AxisModule axisModule)
+            throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void engageNotify(AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public boolean canSupportAssertion(Assertion assertion) {
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public void shutdown(ConfigurationContext configurationContext) throws AxisFault {
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/service/ActivationService.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
new file mode 100644
index 0000000..e16f2fb
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/service/ActivationService.java
@@ -0,0 +1,85 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.service;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.activation.utils.ActivationManager;
+import org.wso2.carbon.activation.utils.Util;
+import org.wso2.carbon.stratos.common.config.CloudServiceConfigParser;
+import org.wso2.carbon.stratos.common.config.CloudServicesDescConfig;
+import org.wso2.carbon.stratos.common.util.CloudServicesUtil;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Admin Service to handle activation of cloud services used by tenants.
+ */
+public class ActivationService {
+
+    private static final Log log = LogFactory.getLog(ActivationService.class);
+
+    /**
+     * Method to update an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @throws Exception if the operation failed.
+     */
+    public static void updateActivation(int tenantId) throws Exception {
+        if (tenantId != 0) {
+            String serviceName = Util.getServiceName();
+            boolean isActive = CloudServicesUtil.isCloudServiceActive(serviceName, tenantId);
+            CloudServicesDescConfig cloudServicesDesc =
+                                                        CloudServiceConfigParser.loadCloudServicesConfiguration();
+            CloudServicesUtil.setCloudServiceActive(!isActive,
+                                                    serviceName,
+                                                    tenantId,
+                                                    cloudServicesDesc.getCloudServiceConfigs()
+                                                                     .get(serviceName));
+            ActivationManager.setActivation(tenantId, !isActive);
+        }
+    }
+
+    /**
+     * Method to determine whether a service is active for the given tenant.
+     *
+     * @param tenantId tenantId the tenant identifier.
+     *
+     * @return whether the service is active.
+     * @throws Exception if the operation failed.
+     */
+    public boolean isActive(int tenantId) throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return true;
+        }
+        if (ActivationManager.activationRecorded(tenantId)) {
+            return ActivationManager.getActivation(tenantId);
+        }
+        String serviceName = Util.getServiceName();
+        if (CloudServicesUtil.isCloudServiceActive(serviceName, tenantId)) {
+            log.debug("Successful attempt to access " + serviceName + " by tenant " + tenantId);
+            ActivationManager.setActivation(tenantId, true);
+            return true;
+        }
+        log.warn("Failed attempt to access " + serviceName + " by tenant " + tenantId);
+        ActivationManager.setActivation(tenantId, false);
+        return false;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
new file mode 100644
index 0000000..41153a8
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/ActivationManager.java
@@ -0,0 +1,96 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.utils;
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Manages Activations of Services for Tenants.
+ */
+public class ActivationManager {
+
+    private static final ConcurrentHashMap<Integer, Boolean> activations =
+            new ConcurrentHashMap<Integer, Boolean>();
+    private static Timer timer = null;
+
+    /**
+     * Starts cleaning up cached activation records at periodic intervals.
+     */
+    public static void startCacheCleaner() {
+        TimerTask faultyServiceRectifier = new CacheCleaner();
+        timer = new Timer();
+        // Retry in 1 minute
+        long retryIn = 1000 * 60;
+        timer.schedule(faultyServiceRectifier, 0, retryIn);
+    }
+
+    /**
+     * Stops cleaning up cached activation records.
+     */
+    public static void stopCacheCleaner() {
+        timer.cancel();
+        timer = null;
+    }
+
+    /**
+     * Method to set an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     * @param status   true if the service is active or false if not.
+     */
+    public static void setActivation(int tenantId, boolean status) {
+        ActivationManager.activations.put(tenantId, status);
+    }
+
+    /**
+     * Method to check whether an activation record exists for the given tenant.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if a record exists.
+     */
+    public static boolean activationRecorded(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null;
+    }
+
+    /**
+     * Method to retrieve an activation record.
+     *
+     * @param tenantId the tenant identifier.
+     *
+     * @return true if the service is active or false if not.
+     */
+    public static boolean getActivation(int tenantId) {
+        return ActivationManager.activations.get(tenantId) != null &&
+                ActivationManager.activations.get(tenantId);
+    }
+
+    private static class CacheCleaner extends TimerTask {
+
+        /**
+         * {@inheritDoc}
+         */
+        public void run() {
+            ActivationManager.activations.clear();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/Util.java b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/Util.java
new file mode 100644
index 0000000..9f01045
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/java/org/wso2/carbon/activation/utils/Util.java
@@ -0,0 +1,138 @@
+/*
+ *  Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.activation.utils;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.base.ServerConfiguration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+
+/**
+ * Utilities for the Service Activation Module for Tenants.
+ */
+public class Util {
+
+    private static RegistryService registryService = null;
+    private static RealmService realmService = null;
+    private static String serviceName = null;
+    private static final Log log = LogFactory.getLog(Util.class);
+
+    private static boolean cloudServiceInfoPathSanityChecked = false;
+
+    /**
+     * Stores an instance of the Registry Service that can be used to access the registry.
+     *
+     * @param service the Registry Service instance.
+     */
+    public static synchronized void setRegistryService(RegistryService service) {
+        if (registryService == null) {
+            registryService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Registry Service instance.
+     *
+     * @return the Registry Service instance if it has been stored or null if not.
+     */
+    @SuppressWarnings("unused")
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+    /**
+     * Stores an instance of the Realm Service that can be used to access the user realm.
+     *
+     * @param service the Realm Service instance.
+     */
+    public static synchronized void setRealmService(RealmService service) {
+        if (realmService == null) {
+            realmService = service;
+        }
+    }
+
+    /**
+     * Method to retrieve the Realm Service instance.
+     *
+     * @return the Realm Service instance if it has been stored or null if not.
+     */
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    private static UserRegistry getSuperTenantGovernanceSystemRegistry() throws RegistryException {
+        return registryService.getGovernanceSystemRegistry();
+    }
+
+//    /**
+//     * Method to determine whether the given cloud service is active.
+//     *
+//     * @param cloudServiceName the name of the cloud service.
+//     * @param tenantId         the tenant identifier.
+//     * @param systemRegistry   the super tenant's governance system registry
+//     *
+//     * @return true if the service is active or false if not.
+//     * @throws Exception if the operation failed.
+//     */
+//    public static boolean isCloudServiceActive(String cloudServiceName,
+//                                               int tenantId, UserRegistry systemRegistry)
+//            throws Exception {
+//        // The cloud manager is always active
+//        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+//            return true;
+//        }
+//
+//        if(!cloudServiceInfoPathSanityChecked) {
+//            if(!systemRegistry.resourceExists(StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH)) {
+//                throw new RuntimeException("Cloud services list resource " +
+//                                           StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH + " does not exist");
+//            }
+//            cloudServiceInfoPathSanityChecked = true;
+//        }
+//
+//        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+//                RegistryConstants.PATH_SEPARATOR + tenantId +
+//                RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+//        Resource cloudServiceInfoResource;
+//        if (systemRegistry.resourceExists(cloudServiceInfoPath)) {
+//            cloudServiceInfoResource = systemRegistry.get(cloudServiceInfoPath);
+//            String isActiveStr =
+//                cloudServiceInfoResource.getProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+//            return Boolean.toString(true).equals(isActiveStr);
+//        }
+//        return false;
+//    }
+//
+
+    /**
+     * Method to obtain the name of the cloud service in which this module is running.
+     *
+     * @return the name of the service as defined in the server configuration.
+     */
+    public static String getServiceName() {
+        if (serviceName == null) {
+            serviceName = ServerConfiguration.getInstance().getFirstProperty("Name");
+        }
+        return serviceName;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/module.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/module.xml b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/module.xml
new file mode 100644
index 0000000..b92b725
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/module.xml
@@ -0,0 +1,33 @@
+<!--
+ ~ Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ WSO2 Inc. licenses this file to you under the Apache License,
+ ~ Version 2.0 (the "License"); you may not use this file except
+ ~ in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~    http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied.  See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+<module name="activation" class="org.wso2.carbon.activation.module.ActivationModule">
+   <InFlow>
+        <handler name="InFlowActivationHandler"
+                 class="org.wso2.carbon.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFlow>
+
+   <InFaultFlow>
+        <handler name="FaultInFlowActivationHandler"
+                 class="org.wso2.carbon.activation.module.ActivationHandler">
+        <order phase="Validation" phaseFirst="true"/>
+        </handler>
+   </InFaultFlow>
+  <parameter name="adminModule" locked="true">true</parameter>
+</module>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/services.xml b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..dde74d7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.activation/2.1.0/src/main/resources/META-INF/services.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ !
+ ! Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ !
+ ! WSO2 Inc. licenses this file to you under the Apache License,
+ ! Version 2.0 (the "License"); you may not use this file except
+ ! in compliance with the License.
+ ! You may obtain a copy of the License at
+ !
+ ! http://www.apache.org/licenses/LICENSE-2.0
+ !
+ ! Unless required by applicable law or agreed to in writing,
+ ! software distributed under the License is distributed on an
+ ! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ! KIND, either express or implied.  See the License for the
+ ! specific language governing permissions and limitations
+ ! under the License.
+ !-->
+<serviceGroup>
+    <service name="ActivationService" scope="transportsession">
+        <transports>
+            <transport>https</transport>
+        </transports>
+        <parameter name="ServiceClass" locked="false">
+            org.wso2.carbon.activation.service.ActivationService
+        </parameter>
+    </service>
+    <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>
\ No newline at end of file


[34/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
new file mode 100644
index 0000000..4ab16ff
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
@@ -0,0 +1,462 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.scheduler.BillingScheduler;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.email.sender.api.EmailSender;
+import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Billing engine work on billing per a seller
+ */
+public class BillingEngine {
+
+    private static Log log = LogFactory.getLog(BillingEngine.class);
+    private BillingTaskConfiguration billingTaskConfig;
+    BillingScheduler billingScheduler;
+    DataAccessObject dataAccessObject;
+
+    public BillingEngine(BillingTaskConfiguration billingTaskConfig,
+                         DataAccessObject dataAccessObject) {
+        this.billingTaskConfig = billingTaskConfig;
+        billingScheduler = new BillingScheduler(this, billingTaskConfig);
+        this.dataAccessObject = dataAccessObject;
+    }
+
+    public void scheduleBilling() throws BillingException {
+        // the logic to schedule the billing
+        SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
+        billingScheduler.scheduleNextCycle(schedulerContext);
+    }
+
+    public void generateBill() throws BillingException {
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        generateBill(billingEngineContext);
+    }
+
+    public void generateBill(SchedulerContext schedulerContext) throws BillingException {
+        BillingEngineContext billingEngineContext = new BillingEngineContext();
+        billingEngineContext.setSchedulerContext(schedulerContext);
+        generateBill(billingEngineContext);
+    }
+
+    public void generateBill(BillingEngineContext billingEngineContext) throws BillingException {
+
+        try {
+            beginTransaction();
+            if (billingEngineContext.getSchedulerContext() == null) {
+                SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
+                billingEngineContext.setSchedulerContext(schedulerContext);
+            }
+
+            billingEngineContext.setTaskConfiguration(billingTaskConfig);
+
+            // now iterator through all the handlers
+            List<BillingHandler> handlers = billingTaskConfig.getBillingHandlers();
+            for (BillingHandler handler : handlers) {
+                handler.execute(billingEngineContext);
+            }
+            //commit transaction
+            commitTransaction();
+        }catch (Exception e){
+            String msg = "Error occurred while generating the bill:" + e.getMessage();
+            log.error(msg);
+            //rollback transaction
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        
+    }
+
+    public void beginTransaction() throws BillingException {
+        dataAccessObject.beginTransaction();
+    }
+
+    public void commitTransaction() throws BillingException {
+        dataAccessObject.commitTransaction();
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        dataAccessObject.rollbackTransaction();
+    }
+
+    public List<Item> getItemsWithName(String itemName) throws BillingException {
+        List<Item> items;
+        try {
+            beginTransaction();
+            items = dataAccessObject.getItemsWithName(itemName);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item with name: " + itemName +
+                        " " + e.getMessage();
+            log.error(msg);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return items;
+    }
+
+    public int addItem(Item item) throws BillingException {
+        int itemId = 0;
+        try {
+            beginTransaction();
+            itemId = dataAccessObject.addItem(item);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding item: " + item.getName() +
+                            " " + e.getMessage();
+            log.error(msg);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return itemId;
+    }
+
+    public Item getItem(int itemId) throws BillingException {
+        Item item;
+        try {
+            beginTransaction();
+            item = dataAccessObject.getItem(itemId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item with id: " + itemId +
+                            " " + e.getMessage();
+            log.error(msg);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return item;
+    }
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try{
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if(tenant!=null){
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        }catch(Exception e){
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public int addSubscription(Subscription subscription) throws BillingException {
+        int subscriptionId = 0;
+        try {
+            beginTransaction();
+            subscriptionId =
+                    dataAccessObject.addSubscription(subscription,
+                            subscription.getSubscriptionPlan());
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding subscription: " + subscription.getSubscriptionPlan()+
+                            " for the customer " + subscription.getCustomer().getName() + " " + e.getMessage() ;
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptionId;
+    }
+
+    public int addPayment(Payment payment) throws BillingException {
+        int paymentId = 0;
+        try {
+            beginTransaction();
+            paymentId = dataAccessObject.addPayment(payment);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding payment record (transaction id): " + payment.getDescription() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return paymentId;
+    }
+
+    public int addRegistrationPayment(Payment payment, String usagePlan) throws BillingException {
+        int paymentId = 0;
+        try {
+            beginTransaction();
+            paymentId = dataAccessObject.addRegistrationPayment(payment, usagePlan);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding registration payment record (transaction id): " + payment.getDescription() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return paymentId;
+    }
+
+    public Invoice getLastInvoice(Customer customer) throws BillingException {
+        Invoice invoice = null;
+        try {
+            beginTransaction();
+            invoice = dataAccessObject.getLastInvoice(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting last invoice for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoice;
+    }
+
+    public List<Invoice> getAllInvoices(Customer customer) throws BillingException {
+        List<Invoice> invoices = null;
+        try {
+            beginTransaction();
+            invoices = dataAccessObject.getAllInvoices(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting all invoices for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoices;
+    }
+
+    public List<Subscription> getActiveSubscriptions(Customer customer) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions =
+                    dataAccessObject.getFilteredActiveSubscriptionsForCustomer(
+                            null, customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscriptions for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    public Subscription getActiveSubscriptionOfCustomer(int customerId) throws BillingException {
+        Subscription subscription;
+        try {
+            beginTransaction();
+            subscription =
+                    dataAccessObject.getActiveSubscriptionOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscription for customer: " + customerId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public List<Invoice> getInvoices(Customer customer) throws BillingException {
+        List<Invoice> invoices;
+        try {
+            beginTransaction();
+            invoices = dataAccessObject.getInvoices(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoices for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoices;
+    }
+
+    public Invoice getInvoice(int invoiceId) throws BillingException {
+        Invoice invoice = null;
+        try {
+            beginTransaction();
+            invoice = dataAccessObject.getInvoice(invoiceId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoice with id: " + invoiceId +
+                            " " + e.getMessage();                
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return invoice;
+    }
+
+    public List<Item> getBilledItems(Subscription subscription) throws BillingException {
+        List<Item> billedItems;
+        try {
+            beginTransaction();
+            billedItems = dataAccessObject.getBilledItems(subscription);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting billed items for subscription: " + subscription.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return billedItems;
+    }
+
+    public List<Subscription> getInvoiceSubscriptions(int invoiceId) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions = dataAccessObject.getInvoiceSubscriptions(invoiceId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting invoice subscriptions for invoice id: " + invoiceId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+
+    public Payment getLastPayment(Customer customer) throws BillingException {
+        Payment payment;
+        try {
+            beginTransaction();
+            payment = dataAccessObject.getLastPayment(customer);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting the last payment for customer: " + customer.getId() +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return payment;
+    }
+
+    public List<Customer> getAllCustomers() throws BillingException {
+        return CustomerUtils.getAllCustomers();
+    }
+
+    public List<OutstandingBalanceInfoBean> getAllOutstandingBalanceInfoBeans(String tenantDomain)
+            throws BillingException {
+        if(tenantDomain==null || "".equals(tenantDomain)){
+            return getAllOutstandingBalances(null);
+        }else{
+            List<Customer> customers = getCustomersWithName(tenantDomain);
+            if(customers!=null && customers.size()>0){
+                return getAllOutstandingBalances(customers.get(0));
+            }else{
+                return new ArrayList<OutstandingBalanceInfoBean>();
+            }
+        }
+    }
+
+    public List<OutstandingBalanceInfoBean> getAllOutstandingBalances(Customer preferredCustomer) throws BillingException{
+        List<Customer> customers;// = getAllCustomers();
+        List<OutstandingBalanceInfoBean> outstandingBalances = new ArrayList<OutstandingBalanceInfoBean>();
+        if(preferredCustomer!=null){
+            customers = new ArrayList<Customer>();
+            customers.add(preferredCustomer);
+        }else{
+            customers = getAllCustomers();
+        }
+        for(Customer customer : customers){
+            OutstandingBalanceInfoBean balanceBean = new OutstandingBalanceInfoBean();
+            balanceBean.setCustomerName(customer.getName());
+            Invoice invoice = getLastInvoice(customer);
+            if(invoice!=null){
+                balanceBean.setCarriedForward(invoice.getCarriedForward().toString());
+                balanceBean.setLastInvoiceDate(invoice.getDate());
+            }
+            //setting the active usage plan
+            Subscription subscription = getActiveSubscriptionOfCustomer(customer.getId());
+            if(subscription!=null){
+                balanceBean.setSubscription(subscription.getSubscriptionPlan());
+            }else{
+                balanceBean.setSubscription("Not Available");
+            }
+
+            Payment payment = getLastPayment(customer);
+            if(payment!=null){
+                balanceBean.setLastPaidAmount(payment.getAmount().toString());
+                balanceBean.setLastPaymentDate(payment.getDate());
+            }
+            outstandingBalances.add(balanceBean);
+        }
+        return outstandingBalances;
+    }
+
+    public void sendPaymentReceivedEmail(String toAddress, String emailFile,
+                                         Map<String,String> mailParameters) throws Exception {
+        String emailTemplateFile = CarbonUtils.getCarbonConfigDirPath()+ File.separator
+                                   + StratosConstants.EMAIL_CONFIG + File.separator + emailFile;
+        EmailSenderConfiguration senderConfiguration =
+                EmailSenderConfiguration.loadEmailSenderConfiguration(emailTemplateFile);
+        EmailSender sender = new EmailSender(senderConfiguration);
+        sender.sendEmail(toAddress, mailParameters);
+    }
+    
+    public boolean addDiscount(Discount discount) throws Exception {
+        boolean added = false;
+        try {
+            beginTransaction();
+            added = dataAccessObject.addDiscount(discount);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding the discount for tenant: " + discount.getTenantId()+
+                    ". " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+
+        return added;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
new file mode 100644
index 0000000..8d97dc1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
+
+import java.util.List;
+
+public class BillingEngineContext {
+    List<Subscription> subscriptions;
+    SchedulerContext schedulerContext;
+    Customer customer;
+    BillingTaskConfiguration taskConfiguration;
+
+    public List<Subscription> getSubscriptions() {
+        return subscriptions;
+    }
+
+    public void setSubscriptions(List<Subscription> subscriptions) {
+        this.subscriptions = subscriptions;
+    }
+
+    public SchedulerContext getSchedulerContext() {
+        return schedulerContext;
+    }
+
+    public void setSchedulerContext(SchedulerContext schedulerContext) {
+        this.schedulerContext = schedulerContext;
+    }
+
+    public Customer getCustomer() {
+        return customer;
+    }
+
+    public void setCustomer(Customer customer) {
+        this.customer = customer;
+    }
+
+    public BillingTaskConfiguration getTaskConfiguration() {
+        return taskConfiguration;
+    }
+
+    public void setTaskConfiguration(BillingTaskConfiguration taskConfiguration) {
+        this.taskConfiguration = taskConfiguration;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
new file mode 100644
index 0000000..2aae5a4
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+@SuppressWarnings("serial")
+public class BillingException extends Exception {
+    public BillingException(String msg, Exception e) {
+        super(msg, e);
+    }
+
+    public BillingException(String msg) {
+        super(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
new file mode 100644
index 0000000..2e7e0fc
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import java.util.Map;
+
+public interface BillingHandler {
+    public void init(Map<String, String> handlerConfig) throws BillingException;
+
+    /**
+     * Performs the tasks needed to generate bill, sending bills, etc. 
+     *
+     * @param handlerContext
+     * @throws BillingException
+     */
+    public void execute(BillingEngineContext handlerContext) throws BillingException;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
new file mode 100644
index 0000000..a523b60
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.conf.BillingConfiguration;
+import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A class to handle multiple billing engines
+ */
+public class BillingManager {
+    private static final Log log = LogFactory.getLog(BillingManager.class);
+    private static BillingManager billingManager;
+    private BillingConfiguration billingConfiguration;
+    private DataAccessObject dataAccessObject;
+    private Map<String, BillingEngine> billingEngines = new HashMap<String, BillingEngine>();
+
+    public static BillingManager getInstance() throws BillingException {
+        if (billingManager == null) {
+            String msg = "Billing Manager is not initialized.";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        return billingManager;
+    }
+
+    public static void destroyInstance() {
+        billingManager = null;
+    }
+
+    public BillingManager(BillingConfiguration billingConfiguration) throws BillingException {
+        if (billingManager != null) {
+            String msg = "Billing Manager should not be initialized twice";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        this.billingConfiguration = billingConfiguration;
+        this.dataAccessObject = new DataAccessObject(billingConfiguration.getDataSource());
+        //Create billing engine corresponds to given billingTaskConfigurations
+        Map<String, BillingTaskConfiguration> billingTaskConfigs =
+                billingConfiguration.getBillingTaskConfigs();
+        for (Map.Entry<String, BillingTaskConfiguration> entry : billingTaskConfigs.entrySet()) {
+            String billingTaskName = entry.getKey();
+            BillingTaskConfiguration billingTaskConfiguration = entry.getValue();
+            BillingEngine billingEngine =
+                    new BillingEngine(billingTaskConfiguration, dataAccessObject);
+            billingEngines.put(billingTaskName, billingEngine);
+        }
+        billingManager = this;
+    }
+
+    public BillingConfiguration getBillingConfiguration() {
+        return billingConfiguration;
+    }
+
+    public DataAccessObject getDataAccessObject() {
+        return dataAccessObject;
+    }
+
+    public BillingEngine getBillingEngine(String billingTaskName) {
+        return billingEngines.get(billingTaskName);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
new file mode 100644
index 0000000..403938f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
@@ -0,0 +1,203 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.stratos.common.listeners.TenantMgtListener;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+
+public class BillingTenantMgtListenerImpl implements TenantMgtListener{
+
+    private static Log log = LogFactory.getLog(BillingTenantMgtListenerImpl.class);
+    /**
+     * Adds the subscription entry when the tenant is created
+     * @param tenantInfo Tenant information
+     * @throws StratosException if adding subscription failed
+     */
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException {
+        Customer customer = new Customer();
+        customer.setName(tenantInfo.getTenantDomain());
+        customer.setEmail(tenantInfo.getEmail());
+        customer.setStartedDate(new Date(tenantInfo.getCreatedDate().getTimeInMillis()));
+        customer.setFullName(tenantInfo.getFirstname() + " " + tenantInfo.getLastname());
+
+        customer.setId(tenantInfo.getTenantId());
+        Subscription subscription = new Subscription();
+        subscription.setCustomer(customer);
+        subscription.setActive(false);
+        subscription.setActiveSince(Calendar.getInstance().getTime());
+        subscription.setItem(new Item());
+        subscription.setSubscriptionPlan(tenantInfo.getUsagePlan());
+        try {
+            Util.getDataAccessManager().addSubscription(subscription);
+        } catch (Exception e) {
+            String msg = "Could not add new subscription for tenant: " +tenantInfo.getTenantDomain();
+            log.error( msg + e.getMessage(), e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException {
+        try {
+            if (tenantInfo.getUsagePlan() == null) {
+                return;
+            }
+            Subscription currentSubscription = Util.getDataAccessManager().
+                    getActiveSubscriptionOfCustomer(tenantInfo.getTenantId());
+            if (currentSubscription != null && currentSubscription.getSubscriptionPlan() != null) {
+                if (!currentSubscription.getSubscriptionPlan().equals(tenantInfo.getUsagePlan())) {
+                    boolean updated = Util.getDataAccessManager().
+                            changeSubscription(tenantInfo.getTenantId(), tenantInfo.getUsagePlan());
+                    if (updated) {
+                        log.info("Usage plan was changed successfully from " + currentSubscription.getSubscriptionPlan() +
+                                " to " + tenantInfo.getUsagePlan());
+                    }
+                }
+            }else{
+                //tenant does not have an active subscription. First we have to check whether the tenant
+                //is active. If he is active only we will add a new usage plan. Otherwise it is useless
+                //to add a usage plan to an inactive tenant
+                TenantManager tenantManager = CloudCommonServiceComponent.getTenantManager();
+                Tenant tenant = tenantManager.getTenant(tenantInfo.getTenantId());
+                if(tenant.isActive()){
+                    //we add a new subscription
+                    Subscription subscription = new Subscription();
+                    subscription.setActive(true);
+                    subscription.setSubscriptionPlan(tenantInfo.getUsagePlan());
+                    subscription.setActiveSince(null);
+                    subscription.setActiveUntil(null);
+                    Customer customer = new Customer();
+                    customer.setName(tenantInfo.getTenantDomain());
+                    customer.setId(tenantInfo.getTenantId());
+                    subscription.setCustomer(customer);
+
+                    int subsId = Util.getDataAccessManager().addSubscription(subscription);
+                    if(subsId>0){
+                        log.info("Added a new " + subscription.getSubscriptionPlan() + " usage plan for the tenant " +
+                                tenantInfo.getTenantDomain());
+                    }
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while changing the subscription plan for tenant: " + tenantInfo.getTenantDomain();
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantRename(int tenantId, String oldDomainName, String newDomainName) throws StratosException {
+        //Nothing to be done
+    }
+
+    public void onTenantInitialActivation(int tenantId) throws StratosException {
+        onTenantActivation(tenantId);
+    }
+
+    public void onTenantActivation(int tenantId) throws StratosException {
+        //On tenant activation we need to activate the subscription
+
+        try {
+
+            Subscription subscription = Util.getDataAccessManager().getActiveSubscriptionOfCustomer(tenantId);
+
+            if (subscription != null) {
+                String msg = "Unable to activate the subscription for tenant: " + tenantId +
+                        ". An active subscription already exists";
+                log.info(msg);
+            } else {
+                List<Subscription> inactiveSubscriptions = Util.getDataAccessManager().getInactiveSubscriptionsOfCustomer(tenantId);
+                if (inactiveSubscriptions.size() == 1) {
+                    //This is the scenario where the tenant has registered, but not activated yet
+                    subscription = inactiveSubscriptions.get(0);
+                    boolean activated = Util.getDataAccessManager().activateSubscription(subscription.getId());
+                    if (activated) {
+                        log.info("Subscription was activated for tenant: " + tenantId);
+                    }
+                }else if(inactiveSubscriptions.size() > 1){
+                    //this is the scenario where the tenant has been deactivated by admin and
+                    //again activated. Here, I am adding a new active subscription which is similar to the
+                    //last existed one
+                    //inactiveSubscriptions.get(0) gives the latest inactive subscription
+                    Subscription subscriptionToAdd = inactiveSubscriptions.get(0);
+                    subscriptionToAdd.setActive(true);
+                    subscriptionToAdd.setActiveSince(null);
+                    subscriptionToAdd.setActiveUntil(null);
+
+                    int subsId = Util.getDataAccessManager().addSubscription(subscriptionToAdd);
+                    if(subsId>0){
+                        log.info("New subscription: " + subscriptionToAdd.getSubscriptionPlan() +
+                                " added and it was activated for tenant: " + tenantId);
+                    }
+                }else{
+                    //this means there are no subscriptions. Lets handle this later
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while activating the subscription for tenant: " +
+                    tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onTenantDeactivation(int tenantId) throws StratosException {
+        try{
+            Subscription currentActiveSubscription = Util.getDataAccessManager().getActiveSubscriptionOfCustomer(tenantId);
+            if(currentActiveSubscription==null){
+                String msg = "There is no active subscription to deactivate for tenant: " +
+                        tenantId + " on tenant deactivation";
+                log.info(msg);
+            }else {
+                boolean deactivated = Util.getDataAccessManager().deactivateActiveSubscription(tenantId);
+                if(deactivated){
+                    log.info("Subscription deactivated on tenant deactivation");
+                }else{
+                    log.info("Subscription was not deactivated on tenant deactivation");
+                }
+            }
+        } catch (Exception e){
+            String msg = "Error occurred while deactivating the active subscription for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, String newPlan) throws StratosException {
+        //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    public int getListenerOrder() {
+        return 0;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
new file mode 100644
index 0000000..89cce4c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import javax.sql.DataSource;
+import java.util.ArrayList;
+import java.util.List;
+
+
+public class DataAccessManager {
+
+    private static Log log = LogFactory.getLog(DataAccessManager.class);
+    private DataAccessObject dataAccessObject = null;
+
+    public DataAccessManager(DataSource dataSource) {
+        this.dataAccessObject = new DataAccessObject(dataSource);
+    }
+    
+    public DataAccessManager(DataAccessObject dao){
+        this.dataAccessObject = dao;
+    }
+
+    public void beginTransaction() throws BillingException {
+        dataAccessObject.beginTransaction();
+    }
+
+    public void commitTransaction() throws BillingException {
+        dataAccessObject.commitTransaction();
+    }
+
+    public void rollbackTransaction() throws BillingException {
+        dataAccessObject.rollbackTransaction();
+    }
+
+    public int addSubscription(Subscription subscription) throws BillingException {
+        int subscriptionId = 0;
+        try {
+            beginTransaction();
+            subscriptionId = dataAccessObject.addSubscription(subscription,
+                                subscription.getSubscriptionPlan());
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while adding subscription: " + subscription.getSubscriptionPlan()+
+                            " for the customer " + subscription.getCustomer().getName() + " " + e.getMessage() ;
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptionId;
+    }
+
+    public void deleteBillingData(int tenantId) throws BillingException {
+        try {
+            beginTransaction();
+            dataAccessObject.deleteBillingData(tenantId);
+            commitTransaction();
+        } catch (Exception e) {
+            rollbackTransaction();
+            String msg = "Error occurred while deleting subscription for tenant id: " + tenantId ;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    public List<Customer> getCustomersWithName(String customerName) throws BillingException {
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        List<Customer> customers = new ArrayList<Customer>();
+        try {
+            int tenantId = tenantManager.getTenantId(customerName);
+            Tenant tenant = tenantManager.getTenant(tenantId);
+            if (tenant != null) {
+                Customer customer = new Customer();
+                customer.setId(tenant.getId());
+                customer.setName(tenant.getDomain());
+                customer.setStartedDate(tenant.getCreatedDate());
+                customer.setEmail(tenant.getEmail());
+                //customer.setAddress();
+                customers.add(customer);
+            }
+        } catch (Exception e) {
+            String msg = "Failed to get customers for customers: " + customerName + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return customers;
+    }
+
+    public Subscription getSubscription(int subscriptionId) throws BillingException {
+        Subscription subscription = null;
+        try {
+            beginTransaction();
+            subscription = dataAccessObject.getSubscription(subscriptionId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting subscription with id: " + subscriptionId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public Subscription getActiveSubscriptionOfCustomer(int customerId) throws BillingException {
+        Subscription subscription;
+        try {
+            beginTransaction();
+            subscription = dataAccessObject.getActiveSubscriptionOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting active subscription for customer: "
+                            + customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscription;
+    }
+
+    public int getItemIdWithName(String name, int parentId) throws BillingException {
+        int itemId;
+        try {
+            beginTransaction();
+            itemId = dataAccessObject.getItemId(name, parentId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting item id for item name: " + name +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return itemId;
+    }
+
+    public boolean changeSubscription(int customerId, String subscriptionPlan) throws BillingException {
+        boolean changed = false;
+        String oldSubscriptionPlan = null;
+
+        try {
+            beginTransaction();
+            Subscription oldSubscription = getActiveSubscriptionOfCustomer(customerId);
+            if(oldSubscription!=null){
+                oldSubscriptionPlan = oldSubscription.getSubscriptionPlan();
+            }
+            changed = dataAccessObject.changeSubscription(customerId, subscriptionPlan);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while changing subscription to: " + subscriptionPlan +
+                            " for customer: " + customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+
+        try {
+            // Notify Listeners about the subscription change
+            Util.alertTenantSubscriptionPlanChange(
+                    customerId, oldSubscriptionPlan, subscriptionPlan);
+        } catch (StratosException e) {
+            log.error(e.getMessage(), e);
+            throw new BillingException(e.getMessage(), e);
+        }
+
+        return changed;
+    }
+
+    public List<Subscription> getInactiveSubscriptionsOfCustomer(int customerId) throws BillingException {
+        List<Subscription> subscriptions;
+        try {
+            beginTransaction();
+            subscriptions = dataAccessObject.getInactiveSubscriptionsOfCustomer(customerId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while getting inactive subscriptions of customer: " +
+                            customerId + " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+
+    }
+
+    public boolean activateSubscription(int subscriptionId) throws BillingException {
+        boolean activated = false;
+        try {
+            beginTransaction();
+            activated = dataAccessObject.activateSubscription(subscriptionId);
+            commitTransaction();
+        } catch(Exception e){
+            String msg = "Error occurred while activating subscription with id: " + subscriptionId +
+                            " " + e.getMessage();
+            log.error(msg, e);
+            rollbackTransaction();
+            throw new BillingException(msg, e);
+        }
+        return activated;
+    }
+
+    public boolean deactivateActiveSubscription(int tenantId) throws BillingException {
+        boolean deactivated = false;
+        try{
+            beginTransaction();
+            deactivated = dataAccessObject.deactivateCurrentSubscriptoin(tenantId);
+            commitTransaction();
+        }catch(Exception e){
+            rollbackTransaction();
+            String msg = "Error occurred while deactivating the active subscription of customer: " +
+                            tenantId;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        return deactivated;
+    }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
new file mode 100644
index 0000000..04260fd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.beans;
+
+import java.util.Date;
+
+/**
+ * This class holds the data to be shown in the invoice summary page of all
+ * tenants
+ */
+public class OutstandingBalanceInfoBean {
+
+    private int invoiceId;
+    private String customerName;
+    private String subscription;
+    private String carriedForward;
+    private Date lastPaymentDate;
+    private Date lastInvoiceDate;
+    private String lastPaidAmount;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public String getCustomerName() {
+        return customerName;
+    }
+
+    public void setCustomerName(String customerName) {
+        this.customerName = customerName;
+    }
+
+    public String getSubscription() {
+        return subscription;
+    }
+
+    public void setSubscription(String subscription) {
+        this.subscription = subscription;
+    }
+
+    public String getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(String carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public Date getLastPaymentDate() {
+        return lastPaymentDate;
+    }
+
+    public void setLastPaymentDate(Date lastPaymentDate) {
+        this.lastPaymentDate = lastPaymentDate;
+    }
+
+    public String getLastPaidAmount() {
+        return lastPaidAmount;
+    }
+
+    public void setLastPaidAmount(String lastPaidAmount) {
+        this.lastPaidAmount = lastPaidAmount;
+    }
+
+    public Date getLastInvoiceDate() {
+        return lastInvoiceDate;
+    }
+
+    public void setLastInvoiceDate(Date lastInvoiceDate) {
+        this.lastInvoiceDate = lastInvoiceDate;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
new file mode 100644
index 0000000..68e968e
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
@@ -0,0 +1,52 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.core.beans;
+
+import org.wso2.carbon.utils.Pageable;
+
+import java.util.List;
+
+/**
+ * Class used paginating the invoice summaries of all tenants
+ */
+public class PaginatedBalanceInfoBean implements Pageable {
+
+    private OutstandingBalanceInfoBean[] balanceInfoBeans;
+    private int numberOfPages;
+
+    public OutstandingBalanceInfoBean[] getBalanceInfoBeans() {
+        return balanceInfoBeans;
+    }
+
+    public void setBalanceInfoBeans(OutstandingBalanceInfoBean[] balanceInfoBeans) {
+        this.balanceInfoBeans = balanceInfoBeans;
+    }
+
+    public int getNumberOfPages() {
+        return numberOfPages;
+    }
+
+    public void setNumberOfPages(int numberOfPages) {
+        this.numberOfPages = numberOfPages;
+    }
+
+    public <T> void set(List<T> items) {
+        this.balanceInfoBeans =
+                items.toArray(new OutstandingBalanceInfoBean[items.size()]);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
new file mode 100644
index 0000000..0027f16
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.conf;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.internal.Util;
+import org.wso2.carbon.ndatasource.common.DataSourceException;
+
+import javax.sql.DataSource;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * This class reads the billing-config.xml file and
+ * keeps the billing task configurations in a map.
+ * There are two configurations, one for scheduled bill generation
+ * and the other for on-demand bill generation
+ */
+public class BillingConfiguration {
+    private static final Log log = LogFactory.getLog(BillingConfiguration.class);
+    DataSource dataSource;
+    Map<String, BillingTaskConfiguration> billingTaskConfigs = new HashMap<String, BillingTaskConfiguration>();
+
+    public BillingConfiguration(String billingConfigFile) throws BillingException {
+        try {
+            dataSource = (DataSource) Util.getDataSourceService().getDataSource(BillingConstants.WSO2_BILLING_DS).getDSObject();
+            OMElement billingConfig = buildOMElement(new FileInputStream(billingConfigFile));
+            deserialize(billingConfig);
+        } catch (FileNotFoundException e) {
+            String msg = "Unable to find the file responsible for billing task configs: "
+                            + billingConfigFile;
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } catch (DataSourceException e) {
+            String msg = "Error retrieving Billing datasource from master-datasources.xml configuration.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    private OMElement buildOMElement(InputStream inputStream) throws BillingException {
+        XMLStreamReader parser;
+        try {
+            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
+        } catch (XMLStreamException e) {
+            String msg = "Error in initializing the parser to build the OMElement.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+        return builder.getDocumentElement();
+    }
+    
+    /*
+       Deserialize the following
+       <billingConfig xmlns="http://wso2.com/carbon/multitenancy/billing/config">
+           <dbConfig>
+                ...
+           </dbConfig>
+           <tasks>
+                <task id="multitenancyScheduledTask">
+                    ...
+                </task>
+                <task id="multitenancyViewingTask">
+                    ...
+                </task>
+            </tasks>
+        </billingConfig>
+     */
+    private void deserialize(OMElement billingConfigEle) throws BillingException {
+        Iterator billingConfigChildIt = billingConfigEle.getChildElements();
+        
+        while (billingConfigChildIt.hasNext()) {
+            OMElement billingConfigChildEle = (OMElement) billingConfigChildIt.next();
+            
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.TASKS,
+                    BillingConstants.NS_PREFIX).equals(billingConfigChildEle.getQName())) {
+                //element is "tasks"
+                Iterator taskConfigChildIt = billingConfigChildEle.getChildElements();
+                while (taskConfigChildIt.hasNext()) {
+                    OMElement taskConfigEle = (OMElement) taskConfigChildIt.next();
+                    String id = taskConfigEle.getAttributeValue(new QName(BillingConstants.ATTR_ID));
+                    BillingTaskConfiguration taskConfig =
+                            new BillingTaskConfiguration(id, taskConfigEle);
+                    billingTaskConfigs.put(id, taskConfig);
+                }
+            } else {
+                String msg = "Unknown element in Billing Configuration: " +
+                                billingConfigChildEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }
+
+    /*
+     * Deserialise dbConfigElement (Given below) and initialize data source
+        <dbConfig>
+            <url>jdbc:mysql://localhost:3306/billing</url>
+            <userName>billing</userName>
+            <password>billing</password>
+            <driverName>com.mysql.jdbc.Driver</driverName>
+            <maxActive>80</maxActive>
+            <maxWait>60000</maxWait>
+            <minIdle>5</minIdle>
+            <validationQuery>SELECT 1</validationQuery>
+        </dbConfig>
+     */
+    /*private void initDataSource(OMElement dbConfigEle) throws BillingException {
+        // initializing the data source and load the database configurations
+        Iterator dbConfigChildIt = dbConfigEle.getChildElements();
+        dataSource = new BasicDataSource();
+        
+        while (dbConfigChildIt.hasNext()) {
+            
+            OMElement dbConfigChildEle = (OMElement) dbConfigChildIt.next();
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_URL,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setUrl(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_USER_NAME,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setUsername(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_PASSWORD,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setPassword(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_DRIVER_NAME,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setDriverClassName(dbConfigChildEle.getText());
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MAX_ACTIVE,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMaxActive(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MAX_WAIT,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMaxWait(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.DBCONFIG_MIN_IDLE,
+                    BillingConstants.NS_PREFIX).equals(dbConfigChildEle.getQName())) {
+                dataSource.setMinIdle(Integer.parseInt(dbConfigChildEle.getText()));
+            } else if (new QName(BillingConstants.CONFIG_NS, 
+                    BillingConstants.DBCONFIG_VALIDATION_QUERY, BillingConstants.NS_PREFIX)
+                    .equals(dbConfigChildEle.getQName())) {
+                dataSource.setValidationQuery(dbConfigChildEle.getText());
+            } else {
+                String msg = "Unknown element in DBConfig of Billing Configuration: " +
+                                dbConfigChildEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }*/
+
+    public Map<String, BillingTaskConfiguration> getBillingTaskConfigs() {
+        return billingTaskConfigs;
+    }
+
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
new file mode 100644
index 0000000..5530ed1
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.conf;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.scheduler.ScheduleHelper;
+
+import javax.xml.namespace.QName;
+import java.util.*;
+
+public class BillingTaskConfiguration {
+    private static final Log log = LogFactory.getLog(BillingTaskConfiguration.class);
+
+    private String id;
+    private ScheduleHelper scheduleHelper = null;
+    private Map<String, String> schedulerHelperArgs;
+    private String schedulerServiceName;
+
+    private List<BillingHandler> billingHandlers = new ArrayList<BillingHandler>();
+    private List<HandlerConfigBean> handlerArgs = new ArrayList<HandlerConfigBean>(); //key - handler service name
+    private static Map<String, ScheduleHelper> schedulerServices =
+            new HashMap<String, ScheduleHelper>(); 
+    private static Map<String, BillingHandler> handlerServices =
+            new HashMap<String, BillingHandler>();
+
+    private class HandlerConfigBean {
+        public String name;
+        public boolean isServiceType;
+        public Map<String, String> constructorArgs;
+
+        public HandlerConfigBean(String name, boolean isServiceType, Map<String, String> constructorArgs){
+            this.name = name;
+            this.isServiceType = isServiceType;
+            this.constructorArgs = constructorArgs;
+        }
+    }
+
+    public BillingTaskConfiguration(String id, OMElement billingConfigEle) throws BillingException {
+        this.id = id;
+        deserialize(billingConfigEle);
+    }
+
+    /*
+     *  Deserialize following and creates tasks
+        <task id="multitenancyScheduledTask">
+            <subscriptionFilter>multitenancy</subscriptionFilter>
+            <schedule scheduleHelperClass="package.ClassName">
+                ...
+            </schedule>
+            <handlers>
+                ...
+            </handlers>
+        </task>
+     */
+    private void deserialize(OMElement taskConfigEle) throws BillingException {
+        Iterator billingConfigChildIt = taskConfigEle.getChildElements();
+        
+        while (billingConfigChildIt.hasNext()) {
+            OMElement childEle = (OMElement) billingConfigChildIt.next();
+            if (new QName(BillingConstants.CONFIG_NS, BillingConstants.SCHEDULE_CONF_KEY,
+                    BillingConstants.NS_PREFIX).equals(childEle.getQName())) {
+                deserializeSchedule(childEle);
+            } else if (new QName(BillingConstants.CONFIG_NS, BillingConstants.HANDLERS,
+                    BillingConstants.NS_PREFIX).equals(childEle.getQName())) {
+                deserializeHandlers(childEle);
+            } else {
+                String msg = "Unknown element in task configuration for task " + id +
+                                ": " + childEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+        }
+    }
+
+    /*
+        <handlers>
+            <handler service="serviceName">
+            </handler>
+            <handler class="org.wso2.carbon.billing.core.handlers.EmailSendingHandler">
+                <parameter name="file">email-billing-notifications.xml</parameter>
+            </handler>
+        </handlers>
+     */
+    private void deserializeHandlers(OMElement handlersEle) throws BillingException {
+        // iterate through each billingHandlers
+        Iterator handlersChildIt = handlersEle.getChildElements();
+        
+        while (handlersChildIt.hasNext()) {
+            OMElement handlerEle = (OMElement) handlersChildIt.next();
+            if (!(new QName(BillingConstants.CONFIG_NS, BillingConstants.HANDLER,
+                    BillingConstants.NS_PREFIX).equals(handlerEle.getQName()))) {
+                String msg = "Unknown element in handler configuration for task " + id +
+                                ": " + handlerEle.getQName().getLocalPart();
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+
+            // get the parameters for handler
+            Iterator handlerParametersIt = handlerEle.getChildElements();
+            Map<String, String> constructorArgs = extractConstructorArgs(handlerParametersIt);
+            String handlerClassName =
+                    handlerEle.getAttributeValue(new QName(BillingConstants.HANDLER_CLASS_ATTR));
+            if (handlerClassName == null) {
+                // className is not given. So, it uses a handlerService
+                String handlerServiceName = handlerEle.getAttributeValue(
+                        new QName(BillingConstants.HANDLER_SERVICE_ATTR));
+                HandlerConfigBean bean = new HandlerConfigBean(handlerServiceName, true, constructorArgs);
+                handlerArgs.add(bean);
+            } else {
+                HandlerConfigBean bean = new HandlerConfigBean(handlerClassName, false, constructorArgs);
+                handlerArgs.add(bean);
+            }
+        }
+    }
+
+    /* 
+     * Deserialize following and creates scheduleHelper
+        <schedule scheduleHelperClass="package.ClassName">
+            <parameter name="dayToTriggerOn">1</parameter>
+            <parameter name="hourToTriggerOn">0</parameter>
+            <parameter name="timeZone">GMT-8:00</parameter>
+        </schedule>
+     */
+    private void deserializeSchedule(OMElement scheduleEle) throws BillingException {
+        Iterator scheduleHelperConfigChildIt = scheduleEle.getChildElements();
+        Map<String, String> constructorArgs = extractConstructorArgs(scheduleHelperConfigChildIt);
+        
+        // get the scheduleHelper class name
+        String className = scheduleEle.getAttributeValue(
+                new QName(BillingConstants.TRIGGER_CALCULATOR_CLASS_ATTR));
+        
+        if (className == null) {
+            //className is not given; it is using scheduler service
+            schedulerServiceName = scheduleEle.getAttributeValue(
+                    new QName(BillingConstants.TRIGGER_CALCULATOR_SERVICE_ATTR));
+            schedulerHelperArgs = constructorArgs;
+        } else {
+            //className is given; Construct the object
+            scheduleHelper = (ScheduleHelper) constructObject(className);
+            scheduleHelper.init(constructorArgs);
+        }
+    }
+
+    public ScheduleHelper getScheduleHelper() throws BillingException {
+        if (scheduleHelper == null && schedulerServiceName != null) {
+            scheduleHelper = schedulerServices.get(schedulerServiceName);
+            if (scheduleHelper == null) {
+                String msg = "The scheduler helper service: " + schedulerServiceName +
+                                " is not loaded.";
+                log.error(msg);
+                throw new BillingException(msg);
+            }
+            scheduleHelper.init(schedulerHelperArgs);
+        }
+        return scheduleHelper;
+    }
+
+    public List<BillingHandler> getBillingHandlers() throws BillingException {
+        // We have to combine the handlers and handlerServices as a single list and return. When
+        // creating and initializing handerServices, remove them from the handelerArgs so that they
+        // will be included only once
+        if(!handlerArgs.isEmpty()){
+            for(HandlerConfigBean bean : handlerArgs){
+                if(bean.isServiceType){
+                    BillingHandler handlerService = handlerServices.get(bean.name);
+                    if (handlerService == null) {
+                        billingHandlers = null;
+                        String msg = "The handler service: " + bean.name + " is not loaded.";
+                        log.error(msg);
+                        throw new BillingException(msg);
+                    }
+                    handlerService.init(bean.constructorArgs);
+                    billingHandlers.add(handlerService);
+
+                } else {
+                    BillingHandler handler = (BillingHandler) constructObject(bean.name);
+                    handler.init(bean.constructorArgs);
+                    billingHandlers.add(handler);
+                }
+            }
+
+            //all the billing handler services are initialized properly, can clear handlerArgs
+            handlerArgs.clear();
+        }
+        return billingHandlers;
+    }
+
+    private static Object constructObject(String className) throws BillingException {
+        try {
+            return Class.forName(className).newInstance();
+        } catch (ClassNotFoundException e) {
+            String msg = "The class: " + className + " is not in the classpath.";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        } catch (Exception e) {
+            String msg = "Error in initializing the object for " + className + ".";
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    private static Map<String, String> extractConstructorArgs(Iterator parameterIt) {
+        Map<String, String> constructorArgs = new HashMap<String, String>();
+        
+        while (parameterIt.hasNext()) {
+            OMElement paramEle = (OMElement) parameterIt.next();
+            if (!new QName(BillingConstants.CONFIG_NS, BillingConstants.SCHEDULE_CONF_PARAM_KEY,
+                    BillingConstants.NS_PREFIX).equals(paramEle.getQName())) {
+                continue;
+            }
+            
+            String paramName = paramEle.getAttributeValue(
+                    new QName(BillingConstants.SCHEDULE_CONF_PARAM_NAME_KEY));
+            String paramValue = paramEle.getText();
+            constructorArgs.put(paramName, paramValue);
+        }
+        return constructorArgs;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    // the following two methods will be called when the services are available for the schedule
+    // helper and the billing handlers
+    public static void addScheduleHelper(ScheduleHelper scheduleHelper) {
+        schedulerServices.put(scheduleHelper.getClass().getName(), scheduleHelper);
+    }
+
+    public static void addBillingHandler(BillingHandler billingHandler) {
+        handlerServices.put(billingHandler.getClass().getName(), billingHandler);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
new file mode 100644
index 0000000..e9d760a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core.dataobjects;
+
+import org.wso2.carbon.billing.core.BillingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.regex.Pattern;
+
+
+public class Cash {
+    private static final Log log = LogFactory.getLog(Cash.class);
+    public static final String CURRENCY_USD = "$";
+    public static final String DEFAULT_CURRENCY = CURRENCY_USD;
+
+    public enum Sign {
+        POSITIVE, NEGATIVE
+    };
+
+    String currency;
+    int wholeNumber;
+    int decimalNumber;
+    Sign sign = Sign.POSITIVE; // true for positive
+
+    private static final String notNumbersRegEx = "[^0-9]";
+    private static final Pattern notNumbersPattern = Pattern.compile(notNumbersRegEx);
+
+    public Cash() {
+        // the default constructor for Cash
+    }
+
+    public Cash(Cash copyFrom) {
+        this.currency = copyFrom.getCurrency();
+        this.wholeNumber = copyFrom.getWholeNumber();
+        this.decimalNumber = copyFrom.getDecimalNumber();
+        this.sign = copyFrom.getSign();
+    }
+
+    public Cash(String cashString) throws BillingException {
+        if (cashString == null) {
+            cashString = "$0";
+        }
+        if (cashString.startsWith(CURRENCY_USD)) {
+            cashString = cashString.substring(CURRENCY_USD.length());
+            currency = CURRENCY_USD;
+        }
+        // possible other currencies
+        else {
+            currency = DEFAULT_CURRENCY;
+        }
+
+        if (cashString.startsWith("-")) {
+            sign = Sign.NEGATIVE;
+            cashString = cashString.substring(1);
+        } else if (cashString.startsWith("+")) {
+            sign = Sign.POSITIVE;
+            cashString = cashString.substring(1);
+        } else {
+            sign = Sign.POSITIVE;
+        }
+
+        if (cashString.contains(".")) {
+            String wholeNumberStr = cashString.substring(0, cashString.indexOf("."));
+            if (wholeNumberStr.trim().equals("")) {
+                String msg = "Whole number can not be empty";
+                throw new BillingException(msg);
+            }
+            if (notNumbersPattern.matcher(wholeNumberStr).find()) {
+                String msg = "The whole number expected to have only 0-9 characters.: " +
+                                wholeNumberStr + " is not a number. ";
+                throw new BillingException(msg);
+            }
+            
+            String decimalNumberStr = cashString.substring(cashString.indexOf(".") + 1);
+            if (notNumbersPattern.matcher(decimalNumberStr).find()) {
+                String msg = "The decimal number expected to have only 0-9 characters.: " +
+                                decimalNumberStr + " is not a number. ";
+                throw new BillingException(msg);
+            }
+            if (decimalNumberStr.length() == 0) {
+                String msg = "String after the decimal point is zero.";
+                throw new BillingException(msg);
+            } else if (decimalNumberStr.length() > 2) {
+                String msg = "String after the decimal point is greater than 2";
+                throw new BillingException(msg);
+            } else if (decimalNumberStr.length() == 1) {
+                decimalNumberStr += "0";
+            }
+            
+            wholeNumber = Integer.parseInt(wholeNumberStr);
+            decimalNumber = Integer.parseInt(decimalNumberStr);
+            
+        } else {
+            if (notNumbersPattern.matcher(cashString).find()) {
+                String msg = "The cash string to have only 0-9 characters.: " + cashString +
+                                " is not a number. ";
+                throw new BillingException(msg);
+            }
+            
+            wholeNumber = Integer.parseInt(cashString);
+            decimalNumber = 0;
+        }
+    }
+
+    public Sign getSign() {
+        return sign;
+    }
+
+    public void setSign(Sign sign) {
+        this.sign = sign;
+    }
+
+    public String getCurrency() {
+        return currency;
+    }
+
+    public void setCurrency(String currency) {
+        this.currency = currency;
+    }
+
+    public int getWholeNumber() {
+        return wholeNumber;
+    }
+
+    public void setWholeNumber(int wholeNumber) {
+        this.wholeNumber = wholeNumber;
+    }
+
+    public int getDecimalNumber() {
+        return decimalNumber;
+    }
+
+    public void setDecimalNumber(int decimalNumber) {
+        this.decimalNumber = decimalNumber;
+    }
+
+    public String serializeToString() {
+        String str = currency;
+        if (sign == Sign.NEGATIVE) {
+            str += "-";
+        }
+        str += wholeNumber + ".";
+        if (decimalNumber < 10) {
+            str += "0" + decimalNumber;
+        } else {
+            str += decimalNumber;
+        }
+        return str;
+    }
+
+    @Override
+    public String toString() {
+        return serializeToString();
+    }
+
+    public static Cash add(Cash a, Cash b) throws BillingException {
+        if (!a.getCurrency().equals(b.getCurrency())) {
+            // we still not support this.
+            String msg = "Can not add in-similar currencies: " + a.getCurrency() + "!=" +
+                            b.getCurrency() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        if (a.getSign() == Sign.POSITIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash b2 = new Cash(b);
+            b2.setSign(Sign.POSITIVE);
+            return subtract(a, b2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.POSITIVE) {
+            Cash a2 = new Cash(a);
+            a2.setSign(Sign.POSITIVE);
+            return subtract(b, a2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash a2 = new Cash(a);
+            Cash b2 = new Cash(b);
+            a2.setSign(Sign.POSITIVE);
+            b2.setSign(Sign.POSITIVE);
+            Cash c2 = add(a2, b2);
+            c2.setSign(Sign.NEGATIVE);
+            return c2;
+        }
+        
+        int decimalSum = a.getDecimalNumber() + b.getDecimalNumber();
+        int wholeSum = a.getWholeNumber() + b.getWholeNumber();
+
+        Cash cash = new Cash();
+        cash.setCurrency(a.getCurrency());
+        if (decimalSum >= 100) {
+            decimalSum -= 100;
+            wholeSum += 1;
+        }
+        cash.setDecimalNumber(decimalSum);
+        cash.setWholeNumber(wholeSum);
+        cash.setSign(Sign.POSITIVE);
+        return cash;
+    }
+
+    public static Cash subtract(Cash a, Cash b) throws BillingException {
+        if (!a.getCurrency().equals(b.getCurrency())) {
+            // we still not support this.
+            String msg = "Can not add in-similar currencies: " + a.getCurrency() + "!=" +
+                            b.getCurrency() + ".";
+            log.error(msg);
+            throw new BillingException(msg);
+        }
+        
+        if (a.getSign() == Sign.POSITIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash b2 = new Cash(b);
+            b2.setSign(Sign.POSITIVE);
+            return add(a, b2);
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.POSITIVE) {
+            Cash a2 = new Cash(a);
+            a2.setSign(Sign.POSITIVE);
+            Cash c2 = add(b, a2);
+            c2.setSign(Sign.NEGATIVE);
+            return c2;
+        }
+        
+        if (a.getSign() == Sign.NEGATIVE && b.getSign() == Sign.NEGATIVE) {
+            Cash a2 = new Cash(a);
+            Cash b2 = new Cash(b);
+            a2.setSign(Sign.POSITIVE);
+            b2.setSign(Sign.POSITIVE);
+            Cash c2 = subtract(a2, b2);
+            if (c2.getSign() == Sign.NEGATIVE) {
+                c2.setSign(Sign.POSITIVE);
+            } else {
+                c2.setSign(Sign.NEGATIVE);
+            }
+            return c2;
+        }
+        
+        int decimalSum = a.getDecimalNumber() - b.getDecimalNumber();
+        int wholeSum = a.getWholeNumber() - b.getWholeNumber();
+
+        if (wholeSum < 0 || (decimalSum < 0 && wholeSum == 0)) {
+            // then it is negative value
+            Cash c = subtract(b, a);
+            c.setSign(Sign.NEGATIVE);
+            return c;
+        }
+
+        Cash cash = new Cash();
+        cash.setCurrency(a.getCurrency());
+        if (decimalSum < 0) {
+            decimalSum += 100;
+            wholeSum -= 1;
+        }
+
+        cash.setDecimalNumber(decimalSum);
+        cash.setWholeNumber(wholeSum);
+        return cash;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (!(o instanceof Cash)) {
+            return false;
+        }
+        Cash otherCash = (Cash) o;
+        return otherCash.serializeToString().equals(this.serializeToString());
+    }
+
+    @Override
+    public int hashCode() {
+        return serializeToString().hashCode();
+    }
+
+    public Cash multiply(double multiplyBy) {
+        long answerInCent = (long) (wholeNumber * 100 * multiplyBy + decimalNumber * multiplyBy);
+        int newWholeNumber = (int) (answerInCent / 100);
+        int newDecimalNumber = (int) (answerInCent % 100);
+
+        Cash cash = new Cash();
+        cash.setCurrency(this.getCurrency());
+        if (newWholeNumber < 0) {
+            cash.setSign(Sign.NEGATIVE);
+        }
+        cash.setWholeNumber(newWholeNumber);
+        cash.setDecimalNumber(newDecimalNumber);
+        return cash;
+    }
+}


[23/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
new file mode 100644
index 0000000..cd9b4bd
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
@@ -0,0 +1,201 @@
+package org.wso2.carbon.billing.mgt.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.mgt.services.BillingDataAccessService;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.user.api.Tenant;
+import org.wso2.carbon.user.api.TenantManager;
+
+import java.util.Calendar;
+
+public class DefaultTenantBilling implements TenantBillingService {
+    
+    private static final Log log = LogFactory.getLog(DefaultTenantBilling.class);
+    
+    public void addUsagePlan(Tenant tenant, String usagePlan) throws StratosException {
+
+        Customer customer = new Customer();
+        customer.setName(tenant.getDomain());
+        customer.setEmail(tenant.getEmail());
+        customer.setStartedDate(tenant.getCreatedDate());
+        customer.setFullName(tenant.getAdminFirstName() + " " + tenant.getAdminLastName());
+
+        customer.setId(tenant.getId());
+        Subscription subscription = new Subscription();
+        subscription.setCustomer(customer);
+        subscription.setActive(false);
+        subscription.setActiveSince(Calendar.getInstance().getTime());
+        Item item = new Item();
+        subscription.setItem(item);
+        subscription.setSubscriptionPlan(usagePlan);
+        try {
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            dataAccessService.addSubscription(subscription);
+        } catch (Exception e) {
+            log.error("Could not add new subscription for tenant: " +
+                      tenant.getDomain() + " " + e.getMessage(), e);
+        }
+    }
+
+    public String getActiveUsagePlan(String tenantDomain) throws StratosException {
+        Subscription subscription;
+        try {
+            TenantManager tenantMan = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantMan.getTenantId(tenantDomain);
+            BillingDataAccessService billingDataAccessService = new BillingDataAccessService();
+            subscription = billingDataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+        } catch (Exception e) {
+            String msg = "Error occurred while getting the usage plan for tenant: " + 
+                         tenantDomain + " " + e.getMessage();
+            log.error(msg);
+            throw new StratosException(msg, e);
+        }
+
+        if(subscription!=null){
+            return subscription.getSubscriptionPlan();
+        }else{
+            return null;
+        }
+    }
+
+    public void updateUsagePlan(String tenantDomain, String usagePlan) throws StratosException {
+        try {
+            TenantManager tenantManager = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantManager.getTenantId(tenantDomain);
+
+            BillingDataAccessService billingDataAccessService = new BillingDataAccessService();
+            Subscription currentSubscription = billingDataAccessService.
+                    getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+
+            if (currentSubscription != null && currentSubscription.getSubscriptionPlan() != null) {
+                if (!currentSubscription.getSubscriptionPlan().equals(usagePlan)) {
+                    boolean updated = billingDataAccessService.changeSubscriptionBySuperTenant(tenantId, usagePlan);
+                    if (updated) {
+                        log.debug("Usage plan was changed successfully from " + currentSubscription.getSubscriptionPlan() +
+                                  " to " + usagePlan);
+                    } else {
+                        log.debug("Usage plan was not changed");
+                    }
+                }
+            }else{
+                //tenant does not have an active subscription. First we have to check whether the tenant
+                //is active. If he is active only we will add a new usage plan. Otherwise it is useless
+                //to add a usage plan to an inactive tenant
+                Tenant tenant = tenantManager.getTenant(tenantId);
+                if(tenant.isActive()){
+                    //we add a new subscription
+                    Subscription subscription = new Subscription();
+                    subscription.setActive(true);
+                    subscription.setSubscriptionPlan(usagePlan);
+                    subscription.setActiveSince(null);
+                    subscription.setActiveUntil(null);
+                    Customer customer = new Customer();
+                    customer.setName(tenantDomain);
+                    customer.setId(tenantId);
+                    subscription.setCustomer(customer);
+
+                    int subsId = billingDataAccessService.addSubscription(subscription);
+                    if(subsId>0){
+                        log.info("Added a new " + subscription.getSubscriptionPlan() + " plan for the tenant " +
+                                 tenantDomain);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while changing the subscription plan for tenant: " + tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void activateUsagePlan(String tenantDomain) throws StratosException {
+        try {
+            TenantManager tenantManager = CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantManager.getTenantId(tenantDomain);
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            Subscription subscription = dataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+            if (subscription != null) {
+                String msg = "Unable to activate the subscription for tenant: " + tenantId +
+                             ". An active subscription already exists";
+                log.info(msg);
+            } else {
+                Subscription[] inactiveSubscriptions = dataAccessService.getInactiveSubscriptionsOfCustomer(tenantId);
+                if (inactiveSubscriptions.length == 1) {
+                    //This is the scenario where the tenant has registered, but not activated yet
+                    subscription = inactiveSubscriptions[0];
+                    boolean activated = dataAccessService.activateSubscription(subscription.getId());
+                    if (activated) {
+                        log.info("Subscription was activated for tenant: " + tenantId);
+                    }
+                }else if(inactiveSubscriptions.length > 1){
+                    //this is the scenario where the tenant has been deactivated by admin and
+                    //again activated. Here, I am adding a new active subscription which is similar to the
+                    //last existed one
+                    Subscription subscriptionToAdd = inactiveSubscriptions[0];
+                    subscriptionToAdd.setActive(true);
+                    subscriptionToAdd.setActiveSince(null);
+                    subscriptionToAdd.setActiveUntil(null);
+
+                    int subsId = dataAccessService.addSubscription(subscriptionToAdd);
+                    if(subsId>0){
+                        log.info("New subscription: " + subscriptionToAdd.getSubscriptionPlan() +
+                                " added and it was activated for tenant: " + tenantId);
+                    }
+                }else{
+                    //this means there are no subscriptions. Lets handle this later
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while activating the subscription for tenant: " +
+                    tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void deactivateActiveUsagePlan(String tenantDomain) throws StratosException {
+        try {
+            TenantManager tenantMan = 
+                    CloudCommonServiceComponent.getRealmService().getTenantManager();
+            int tenantId = tenantMan.getTenantId(tenantDomain);
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+
+            Subscription subscription = 
+                    dataAccessService.getActiveSubscriptionOfCustomerBySuperTenant(tenantId);
+
+            if (subscription == null) {
+                String msg = "Unable to deactivate the subscription for tenant: " + tenantId +
+                        ". An active subscription doesn't exist";
+                log.info(msg);
+            } else {
+                boolean deactivated = 
+                        dataAccessService.deactivateActiveSubscriptionBySuperTenant(tenantId);
+                if (deactivated) {
+                    log.info("Active subscription of tenant " + tenantId + " was deactivated");
+                }
+            }
+        } catch (Exception e) {
+            String msg = "Error occurred while deactivating the active subscription of tenant: " +
+                    tenantDomain;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+
+    public void deleteBillingData(int tenantId) throws StratosException{
+        try {
+            BillingDataAccessService dataAccessService = new BillingDataAccessService();
+            dataAccessService.deleteBillingData(tenantId);
+        } catch (Exception e) {
+            String msg = "Error deleting subscription  for tenant: " + tenantId;
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
new file mode 100644
index 0000000..6486767
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.api;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyPackage;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Reads the multitenancy-packages.xml and populates the
+ * multitenancy packages list
+ */
+public class MultitenancyBillingInfo {
+    private static Log log = LogFactory.getLog(MultitenancyBillingInfo.class);
+    private static final String PACKAGE_DESCRIPTION_CONFIG_FILENAME = "multitenancy-packages.xml";
+    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
+            "http://wso2.com/carbon/multitenancy/billing/pacakges";
+    
+    List<MultitenancyPackage> multitenancyPackages = new ArrayList<MultitenancyPackage>();
+
+    public MultitenancyBillingInfo() throws BillingException {
+        // this should be only available to the super tenants..
+        multitenancyPackages = deserializePackageDescriptionConfig();
+    }
+
+    public List<MultitenancyPackage> getMultitenancyPackages() {
+        return multitenancyPackages;
+    }
+
+    /*
+     * Deserialize following XML
+    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+        <package name="multitenancy-free">
+            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+            <users>
+                <limit>5</limit>
+                <charge>0</charge> <!-- charge per month -->
+            </users>
+            <resourceVolume>
+                <limit>10</limit> <!--mb per user -->
+            </resourceVolume>
+            <bandwidth>
+                <limit>1000</limit> <!-- mb per user -->
+                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+            </bandwidth>
+        </package>
+        <package name="multitenancy-small">
+            ...
+        </package>
+    </packages>
+     */
+    private List<MultitenancyPackage> deserializePackageDescriptionConfig() throws BillingException {
+        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                PACKAGE_DESCRIPTION_CONFIG_FILENAME;
+        
+        OMElement packageConfigs;
+        try {
+            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
+        } catch (Exception e) {
+            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+
+        Iterator packageConfigsChildsIt = packageConfigs.getChildElements();
+        while (packageConfigsChildsIt.hasNext()) {
+            OMElement packageConfigEle = (OMElement) packageConfigsChildsIt.next();
+            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
+                    packageConfigEle.getQName())) {
+                continue;
+            }
+            
+            MultitenancyPackage multitenancyPackage = new MultitenancyPackage();
+            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
+            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
+            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
+            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
+
+            String resourceVolumeLimit =
+                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
+            String resourceVolumeOveruseCharge =
+                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
+            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
+            String bandwidthOveruseCharge =
+                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
+            int usersLimitInt = -1;
+            if (!usersLimit.equals("unlimited")) {
+                usersLimitInt = Integer.parseInt(usersLimit);
+            }
+            int resourceVolumeLimitInt = -1;
+            if (!resourceVolumeLimit.equals("unlimited")) {
+                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
+            }
+            int bandwidthLimitInt = -1;
+            if (!bandwidthLimit.equals("unlimited")) {
+                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
+            }
+
+            multitenancyPackage.setName(packageName);
+            multitenancyPackage.setSubscriptionCharge(new Cash(subscriptionCharge));
+            multitenancyPackage.setUsersLimit(usersLimitInt);
+            multitenancyPackage.setChargePerUser(new Cash(usersCharge));
+            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
+            multitenancyPackage.setResourceVolumeOveruseCharge(new Cash(resourceVolumeOveruseCharge));
+            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
+            multitenancyPackage.setBandwidthOveruseCharge(new Cash(bandwidthOveruseCharge));
+
+            
+            multitenancyPackages.add(multitenancyPackage);
+        }
+        return multitenancyPackages;
+    }
+
+    private String getPackageConfigValue(String key, OMElement packageNode) throws BillingException {
+        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
+        AXIOMXPath xpathExpression;
+        try {
+            xpathExpression = new AXIOMXPath(qualifiedKey);
+            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
+            List valueNodes = xpathExpression.selectNodes(packageNode);
+            if (valueNodes.isEmpty()) {
+                if (log.isDebugEnabled()) {
+                    String msg = "No results found parsing package configuration for key: " + 
+                            qualifiedKey + ".";
+                    log.debug(msg);
+                }
+                return null;
+            }
+            OMElement valueNode = (OMElement) valueNodes.get(0);
+            return valueNode.getText();
+        } catch (JaxenException e) {
+            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
+            log.error(msg, e);
+            throw new BillingException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
new file mode 100644
index 0000000..8b88b99
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+/**
+ * Under a subscription there are billed items. For example
+ * subscription fee, bandwidth overuse charge, storage overuse charge
+ */
+public class BilledEntry {
+    String name;
+    String cost;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getCost() {
+        return cost;
+    }
+
+    public void setCost(String cost) {
+        this.cost = cost;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
new file mode 100644
index 0000000..76ff4e6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Date;
+
+/**
+ * This class is used when providing available invoices to the user
+ */
+public class BillingPeriod {
+    private int invoiceId;
+    private Date startDate;
+    private Date endDate;
+    private Date invoiceDate;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public Date getInvoiceDate() {
+        return new Date(invoiceDate.getTime());
+    }
+
+    public void setInvoiceDate(Date invoiceDate) {
+        this.invoiceDate = new Date(invoiceDate.getTime());
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
new file mode 100644
index 0000000..994a161
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Arrays;
+import java.util.Date;
+
+public class MultitenancyInvoice {
+    private int invoiceId;
+    private Date billingDate;
+    private Date startDate;
+    private Date endDate;
+    private String boughtForward;
+    private String carriedForward;
+    private String totalPayments;
+    private String totalCost;
+    private boolean lastInvoice;
+    private MultitenancySubscription[] subscriptions;
+    private MultitenancyPurchaseOrder[] purchaseOrders;
+
+    public int getInvoiceId() {
+        return invoiceId;
+    }
+
+    public void setInvoiceId(int invoiceId) {
+        this.invoiceId = invoiceId;
+    }
+
+    public Date getBillingDate() {
+        return new Date(billingDate.getTime());
+    }
+
+    public void setBillingDate(Date billingDate) {
+        this.billingDate = new Date(billingDate.getTime());
+    }
+
+    public Date getStartDate() {
+        return new Date(startDate.getTime());
+    }
+
+    public void setStartDate(Date startDate) {
+        this.startDate = new Date(startDate.getTime());
+    }
+
+    public Date getEndDate() {
+        return new Date(endDate.getTime());
+    }
+
+    public void setEndDate(Date endDate) {
+        this.endDate = new Date(endDate.getTime());
+    }
+
+    public String getBoughtForward() {
+        return boughtForward;
+    }
+
+    public void setBoughtForward(String boughtForward) {
+        this.boughtForward = boughtForward;
+    }
+
+    public String getCarriedForward() {
+        return carriedForward;
+    }
+
+    public void setCarriedForward(String carriedForward) {
+        this.carriedForward = carriedForward;
+    }
+
+    public String getTotalPayments() {
+        return totalPayments;
+    }
+
+    public void setTotalPayments(String totalPayments) {
+        this.totalPayments = totalPayments;
+    }
+
+    public String getTotalCost() {
+        return totalCost;
+    }
+
+    public void setTotalCost(String totalCost) {
+        this.totalCost = totalCost;
+    }
+
+    public boolean isLastInvoice() {
+        return lastInvoice;
+    }
+
+    public void setLastInvoice(boolean lastInvoice) {
+        this.lastInvoice = lastInvoice;
+    }
+
+    public MultitenancySubscription[] getSubscriptions() {
+        return Arrays.copyOf(subscriptions, subscriptions.length);
+    }
+
+    public void setSubscriptions(MultitenancySubscription[] subscriptions) {
+        this.subscriptions = Arrays.copyOf(subscriptions, subscriptions.length);
+    }
+
+    public MultitenancyPurchaseOrder[] getPurchaseOrders() {
+        return Arrays.copyOf(purchaseOrders, purchaseOrders.length);
+    }
+
+    public void setPurchaseOrders(MultitenancyPurchaseOrder[] purchaseOrders) {
+        this.purchaseOrders = Arrays.copyOf(purchaseOrders, purchaseOrders.length);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
new file mode 100644
index 0000000..ffddda0
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Date;
+
+/**
+ * Payment record details
+ */
+public class MultitenancyPurchaseOrder {
+    private Date paymentDate;
+    private String payment;
+    private int id;
+    private String transactionId;
+
+    public Date getPaymentDate() {
+        return new Date(paymentDate.getTime());
+    }
+
+    public void setPaymentDate(Date paymentDate) {
+        this.paymentDate = new Date(paymentDate.getTime());
+    }
+
+    public String getPayment() {
+        return payment;
+    }
+
+    public void setPayment(String payment) {
+        this.payment = payment;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getTransactionId() {
+        return transactionId;
+    }
+
+    public void setTransactionId(String transactionId) {
+        this.transactionId = transactionId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
new file mode 100644
index 0000000..5490e9f
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.beans;
+
+import java.util.Arrays;
+import java.util.Date;
+
+public class MultitenancySubscription {
+    String subscribedPackage;
+    BilledEntry[] billedEntries;
+    Date activeSince;
+    Date activeUntil;
+    boolean isActive;
+
+    public String getSubscribedPackage() {
+        return subscribedPackage;
+    }
+
+    public void setSubscribedPackage(String subscribedPackage) {
+        this.subscribedPackage = subscribedPackage;
+    }
+
+    public BilledEntry[] getBilledEntries() {
+        return Arrays.copyOf(billedEntries, billedEntries.length);
+    }
+
+    public void setBilledEntries(BilledEntry[] billedEntries) {
+        this.billedEntries = Arrays.copyOf(billedEntries, billedEntries.length);
+    }
+
+    public Date getActiveSince() {
+        return new Date(activeSince.getTime());
+    }
+
+    public void setActiveSince(Date activeSince) {
+        this.activeSince = new Date(activeSince.getTime());
+    }
+
+    public Date getActiveUntil() {
+        return new Date(activeUntil.getTime());
+    }
+
+    public void setActiveUntil(Date activeUntil) {
+        this.activeUntil = new Date( activeUntil.getTime());
+    }
+
+    public boolean isActive() {
+        return isActive;
+    }
+
+    public void setActive(boolean active) {
+        isActive = active;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
new file mode 100644
index 0000000..87a716c
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/**
+ * Multitenancy customer class
+ */
+public class MultitenancyCustomer extends Customer {
+
+    private int numberOfUsers;
+    private long incomingBandwidth;
+    private long outgoingBandwidth;
+    private long totalBandwidth;
+    private long currentStorage;
+    private long historyStorage;
+    private long totalStorage;
+    private int tenantId = MultitenantConstants.INVALID_TENANT_ID;
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public int getNumberOfUsers() {
+        return numberOfUsers;
+    }
+
+    public void setNumberOfUsers(int numberOfUsers) {
+        this.numberOfUsers = numberOfUsers;
+    }
+
+    public long getIncomingBandwidth() {
+        return incomingBandwidth;
+    }
+
+    public void setIncomingBandwidth(long incomingBandwidth) {
+        this.incomingBandwidth = incomingBandwidth;
+    }
+
+    public long getOutgoingBandwidth() {
+        return outgoingBandwidth;
+    }
+
+    public void setOutgoingBandwidth(long outgoingBandwidth) {
+        this.outgoingBandwidth = outgoingBandwidth;
+    }
+
+    public long getTotalBandwidth() {
+        return totalBandwidth;
+    }
+
+    public void setTotalBandwidth(long totalBandwidth) {
+        this.totalBandwidth = totalBandwidth;
+    }
+
+    public long getCurrentStorage() {
+        return currentStorage;
+    }
+
+    public void setCurrentStorage(long currentStorage) {
+        this.currentStorage = currentStorage;
+    }
+
+    public long getHistoryStorage() {
+        return historyStorage;
+    }
+
+    public void setHistoryStorage(long historyStorage) {
+        this.historyStorage = historyStorage;
+    }
+
+    public long getTotalStorage() {
+        return totalStorage;
+    }
+
+    public void setTotalStorage(long totalStorage) {
+        this.totalStorage = totalStorage;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        if (!super.equals(o)) {
+            return false;
+        }
+
+        MultitenancyCustomer that = (MultitenancyCustomer) o;
+
+        if (tenantId != that.tenantId) {
+            return false;
+        }
+
+        return true;
+    }
+
+    @Override
+    public int hashCode() {
+        int result = super.hashCode();
+        result = 31 * result + tenantId;
+        return result;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
new file mode 100644
index 0000000..68cf24b
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Cash;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MultitenancyPackage extends Item {
+    public static final String SUBSCRIPTION_SUB_ITEM_NAME = "subscription";
+    public static final String BW_OVERUSE_SUB_ITEM_NAME = "bwOveruse";
+    public static final String STORAGE_OVERUSE_SUB_ITEM_NAME = "storageOveruse";
+    private int usersLimit;
+    private Cash subscriptionCharge;
+    private Cash chargePerUser;
+    //private int resourceVolumeLimit;
+    //private int bandwidthLimit;
+    //private Cash bandwidthOveruseCharge;
+    private List<MultitenancyPackageSubItem> subItems;
+
+    public MultitenancyPackage() {
+        subItems = new ArrayList<MultitenancyPackageSubItem>();
+        // adding subscription sub item
+        MultitenancyPackageSubItem subscriptionSubItem = new MultitenancyPackageSubItem();
+        subscriptionSubItem.setName(SUBSCRIPTION_SUB_ITEM_NAME);
+        subscriptionSubItem.setDescription("Subscription for package");
+        subscriptionSubItem.setParent(this);
+        subItems.add(subscriptionSubItem);
+
+        // adding bandwidth overuse sub item
+        MultitenancyPackageSubItem bandwdithOverUseSubItem = new MultitenancyPackageSubItem();
+        bandwdithOverUseSubItem.setName(BW_OVERUSE_SUB_ITEM_NAME);
+        bandwdithOverUseSubItem.setDescription("Bandwidth overuse");
+        bandwdithOverUseSubItem.setParent(this);
+        subItems.add(bandwdithOverUseSubItem);
+
+        // adding storage overuse sub item
+        MultitenancyPackageSubItem storageOverUseSubItem = new MultitenancyPackageSubItem();
+        storageOverUseSubItem.setName(STORAGE_OVERUSE_SUB_ITEM_NAME);
+        storageOverUseSubItem.setDescription("Storage overuse");
+        storageOverUseSubItem.setParent(this);
+        subItems.add(storageOverUseSubItem);
+
+    }
+
+    public MultitenancyPackage(MultitenancyPackage staticMtPackage, boolean isSubscriptionActive) {
+        usersLimit = staticMtPackage.getUsersLimit();
+        chargePerUser = staticMtPackage.getChargePerUser();
+        subscriptionCharge = staticMtPackage.getSubscriptionCharge();
+        super.setResourceVolumeLimit(staticMtPackage.getResourceVolumeLimit());
+        super.setResourceVolumeOveruseCharge(staticMtPackage.getResourceVolumeOveruseCharge());
+        super.setBandwidthLimit(staticMtPackage.getBandwidthLimit());
+        super.setBandwidthOveruseCharge(staticMtPackage.getBandwidthOveruseCharge());
+        setId(staticMtPackage.getId());
+        setName(staticMtPackage.getName());
+        setCost(staticMtPackage.getCost());
+        setDescription(staticMtPackage.getDescription());
+
+        subItems = new ArrayList<MultitenancyPackageSubItem>();
+        for (Item subItem : staticMtPackage.getChildren()) {
+            //Storage overuse and Bandwidth overuse sub items will be added only to active subscription
+            if(isSubscriptionActive || (!isSubscriptionActive && SUBSCRIPTION_SUB_ITEM_NAME.equals(subItem.getName()))){
+
+                MultitenancyPackageSubItem subscriptionSubItem = new MultitenancyPackageSubItem();
+                subscriptionSubItem.setId(subItem.getId());
+                subscriptionSubItem.setName(subItem.getName());
+                subscriptionSubItem.setDescription(subItem.getDescription());
+                subscriptionSubItem.setParent(this);
+                subItems.add(subscriptionSubItem);
+            }
+        }
+    }
+
+    public int getUsersLimit() {
+        return usersLimit;
+    }
+
+    public void setUsersLimit(int usersLimit) {
+        this.usersLimit = usersLimit;
+    }
+
+    public Cash getChargePerUser() {
+        return chargePerUser;
+    }
+
+    public void setChargePerUser(Cash chargePerUser) {
+        this.chargePerUser = chargePerUser;
+    }
+
+    public Cash getSubscriptionCharge() {
+        return subscriptionCharge;
+    }
+
+    public void setSubscriptionCharge(Cash subscriptionCharge) {
+        this.subscriptionCharge = subscriptionCharge;
+    }
+
+    /*public int getResourceVolumeLimit() {
+        return resourceVolumeLimit;
+    }
+
+    public void setResourceVolumeLimit(int resourceVolumeLimit) {
+        this.resourceVolumeLimit = resourceVolumeLimit;
+    }
+    */
+    /*public int getBandwidthLimit() {
+        return bandwidthLimit;
+    }
+
+    public void setBandwidthLimit(int bandwidthLimit) {
+        this.bandwidthLimit = bandwidthLimit;
+    }
+
+    public Cash getBandwidthOveruseCharge() {
+        return bandwidthOveruseCharge;
+    }
+
+    public void setBandwidthOveruseCharge(Cash bandwidthOveruseCharge) {
+        this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+    }*/
+
+    @Override
+    public List<? extends Item> getChildren() {
+        return subItems;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
new file mode 100644
index 0000000..7245a2a
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.dataobjects;
+
+import org.wso2.carbon.billing.core.dataobjects.Item;
+
+public class MultitenancyPackageSubItem extends Item {
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
new file mode 100644
index 0000000..d9c5ef2
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.handlers;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingException;
+import org.wso2.carbon.billing.core.BillingHandler;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Item;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
+import org.wso2.carbon.billing.core.utilities.CustomerUtils;
+import org.wso2.carbon.billing.mgt.api.MultitenancyBillingInfo;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyCustomer;
+import org.wso2.carbon.billing.mgt.dataobjects.MultitenancyPackage;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.usage.beans.TenantUsage;
+
+import java.util.*;
+
+/**
+ * Gets subscriptions and feeds them to the Billing Engine context
+ */
+public class MultitenancySubscriptionFeedingHandler implements BillingHandler {
+    private static final Log log = LogFactory.getLog(MultitenancySubscriptionFeedingHandler.class);
+
+    private Map<Integer, MultitenancyPackage> multitenancyPackagesMap = new HashMap<Integer, MultitenancyPackage>();
+
+    public void init(Map<String, String> handlerConfig) throws BillingException {
+        DataAccessObject dataAccessObject = Util.getBillingManager().getDataAccessObject();
+        MultitenancyBillingInfo billingInfo = Util.getMultitenancyBillingInfo();
+
+        // here we are initializing the packages
+        List<MultitenancyPackage> multitenancyPackages = billingInfo.getMultitenancyPackages();
+        try {
+            dataAccessObject.beginTransaction();
+            for (MultitenancyPackage multitenancyPackage : multitenancyPackages) {
+                // check the package existence in the database; If not available, insert it
+                int itemId = dataAccessObject.getItemIdWithName(multitenancyPackage.getName());
+                if (itemId == DataAccessObject.INVALID) {
+                    itemId = dataAccessObject.addItem(multitenancyPackage);
+                }
+                multitenancyPackage.setId(itemId);
+                multitenancyPackagesMap.put(itemId, multitenancyPackage);
+                // and add all the sub items too
+                for (Item subItem : multitenancyPackage.getChildren()) {
+                    int subItemId = dataAccessObject.getItemId(subItem.getName(), itemId);
+                    if (subItemId == DataAccessObject.INVALID) {
+                        subItemId = dataAccessObject.addItem(subItem);
+                    }
+                    subItem.setId(subItemId);
+                }
+            }
+            dataAccessObject.commitTransaction();
+        }catch (Exception e){
+            dataAccessObject.rollbackTransaction();
+            log.error(e.getMessage());
+            throw new BillingException(e.getMessage(), e);
+        }
+    }
+
+    public void execute(BillingEngineContext handlerContext) throws BillingException {
+        feedSubscriptions(handlerContext);
+    }
+
+    private void feedSubscriptions(BillingEngineContext handlerContext) throws BillingException {
+        // get the subscriptions of the customer.
+        Customer customer = handlerContext.getCustomer();
+        List<Subscription> subscriptions = getSubscriptions(null, customer); //if the customer is null
+                                                                               // this will get subscriptions
+                                                                              // of all customers
+
+        //Filtering out the subscription entries of customers who has not activated their accounts
+        //This will avoid an invoice being generated for such customers
+        Date endDate = new Date();
+
+        Iterator iterator = subscriptions.iterator();
+        while(iterator.hasNext()){
+            Subscription subscription = (Subscription) iterator.next();
+            if(!subscription.isActive() && subscription.getActiveUntil().after(endDate)){
+                iterator.remove();
+            }
+        }
+
+        // prepare the handler context
+        handlerContext.setSubscriptions(subscriptions);
+        String infoMsg = "Subscription feeding phase completed. ";
+        if (subscriptions!=null){
+            infoMsg += subscriptions.size() + " subscriptions fed. ";
+        }else{
+            infoMsg += "0 subscriptions fed. ";
+        }
+        log.info(infoMsg);
+        // resetting the single customer back from the fed data
+        // this is applicable in the interim invoice scenario
+        //If this is not done, the customer object in the BillingEngine context will have
+        //a null invoice
+        if (customer != null && subscriptions != null && subscriptions.size() > 0) {
+            Subscription subscription = subscriptions.get(0);
+            handlerContext.setCustomer(subscription.getCustomer());
+        }
+    }
+
+    /**
+     *
+     * @param itemId
+     * @param isSubscriptionActive subitems for bw_overuse and storage_overuse
+     * will be added only for the active subscription
+     * @return
+     */
+    private Item getItem(int itemId, boolean isSubscriptionActive) {
+        return new MultitenancyPackage(multitenancyPackagesMap.get(itemId), isSubscriptionActive);
+    }
+
+    /**
+     * Retrieving tenant info and filling the customer object
+     * @param customerId
+     * @return
+     * @throws BillingException
+     */
+    private Customer getCustomer(int customerId) throws BillingException {
+        MultitenancyCustomer customer = new MultitenancyCustomer();
+        CustomerUtils.fillCustomerData(customerId, customer);
+        customer.setTenantId(customerId);
+
+        fillTenantUsage(customer);
+        return customer;
+    }
+
+    /**
+     * Fill usage data of the customer
+     * @param customer
+     * @throws BillingException
+     */
+    private void fillTenantUsage(MultitenancyCustomer customer) throws BillingException {
+        // first get the current month string
+        Calendar calendar = Calendar.getInstance();
+        String monthString = CommonUtil.getMonthString(calendar);
+        try {
+            int tenantId = customer.getTenantId();
+            TenantUsage usage =
+                    Util.getTenantUsageRetriever().getTenantUsage(tenantId, monthString);
+
+            long currentDataCapacity = usage.getRegistryContentCapacity();
+            long historyDataCapacity = usage.getRegistryContentHistoryCapacity();
+            customer.setCurrentStorage(currentDataCapacity);
+            customer.setHistoryStorage(historyDataCapacity);
+            customer.setTotalStorage(currentDataCapacity + historyDataCapacity);
+
+            long incomingBW = usage.getTotalIncomingBandwidth();
+            long outgoingBW = usage.getTotalOutgoingBandwidth();
+            customer.setIncomingBandwidth(incomingBW);
+            customer.setOutgoingBandwidth(outgoingBW);
+            customer.setTotalBandwidth(incomingBW + outgoingBW);
+
+            log.debug("Customer: " + customer.getTenantId() + " - Data Capacity: " + customer.getTotalStorage());
+
+            customer.setNumberOfUsers(usage.getNumberOfUsers());
+        } catch (Exception e) {
+            String msg = "Error in getting the tenant usage for customer name: " 
+                    + customer.getName() + ".";
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+    }
+
+    /**
+     * Gets subscriptions of customer(s)
+     * @param filter currently there is a filter "multitenancy" defined in the billing-config.xml
+     * This will be removed in the future trunk
+     * @param customer if the customer is null it gets subscriptions of all customers
+     * @return
+     * @throws BillingException
+     */
+    private List<Subscription> getSubscriptions(String filter,
+                                                Customer customer)throws BillingException {
+        DataAccessObject dataAccessObject = Util.getBillingManager().getDataAccessObject();
+        List<Subscription> subscriptions = null;
+        Map<Integer, Customer> customersCash = new HashMap<Integer, Customer>();
+        try {
+            dataAccessObject.beginTransaction();
+            if (customer == null) {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptions(filter);
+            } else {
+                subscriptions = dataAccessObject.getFilteredActiveSubscriptionsForCustomer(filter, customer);
+            }
+            if(subscriptions!=null && subscriptions.size()>0){
+                for (Subscription subscription : subscriptions) {
+                    Customer dummyCustomer = subscription.getCustomer();
+                    int customerId = dummyCustomer.getId();
+                    Customer correctCustomer = customersCash.get(customerId);
+                    if (correctCustomer == null) {
+                        correctCustomer = getCustomer(customerId);
+                        customersCash.put(customerId, correctCustomer);
+                    }
+                    subscription.setCustomer(correctCustomer);
+
+                    Item dummyItem = subscription.getItem();
+                    Item correctItem = getItem(dummyItem.getId(), subscription.isActive());
+                    subscription.setItem(correctItem);
+                }
+            }
+            dataAccessObject.commitTransaction();
+        }catch (Exception e){
+            dataAccessObject.rollbackTransaction();
+            String msg = "Error occurred while getting subscriptions";
+            if(customer != null) {
+                msg = msg + " for customer: " + customer.getName();
+            }
+            log.error(msg);
+            throw new BillingException(msg, e);
+        }
+        return subscriptions;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
new file mode 100644
index 0000000..d30e3f9
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
@@ -0,0 +1,109 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.usage.api.TenantUsageRetriever;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+/**
+ * @scr.component name="org.wso2.carbon.billing.mgt"
+ * immediate="true"
+ * @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="user.realmservice.default"
+ * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1"
+ * policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
+ * @scr.reference name="billingManager.service"
+ * interface="org.wso2.carbon.billing.core.BillingManager" cardinality="1..1"
+ * policy="dynamic" bind="setBillingManager" unbind="unsetBillingManager"
+ * @scr.reference name="tenant.usage.retriever.service"
+ * interface="org.wso2.carbon.usage.api.TenantUsageRetriever" cardinality="1..1"
+ * policy="dynamic" bind="setTenantUsageRetriever" unbind="unsetTenantUsageRetriever"
+ */
+public class MultitenancyBillingServiceComponent {
+    private static Log log = LogFactory.getLog(MultitenancyBillingServiceComponent.class);
+    private static ConfigurationContextService contextService;
+
+    protected void activate(ComponentContext context) {
+        try {
+            Util.registerSubscriptionFeedingHandlers(context.getBundleContext());
+            Util.scheduleBilling();
+            Util.registerBillingInfo(context.getBundleContext());
+            Util.initDataAccessManager();
+            Util.initializeThrottling(context.getBundleContext());
+            Util.registerTenantBillingService(context.getBundleContext());
+            log.debug("******* Multitenancy Billing bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Multitenancy Billing bundle failed activating ****", e);
+        }
+    }
+
+    @SuppressWarnings("unused")
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Multitenancy Billing is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        Util.setRegistryService(registryService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRegistryService(RegistryService registryService) {
+        Util.setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        Util.setRealmService(realmService);
+    }
+
+    @SuppressWarnings("unused")
+    protected void unsetRealmService(RealmService realmService) {
+        Util.setRealmService(null);
+    }
+
+    public void setBillingManager(BillingManager billingManager) {
+        log.debug("Receiving billingManager service");
+        Util.setBillingManager(billingManager);
+    }
+
+    @SuppressWarnings("unused")
+    public void unsetBillingManager(BillingManager billingManager) {
+        log.debug("Unsetting billingManager service");
+        Util.setBillingManager(null);
+    }
+
+    public void setTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        log.debug("Setting Tenant Usage Retriever service");
+        Util.setTenantUsageRetriever(tenantUsageRetriever);
+    }
+
+    @SuppressWarnings("unused")
+    public void unsetTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+        log.debug("Unsetting Tenant Usage Retriever service");
+        Util.setBillingManager(null);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
new file mode 100644
index 0000000..0298c4d
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.mgt.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.DataAccessManager;
+import org.wso2.carbon.billing.core.dataobjects.Customer;
+import org.wso2.carbon.billing.core.dataobjects.Subscription;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+import java.util.List;
+
+/**
+ * This service allows other components to access billing related data
+ * without going through a billing manager
+ */
+public class BillingDataAccessService extends AbstractAdmin {
+    private static Log log = LogFactory.getLog(BillingDataAccessService.class);
+
+    /**
+     * Add a new subscription to the BC_SUBSCRIPTION table
+     * @param subscription  object with subscription info
+     * @return the subscription id of the added subscription
+     * @throws Exception Exception
+     */
+    public int addSubscription(Subscription subscription) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.addSubscription(subscription);
+    }
+
+    /**
+     * Delete a particular tenants subscription and all related data
+     * @param tenantId id of the tenant whose billing details should be deleted
+     * @throws Exception thorwn if an error is occured while deleting data
+     */
+    public void deleteBillingData(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        dataAccessManager.deleteBillingData(tenantId);
+    }
+
+    /**
+     * Finds the customer with a given tenant domain
+     * @param customerName  is the tenant domain
+     * @return  a customer object
+     * @throws Exception Exception
+     */
+    public Customer getCustomerWithName(String customerName) throws Exception {
+
+        //This is invoked by tenants only. Therefore securing this by checking 
+        //whether the string passed is actually the domain of current tenant
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int currentTenantId = userRegistry.getTenantId();
+
+        TenantManager tenantManager = Util.getRealmService().getTenantManager();
+        String currentTenantDomain = tenantManager.getDomain(currentTenantId);
+
+        if(!customerName.equals(currentTenantDomain)){
+            String msg = "Tenant: " + currentTenantDomain + " is trying to get customer object of tenant: " +
+                    customerName + ".";
+            log.error(msg);
+            throw new Exception(msg);
+        }
+
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        Customer customer = null;
+        List<Customer> customers = dataAccessManager.getCustomersWithName(customerName);
+        if (customers.size() > 0) {
+            customer = customers.get(0);
+        }
+        return customer;
+    }
+
+    /**
+     * Get a subscription with a given id
+     * @param subscriptionId subscription id
+     * @return a subscription object
+     * @throws Exception Exception
+     */
+    public Subscription getSubscription(int subscriptionId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getSubscription(subscriptionId);
+    }
+
+
+    /**
+     * Method called by super-tenant to get the active subscription of a tenant
+     * @param tenantId Tenant Id
+     * @return subscription details
+     * @throws Exception Exception
+     */
+    public Subscription getActiveSubscriptionOfCustomerBySuperTenant(int tenantId) throws Exception{
+        return getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+    /**
+     * Method called by tenant to get the active subscription
+     * @return subscription details
+     * @throws Exception Exception
+     */
+    public Subscription getActiveSubscriptionOfCustomerByTenant() throws Exception{
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int tenantId = userRegistry.getTenantId();
+
+        return getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+
+    /**
+     * Gets the item id for a given item name and a parent id
+     * For example "subscription" item id of Demo subscription
+     * @param name  e.g. "subscription", "bwOveruse", "storageOveruse"
+     * @param parentId there is a parent item in BC_ITEM
+     * @return  the item id from the BC_ITEM table
+     * @throws Exception Exception
+     */
+    public int getItemIdWithName(String name, int parentId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getItemIdWithName(name, parentId);
+    }
+
+    /**
+     * This is used by the tenants 
+     * @param subscriptionPlan new Usage plan name that user expect to go
+     * @return whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionByTenant(String subscriptionPlan) throws Exception {
+
+        UserRegistry userRegistry = (UserRegistry) getGovernanceUserRegistry();
+        int tenantId = userRegistry.getTenantId();
+
+        return changeSubscription(tenantId, subscriptionPlan);
+
+    }
+
+    /**
+     * This is used by the super tenant
+     * @param customerId    this is the tenant id
+     * @param subscriptionPlan  new usage plan name
+     * @return  whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionBySuperTenant(int customerId, String subscriptionPlan) throws Exception {
+
+        return changeSubscription(customerId, subscriptionPlan);
+    }
+
+    /**
+     * Gets the inactive subscriptions of a customer ordered by ACTIVE_SINCE time
+     * in the descending order (i.e. latest ones first)
+     * @param customerId this is the tenant id
+     * @return  an array of subscriptions
+     * @throws Exception Exception
+     */
+    public Subscription[] getInactiveSubscriptionsOfCustomer(int customerId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        List<Subscription> subscriptions = dataAccessManager.getInactiveSubscriptionsOfCustomer(customerId);
+        Subscription[] subscriptionArray;
+        if (subscriptions != null && subscriptions.size() > 0) {
+            subscriptionArray = subscriptions.toArray(new Subscription[subscriptions.size()]);
+        } else {
+            subscriptionArray = new Subscription[0];
+        }
+        return subscriptionArray;
+    }
+
+    /**
+     * Activate a subscription with a given id
+     * @param subscriptionId is the id of subscription which needs to be activated
+     * @return  true or false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean activateSubscription(int subscriptionId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.activateSubscription(subscriptionId);
+    }
+
+    /**
+     * Method called by tenants when deactivating the active subscriptions
+     * @return true | false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean deactivateActiveSubscriptionByTenant() throws Exception{
+        UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+        int currentTenantId = registry.getTenantId();
+
+        return deactivateActiveSubscription(currentTenantId);
+    }
+
+
+    /**
+     * Method called by super-tenant
+     * @param tenantId Tenant Id
+     * @return true | false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean deactivateActiveSubscriptionBySuperTenant(int tenantId) throws Exception{
+        return deactivateActiveSubscription(tenantId);
+    }
+    
+
+
+    /**
+     * This is the private method called by tenant or super tenant operations when
+     * changing(updating) the subscription plan
+     * @param tenantId Tenant ID
+     * @param subscriptionPlan new usage plan (subscription plan) name
+     * @return true or false based on whether the operation was successful
+     * @throws Exception Exception
+     */
+    private boolean changeSubscription(int tenantId, String subscriptionPlan) throws Exception {
+
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        if (dataAccessManager.changeSubscription(tenantId, subscriptionPlan)) {
+            try {
+                Util.executeThrottlingRules(tenantId);
+            }
+            catch (Exception e) {
+                log.error("Error occurred executing throttling rules after updating the subscription " +
+                        "to " + subscriptionPlan + ". " + e.toString());
+            }
+            //send mail
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Gets the active subscription of a customer. There can be only one active
+     * subscription for a customer at a given time
+     * @param tenantId Tenant Id
+     * @return  a subscription object
+     * @throws Exception Exception
+     */
+    private Subscription getActiveSubscriptionOfCustomer(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.getActiveSubscriptionOfCustomer(tenantId);
+    }
+
+    /**
+     * Deactivates the active subscription of a customer
+     * @param tenantId is the customer id (both have the same meaning)
+     * @return true or false based on whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    private boolean deactivateActiveSubscription(int tenantId) throws Exception {
+        DataAccessManager dataAccessManager = Util.getDataAccessManager();
+        return dataAccessManager.deactivateActiveSubscription(tenantId);
+    }
+
+    /**
+     * This method is used to update the usage plan when updating the from Demo to a paying plan
+     * @param subscriptionPlan new Usage plan name that user expect to go
+     * @param tenantDomain the domain of the tenant that should be updated 
+     * @return whether the operation was successful or not
+     * @throws Exception Exception
+     */
+    public boolean changeSubscriptionForTenant(String subscriptionPlan, String tenantDomain) throws Exception {
+        int tenantId = Util.getRealmService().getTenantManager().getTenantId(tenantDomain);
+        return changeSubscription(tenantId, subscriptionPlan);
+    }
+
+}


[35/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/pom.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/pom.xml
new file mode 100644
index 0000000..03111eb
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/pom.xml
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~      http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+-->
+<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.wso2.carbon</groupId>
+        <artifactId>adc-mgt</artifactId>
+        <version>2.1.0</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.adc.topology.mgt</artifactId>
+    <packaging>bundle</packaging>
+    <version>2.1.3</version>
+    <name>WSO2 Carbon - Topology Management</name>
+    <url>http://wso2.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>
+        </dependency>
+         <!--dependency>
+            <groupId>org.apache.axis2.wso2</groupId>
+            <artifactId>axis2</artifactId>
+            <version>1.6.1.wso2v9</version>
+        </dependency-->
+        <dependency>
+            <groupId>org.apache.axis2</groupId>
+            <artifactId>axis2-kernel</artifactId>
+            <version>1.6.1-wso2v9</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.utils</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.core</artifactId>
+            <version>4.1.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.lb.common</artifactId>
+            <version>4.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ntask.core</artifactId>
+        </dependency>
+        <dependency>
+                <groupId>org.wso2.andes.wso2</groupId>
+                <artifactId>andes-client</artifactId>
+                <version>0.13.wso2v3</version>
+            </dependency>
+        <dependency>
+                <groupId>org.apache.geronimo.specs.wso2</groupId>
+                <artifactId>geronimo-jms_1.1_spec</artifactId>
+                <version>${orbit.version.geronimo-jms_1.1_spec}</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>
+                        <!-- <Private-Package>
+                        	org.wso2.carbon.stratos.topology.mgt.service.impl.*
+                        </Private-Package> -->
+                        <Export-Package>
+                            org.wso2.carbon.adc.topology.mgt.subscriber.*,
+                            org.wso2.carbon.adc.topology.mgt.service.*,
+                            org.wso2.carbon.adc.topology.mgt.group.mgt.*,
+							org.wso2.carbon.adc.topology.mgt.serviceobjects.*
+                        </Export-Package>
+                        <Import-Package>
+                            org.wso2.carbon.lb.common.*; version=4.1.1,
+                            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/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/builder/TopologySyncher.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/builder/TopologySyncher.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/builder/TopologySyncher.java
new file mode 100644
index 0000000..bcbb808
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/builder/TopologySyncher.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.builder;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.conf.structure.Node;
+import org.wso2.carbon.lb.common.conf.structure.NodeBuilder;
+import org.wso2.carbon.adc.topology.mgt.group.mgt.GroupMgtAgentBuilder;
+import org.wso2.carbon.adc.topology.mgt.util.ConfigHolder;
+
+
+public class TopologySyncher implements Runnable {
+
+	@SuppressWarnings("rawtypes")
+    private BlockingQueue sharedQueue;
+	private static final Log log = LogFactory.getLog(TopologySyncher.class);
+	
+	public TopologySyncher(@SuppressWarnings("rawtypes") BlockingQueue queue){
+		
+		sharedQueue = queue;
+		
+	}
+	
+	public void run() {
+
+	    LoadBalancerConfiguration lbconfig = LoadBalancerConfiguration.getInstance();
+	    
+	    //FIXME Currently there has to be at least one dummy cluster defined in the loadbalancer conf
+	    // in order to proper initialization of TribesClusteringAgent.
+	    generateGroupMgtAgents(lbconfig);
+	    
+        while (true) {
+            try {
+
+                Object obj;
+                String msg = null;
+
+                obj = sharedQueue.take();
+                msg = (String) obj;
+
+                ConfigHolder data = ConfigHolder.getInstance();
+
+                Node topologyNode = NodeBuilder.buildNode(msg);
+
+                List<ServiceConfiguration> currentServiceConfigs = lbconfig.createServicesConfig(topologyNode);
+
+                data.setServiceConfigs(lbconfig.getServiceNameToServiceConfigurations());
+                generateGroupMgtAgents(lbconfig);
+                resetGroupMgtAgents(lbconfig, currentServiceConfigs);
+
+            } catch (InterruptedException ignore) {
+            }
+        }
+
+	}
+
+    /**
+     * @param lbconfig
+     */
+    private void generateGroupMgtAgents(LoadBalancerConfiguration lbconfig) {
+        for (List<ServiceConfiguration> serviceConfigsList : lbconfig.getServiceNameToServiceConfigurations()
+                                                                     .values()) {
+
+        	for (ServiceConfiguration serviceConfiguration : serviceConfigsList) {
+        		GroupMgtAgentBuilder.createGroupMgtAgent(serviceConfiguration.getDomain(),
+        		                                         serviceConfiguration.getSubDomain());
+        	}
+        }
+    }
+    
+    private void resetGroupMgtAgents(LoadBalancerConfiguration lbConfig,
+        List<ServiceConfiguration> currentServiceConfigs) {
+
+        for (Iterator<?> iterator = lbConfig.getServiceConfigurations().values().iterator(); iterator.hasNext();) {
+            @SuppressWarnings("unchecked")
+            Map<String, ServiceConfiguration> valuesMap = (Map<String, ServiceConfiguration>) iterator.next();
+
+            for (Iterator<ServiceConfiguration> iterator2 = valuesMap.values().iterator(); iterator2.hasNext();) {
+                ServiceConfiguration oldServiceConfig = (ServiceConfiguration) iterator2.next();
+
+                if (!currentServiceConfigs.contains(oldServiceConfig)) {
+                    // if the ServiceConfiguration is not there any more in the latest topology
+                    lbConfig.removeServiceConfiguration(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                    GroupMgtAgentBuilder.resetGroupMgtAgent(oldServiceConfig.getDomain(), oldServiceConfig.getSubDomain());
+                }
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/exception/TopologyMgtException.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/exception/TopologyMgtException.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/exception/TopologyMgtException.java
new file mode 100644
index 0000000..1092d0b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/exception/TopologyMgtException.java
@@ -0,0 +1,35 @@
+/**
+ * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.exception;
+
+public class TopologyMgtException extends RuntimeException {
+
+    private static final long serialVersionUID = -663839410798538370L;
+
+    public TopologyMgtException(String msg) {
+        super(msg);
+    }
+
+    public TopologyMgtException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+    public TopologyMgtException(Throwable cause) {
+        super(cause);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
new file mode 100644
index 0000000..83c4043
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/GroupMgtAgentBuilder.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.group.mgt;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.axis2.clustering.ClusteringAgent;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.synapse.SynapseException;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.util.HostContext;
+import org.wso2.carbon.lb.common.conf.util.TenantDomainContext;
+import org.wso2.carbon.adc.topology.mgt.util.ConfigHolder;
+
+public class GroupMgtAgentBuilder {
+
+	private static LoadBalancerConfiguration lbConfig;
+	/**
+     * Key - host name 
+     * Value - {@link HostContext}
+     */
+    private static Map<String, HostContext> hostContexts = new HashMap<String, HostContext>();
+    
+    private static final Log log = LogFactory.getLog(GroupMgtAgentBuilder.class);
+	
+	public static void createGroupMgtAgents() {
+		lbConfig = ConfigHolder.getInstance().getLbConfig();
+		hostContexts = lbConfig.getHostContextMap();
+		
+		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+        }
+
+        // Add the Axis2 GroupManagement agents
+        if (hostContexts != null) {
+            // iterate through each host context
+            for (HostContext hostCtxt : hostContexts.values()) {
+                // each host can has multiple Tenant Contexts, iterate through them
+                for (TenantDomainContext tenantCtxt : hostCtxt.getTenantDomainContexts()) {
+
+                    String domain = tenantCtxt.getDomain();
+                    String subDomain = tenantCtxt.getSubDomain();
+
+                    if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+                        clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                            subDomain),
+                            domain, subDomain, -1);
+                        log.info("Group management agent added to cluster domain: " +
+                            domain + " and sub domain: " + subDomain);
+                    }
+                }
+            }
+        }
+    }
+	
+	public static void createGroupMgtAgent(String domain, String subDomain) {
+		
+		ClusteringAgent clusteringAgent = ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 ClusteringAgent not defined in axis2.xml");
+        }
+		
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) == null) {
+            clusteringAgent.addGroupManagementAgent(new SubDomainAwareGroupManagementAgent(
+                subDomain),
+                domain, subDomain, -1);
+            log.info("Group management agent added to cluster domain: " +
+                domain + " and sub domain: " + subDomain);
+        }
+	}
+	
+	public static void resetGroupMgtAgent(String domain, String subDomain) {
+
+        ClusteringAgent clusteringAgent =
+            ConfigHolder.getInstance().getAxisConfiguration().getClusteringAgent();
+        
+        if (clusteringAgent == null) {
+            throw new SynapseException("Axis2 Clustering Agent not defined in axis2.xml");
+        }
+
+        // checks the existence. 
+        if (clusteringAgent.getGroupManagementAgent(domain, subDomain) != null) {
+            
+            clusteringAgent.resetGroupManagementAgent(domain, subDomain);
+            
+            log.info("Group management agent of cluster domain: " +
+                domain + " and sub domain: " + subDomain+" is removed.");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
new file mode 100644
index 0000000..2ad4a12
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/group/mgt/SubDomainAwareGroupManagementAgent.java
@@ -0,0 +1,32 @@
+package org.wso2.carbon.adc.topology.mgt.group.mgt;
+
+import org.apache.axis2.clustering.Member;
+import org.apache.axis2.clustering.management.DefaultGroupManagementAgent;
+
+/**
+ * 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 || subDomain.equals(this.subDomain)) {
+            super.applicationMemberAdded(member);
+        }
+    }
+
+    @Override
+    public void applicationMemberRemoved(Member member) {
+        String subDomain = member.getProperties().getProperty("subDomain");
+        if (subDomain == null || subDomain.equals(this.subDomain)) {
+            super.applicationMemberRemoved(member);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/internal/TopologyMgtDSComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/internal/TopologyMgtDSComponent.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/internal/TopologyMgtDSComponent.java
new file mode 100644
index 0000000..e5445e2
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/internal/TopologyMgtDSComponent.java
@@ -0,0 +1,290 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.adc.topology.mgt.builder.TopologySyncher;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.adc.topology.mgt.service.impl.TopologyManagementServiceImpl;
+import org.wso2.carbon.adc.topology.mgt.subscriber.TopologySubscriber;
+import org.wso2.carbon.adc.topology.mgt.util.TopologyConstants;
+import org.wso2.carbon.adc.topology.mgt.util.ConfigHolder;
+import org.wso2.carbon.utils.ConfigurationContextService;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.ntask.core.service.TaskService;
+
+//* @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="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="user.realmservice.default"
+//* interface="org.wso2.carbon.user.core.service.RealmService"
+//* cardinality="1..1" policy="dynamic" bind="setRealmService"
+//* unbind="unsetRealmService"
+
+/**
+ * @scr.component name="topology.mgt.service" 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="org.wso2.carbon.lb.common"
+ * interface="org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService"
+ * cardinality="1..1" policy="dynamic" bind="setLoadBalancerConfigurationService"
+ * unbind="unsetLoadBalancerConfigurationService"
+ * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
+ * cardinality="1..1" policy="dynamic" bind="setTaskService" unbind="unsetTaskService"
+ */
+@SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
+public class TopologyMgtDSComponent {
+
+    private static final Log log = LogFactory.getLog(TopologyMgtDSComponent.class);
+
+//    private boolean activated = false;
+
+    protected void activate(ComponentContext ctxt) {
+    	try {
+    		// start consumer
+    		// initialize TopologyBuilder Consumer
+            if (System.getProperty("mb.server.ip") != null) {
+                Thread topologyConsumer = new Thread(new TopologySyncher(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+                // start consumer
+                topologyConsumer.start();
+
+                TopologySubscriber.subscribe(TopologyConstants.TOPIC_NAME);
+            }
+
+    		
+            BundleContext bundleContext = ctxt.getBundleContext();
+            bundleContext.registerService(TopologyManagementService.class.getName(),
+                                          new TopologyManagementServiceImpl(), null);
+
+            log.debug("******* Topology Mgt Service bundle is activated ******* ");
+        } catch (Throwable e) {
+            log.error("******* Topology Mgt Service Service bundle is failed to activate ****", e);
+        }
+//    	log.info("**************************************");
+//    	for (String str : ConfigHolder.getInstance().getLbConfig().getServiceDomains()) {
+//	        log.info(str);
+//        }
+//    	log.info("**************************************");
+    	
+//    	if(!activated){
+//    		GroupMgtAgentBuilder.createGroupMgtAgents();
+//    		activated = true;
+//    	}
+    	
+    	
+    	// topology synching task activation
+//    	TaskManager tm = null;
+//		try {
+//			// topology sync
+//			ConfigHolder.getInstance().getTaskService()
+//			          .registerTaskType(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
+//
+//			tm =
+//					ConfigHolder.getInstance().getTaskService()
+//			               .getTaskManager(TopologyConstants.TOPOLOGY_SYNC_TASK_TYPE);
+//
+//			TriggerInfo triggerInfo = new TriggerInfo(TopologyConstants.TOPOLOGY_SYNC_CRON);
+//			TaskInfo taskInfo =
+//			                    new TaskInfo(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME,
+//			                                 TopologySubscriberTask.class.getName(),
+//			                                 new HashMap<String, String>(), triggerInfo);
+//			tm.registerTask(taskInfo);
+//
+//			// start consumer
+//			// initialize TopologyBuilder Consumer
+//	        Thread topologyConsumer = new Thread(new TopologyBuilder(ConfigHolder.getInstance().getSharedTopologyDiffQueue()));
+//	        // start consumer
+//	        topologyConsumer.start();
+//			
+//		} catch (Exception e) {
+//			String msg = "Error scheduling task: " + TopologyConstants.TOPOLOGY_SYNC_TASK_NAME;
+//			log.error(msg, e);
+//			if (tm != null) {
+//				try {
+//					tm.deleteTask(TopologyConstants.TOPOLOGY_SYNC_TASK_NAME);
+//				} catch (TaskException e1) {
+//					log.error(e1);
+//				}
+//			}
+//			throw new TopologyMgtException(msg, e);
+//		}
+    }
+
+    protected void deactivate(ComponentContext context) {}
+
+    protected void setConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(
+                cfgCtxService.getServerConfigContext().getAxisConfiguration());
+    }
+
+    protected void unsetConfigurationContextService(ConfigurationContextService cfgCtxService) {
+        ConfigHolder.getInstance().setAxisConfiguration(null);
+    }
+
+//    protected void setSynapseConfigurationService(
+//            SynapseConfigurationService synapseConfigurationService) {
+//
+//        ConfigHolder.getInstance().setSynapseConfiguration(
+//                synapseConfigurationService.getSynapseConfiguration());
+//    }
+//
+//    protected void unsetSynapseConfigurationService(
+//            SynapseConfigurationService synapseConfigurationService) {
+//
+//        ConfigHolder.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 = ConfigHolder.getInstance().getSynapseEnvironmentServices().
+//                containsKey(synapseEnvironmentService.getTenantId());
+//
+//        ConfigHolder.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) {
+//        ConfigHolder.getInstance().removeSynapseEnvironmentService(
+//                synapseEnvironmentService.getTenantId());
+//    }
+//
+//    protected void setRegistryService(RegistryService regService) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("RegistryService bound to the endpoint component");
+//        }
+//        try {
+//            ConfigHolder.getInstance().setConfigRegistry(regService.getConfigSystemRegistry());
+//            ConfigHolder.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");
+//        }
+//        ConfigHolder.getInstance().setConfigRegistry(null);
+//    }
+//
+//    protected void setDependencyManager(DependencyManagementService dependencyMgr) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("Dependency management service bound to the endpoint component");
+//        }
+//        ConfigHolder.getInstance().setDependencyManager(dependencyMgr);
+//    }
+//
+//    protected void unsetDependencyManager(DependencyManagementService dependencyMgr) {
+//        if (log.isDebugEnabled()) {
+//            log.debug("Dependency management service unbound from the endpoint component");
+//        }
+//        ConfigHolder.getInstance().setDependencyManager(null);
+//    }
+//
+//    protected void setSynapseRegistrationsService(
+//            SynapseRegistrationsService synapseRegistrationsService) {
+//
+//    }
+
+//    protected void unsetSynapseRegistrationsService(
+//            SynapseRegistrationsService synapseRegistrationsService) {
+//        int tenantId = synapseRegistrationsService.getTenantId();
+//        if (ConfigHolder.getInstance().getSynapseEnvironmentServices().containsKey(tenantId)) {
+//            SynapseEnvironment env = ConfigHolder.getInstance().
+//                    getSynapseEnvironmentService(tenantId).getSynapseEnvironment();
+//
+//            ConfigHolder.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) {
+//        ConfigHolder.getInstance().setRealmService(realmService);
+//    }
+//
+//    protected void unsetRealmService(RealmService realmService) {
+//        ConfigHolder.getInstance().setRealmService(null);
+//    }
+//    
+    protected void setLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(lbConfigSer);
+    }
+    
+    protected void unsetLoadBalancerConfigurationService(LoadBalancerConfigurationService lbConfigSer){
+        ConfigHolder.getInstance().setLbConfigService(null);
+    }
+    
+    protected void setTaskService(TaskService taskService) {
+        ConfigHolder.getInstance().setTaskService(taskService);
+    }
+
+    protected void unsetTaskService(TaskService taskService) {
+        ConfigHolder.getInstance().setTaskService(null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/TopologyManagementService.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/TopologyManagementService.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/TopologyManagementService.java
new file mode 100644
index 0000000..400a38a
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/TopologyManagementService.java
@@ -0,0 +1,69 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.service;
+
+import org.wso2.carbon.adc.topology.mgt.serviceobjects.DomainContext;
+
+/**
+ * This exposes details regarding up-to-date topology
+ *
+ */
+public interface TopologyManagementService {
+
+	/**
+	 * Provide service cluster domains corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return String array of service cluster domains
+	 */
+	String[] getDomains(String cartridgeType, int tenantId);
+
+	/**
+	 * Provide service cluster sub domains corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return String array of service cluster sub domains
+	 */
+	String[] getSubDomains(String cartridgeType, int tenantId);
+
+//	/**
+//	 * Provide public IPs corresponds to the given information.
+//	 * @param cartridgeType cartridge type
+//	 * @param tenantId tenant id
+//	 * @return String array of public IPs
+//	 */
+//	String[] getActiveIPs(String cartridgeType, int tenantId);
+	
+	/**
+	 * Provide public IPs corresponds to the given information.
+	 * @param cartridgeType cartridge type
+	 * @param domain service cluster domain
+	 * @param subDomain service cluster sub domain
+	 * @return String array of public IPs
+	 */
+	String[] getActiveIPs(String cartridgeType, String domain, String subDomain);
+	
+	/**
+	 * Provide domains and the relevant subdomains corresponding to the given information
+	 * 
+	 * @param cartridgeType cartridge type
+	 * @param tenantId tenant id
+	 * @return DomainContext instances array of domains and sub domains 
+	 */
+	DomainContext[] getDomainsAndSubdomains (String cartridgeType, int tenantId);
+	
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
new file mode 100644
index 0000000..b2374fa
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/service/impl/TopologyManagementServiceImpl.java
@@ -0,0 +1,126 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.service.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.conf.util.LoadBalancerConfigUtil;
+import org.wso2.carbon.adc.topology.mgt.service.TopologyManagementService;
+import org.wso2.carbon.adc.topology.mgt.serviceobjects.DomainContext;
+import org.wso2.carbon.adc.topology.mgt.util.ConfigHolder;
+
+public class TopologyManagementServiceImpl implements TopologyManagementService {
+	
+	ConfigHolder data = ConfigHolder.getInstance();
+
+	public String[] getDomains(String cartridgeType, int tenantId) {
+		List<String> domains = new ArrayList<String>();
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						if (!domains.contains(serviceConfiguration.getDomain())) {
+							domains.add(serviceConfiguration.getDomain());
+						}
+					}
+                }
+			}
+		}
+		return domains.toArray(new String[domains.size()]);
+	}
+
+	public String[] getSubDomains(String cartridgeType, int tenantId) {
+		List<String> subDomains = new ArrayList<String>();
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						if (!subDomains.contains(serviceConfiguration.getSubDomain())) {
+							subDomains.add(serviceConfiguration.getSubDomain());
+						}
+					}
+                }
+			}
+		}
+		return subDomains.toArray(new String[subDomains.size()]);
+	}
+
+    public String[] getActiveIPs(String cartridgeType, String domain, String subDomain) {
+		List<String> publicIps = new ArrayList<String>();
+		
+		if(domain == null || subDomain == null){
+			return new String[0];
+		}
+		
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					if(domain.equals(serviceConfiguration.getDomain()) && subDomain.equals(serviceConfiguration.getSubDomain())){
+						
+						String ipStr = serviceConfiguration.getPublicIp();
+						if(ipStr != null && !ipStr.isEmpty()){
+							for (String ip : ipStr.split(",")) {
+								if (!publicIps.contains(ip)) {
+									publicIps.add(ip);
+								}
+							}
+						}
+					}
+                }
+			}
+		}
+		return publicIps.toArray(new String[publicIps.size()]);
+	}
+
+	/* (non-Javadoc)
+	 * @see org.wso2.carbon.stratos.topology.mgt.service.TopologyManagementService#getDomainsAndSubdomains(java.lang.String, int)
+	 */
+	public DomainContext[] getDomainsAndSubdomains(String cartridgeType, int tenantId) {
+		List<DomainContext> domainContexts = new ArrayList<DomainContext>();
+		
+		if(data.getServiceConfigs() != null){
+			List<ServiceConfiguration> serviceConfigs = data.getServiceConfigs().get(cartridgeType);
+			if(serviceConfigs != null){
+				
+				for (ServiceConfiguration serviceConfiguration : serviceConfigs) {
+	                
+					List<Integer> tenantIds = LoadBalancerConfigUtil.getTenantIds(serviceConfiguration.getTenantRange());
+					if(!tenantIds.isEmpty() && (tenantIds.contains(tenantId) || tenantIds.contains(0))){
+						DomainContext domainCtx = new DomainContext(serviceConfiguration.getDomain(), serviceConfiguration.getSubDomain());
+						if (!domainContexts.contains(domainCtx)) {
+							domainContexts.add(domainCtx);
+						}
+					}
+                }
+			}
+		}
+		return domainContexts.toArray(new DomainContext[domainContexts.size()]);
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/serviceobjects/DomainContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/serviceobjects/DomainContext.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/serviceobjects/DomainContext.java
new file mode 100644
index 0000000..9ffac9f
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/serviceobjects/DomainContext.java
@@ -0,0 +1,90 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.wso2.carbon.adc.topology.mgt.serviceobjects;
+
+/**
+ * Class to hold domain and subdomain details
+ *
+ */
+public class DomainContext {
+    
+    private String domain;
+    private String subDomain;
+    
+    /**
+     * Constructor
+     * 
+     * @param domain domain name
+     * @param subDomain subdomain name
+     */
+    public DomainContext (String domain, String subDomain) {
+        this.domain = domain;
+        this.subDomain = subDomain;
+    }
+
+    /**
+     * Returns the domain 
+     * 
+     * @return the domain
+     */
+    public String getDomain() {
+        return domain;
+    }
+
+    /**
+     * Returns the sub domain
+     * 
+     * @return the subDomain
+     */
+    public String getSubDomain() {
+        return subDomain;
+    }
+    
+    /**
+     * Overridden equals method
+     */
+    public boolean equals (Object object) {
+        if (object == null) 
+            return false;
+        if (object == this)  
+            return true;
+        if (!(object instanceof DomainContext))
+            return false;
+        
+        DomainContext domainCtx = (DomainContext)object;
+        if(this.getDomain().equals(domainCtx.getDomain()) &&
+                this.getSubDomain().equals(domainCtx.getSubDomain()))
+            return true;
+        else
+            return false;
+    }
+    
+    /**
+     * Overridden hashCode method
+     */
+    public int hashCode () {
+        int domainHash = 0;
+        int subDomainHash = 0;
+        
+        if(domain != null)
+            domainHash = domain.hashCode();
+        if(subDomain != null)
+            subDomainHash = subDomain.hashCode();
+        
+        return domainHash + subDomainHash;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopicHealthChecker.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopicHealthChecker.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopicHealthChecker.java
new file mode 100644
index 0000000..0ca9de2
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopicHealthChecker.java
@@ -0,0 +1,67 @@
+/*
+*  Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.adc.topology.mgt.subscriber;
+
+import javax.jms.TopicSubscriber;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * This health checker runs forever, and is responsible for re-establishing a connection
+ * between SC and CC.
+ */
+public class TopicHealthChecker implements Runnable{
+    
+    private static final Log log = LogFactory.getLog(TopicHealthChecker.class);
+    private String topicName;
+    private TopicSubscriber subscriber;
+
+    public TopicHealthChecker(String topicName, TopicSubscriber subscriber) {
+        this.topicName = topicName;
+        this.subscriber = subscriber;
+    }
+    
+    @Override
+    public void run() {
+        log.info("Topic Health Checker is running... ");
+
+        while (true) {
+            try {
+                subscriber.getTopic();
+                
+                // health checker runs in every 30s
+                Thread.sleep(30000);
+
+            } 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) {
+                }
+            }
+
+        }
+
+        TopologySubscriber.subscribe(topicName);
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologyListener.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologyListener.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologyListener.java
new file mode 100644
index 0000000..685cc22
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologyListener.java
@@ -0,0 +1,44 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.subscriber;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.TextMessage;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.topology.mgt.util.ConfigHolder;
+
+public class TopologyListener implements MessageListener {
+
+    private static final Log log = LogFactory.getLog(TopologyListener.class);
+
+    @SuppressWarnings("unchecked")
+    public void onMessage(Message message) {
+        TextMessage receivedMessage = (TextMessage) message;
+        try {
+
+            ConfigHolder.getInstance().getSharedTopologyDiffQueue().add(receivedMessage.getText());
+
+        } catch (JMSException e) {
+            log.error(e.getMessage(), e);
+        }
+
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriber.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriber.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriber.java
new file mode 100644
index 0000000..c5ae407
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriber.java
@@ -0,0 +1,92 @@
+/*
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.subscriber;
+
+import java.util.Properties;
+
+import javax.jms.*;
+import javax.naming.InitialContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.adc.topology.mgt.util.TopologyConstants;
+
+public class TopologySubscriber {
+
+	private static final Log log = LogFactory.getLog(TopologySubscriber.class);
+	
+    public static void subscribe(String topicName) {
+        Properties initialContextProperties = new Properties();
+        TopicSubscriber topicSubscriber = null;
+        TopicSession topicSession = null;
+        TopicConnection topicConnection = null;
+        InitialContext initialContext = null;
+
+        initialContextProperties.put("java.naming.factory.initial",
+            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");
+
+        String mbServerIp =
+            System.getProperty(TopologyConstants.MB_SERVER_IP) == null
+                ? TopologyConstants.DEFAULT_MB_SERVER_IP
+                : System.getProperty(TopologyConstants.MB_SERVER_IP);
+
+        String connectionString =
+            "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" +
+                mbServerIp + "'&reconnect='true'";
+        initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);
+
+        try {
+            initialContext = new InitialContext(initialContextProperties);
+            TopicConnectionFactory topicConnectionFactory =
+                (TopicConnectionFactory) initialContext.lookup("qpidConnectionfactory");
+            topicConnection = topicConnectionFactory.createTopicConnection();
+            topicConnection.start();
+            topicSession =
+                topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Topic topic = topicSession.createTopic(topicName);
+            topicSubscriber =
+                topicSession.createSubscriber(topic);
+
+            topicSubscriber.setMessageListener(new TopologyListener());
+
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+
+            try {
+                if (topicSubscriber != null) {
+                    topicSubscriber.close();
+                }
+
+                if (topicSession != null) {
+                    topicSession.close();
+                }
+
+                if (topicConnection != null) {
+                    topicConnection.close();
+                }
+            } catch (JMSException e1) {
+                // ignore
+            }
+
+        } finally {
+            // start the health checker
+            Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
+            healthChecker.start();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriberTask.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriberTask.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/subscriber/TopologySubscriberTask.java
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/ConfigHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/ConfigHolder.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/ConfigHolder.java
new file mode 100644
index 0000000..6f680b9
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/ConfigHolder.java
@@ -0,0 +1,197 @@
+/**
+ *  Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.wso2.carbon.adc.topology.mgt.util;
+
+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.lb.common.conf.LoadBalancerConfiguration;
+import org.wso2.carbon.lb.common.conf.LoadBalancerConfiguration.ServiceConfiguration;
+import org.wso2.carbon.lb.common.service.LoadBalancerConfigurationService;
+import org.wso2.carbon.ntask.core.service.TaskService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.adc.topology.mgt.exception.TopologyMgtException;
+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;
+
+/**
+ *
+ */
+public class ConfigHolder {
+
+    private static ConfigHolder instance;
+    private static final Log log = LogFactory.getLog(ConfigHolder.class);
+
+    private SynapseConfiguration synapseConfiguration;
+    private ConfigurationContext configCtxt;
+    private AxisConfiguration axisConfiguration;
+    private UserRegistry configRegistry;
+    private UserRegistry governanceRegistry;
+    private TaskService taskService;
+    private BlockingQueue sharedTopologyDiffQueue = new LinkedBlockingQueue();
+    private String previousMessage;
+    private Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations;
+//    private DependencyManagementService dependencyManager;
+    private LoadBalancerConfigurationService lbConfigService;
+    
+
+//    private Map<Integer, SynapseEnvironmentService> synapseEnvironmentServices =
+//            new HashMap<Integer, SynapseEnvironmentService>();
+
+    public RealmService getRealmService() {
+        return realmService;
+    }
+
+    public void setRealmService(RealmService realmService) {
+        this.realmService = realmService;
+    }
+
+    private RealmService realmService;
+
+    private ConfigHolder() {
+    }
+
+    public static ConfigHolder getInstance() {
+        if (instance == null) {
+            instance = new ConfigHolder();
+        }
+        return instance;
+    }
+
+    public SynapseConfiguration getSynapseConfiguration() throws TopologyMgtException{
+        assertNull("SynapseConfiguration", synapseConfiguration);
+        return synapseConfiguration;
+    }
+
+    public void setSynapseConfiguration(SynapseConfiguration synapseConfiguration) {
+        this.synapseConfiguration = synapseConfiguration;
+    }
+
+    public AxisConfiguration getAxisConfiguration() throws TopologyMgtException {
+        assertNull("AxisConfiguration", axisConfiguration);
+        return axisConfiguration;
+    }
+
+    public void setAxisConfiguration(AxisConfiguration axisConfiguration) {
+        this.axisConfiguration = axisConfiguration;
+    }
+
+    public UserRegistry getConfigRegistry() throws TopologyMgtException {
+        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 TopologyMgtException {
+        if (object == null) {
+            String message = name + " reference in the proxy admin config holder is null";
+            log.error(message);
+            throw new TopologyMgtException(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 void setLbConfigService(LoadBalancerConfigurationService lbConfigSer) {
+        this.lbConfigService = lbConfigSer;
+    }
+
+    public LoadBalancerConfiguration getLbConfig() {
+        return (LoadBalancerConfiguration) lbConfigService.getLoadBalancerConfig();
+    }
+    
+    public TaskService getTaskService() {
+        return taskService;
+    }
+
+    public void setTaskService(TaskService taskService) {
+        this.taskService = taskService;
+    }
+
+    public BlockingQueue getSharedTopologyDiffQueue() {
+	    return sharedTopologyDiffQueue;
+    }
+
+	public void setSharedTopologyDiffQueue(BlockingQueue sharedTopologyDiffQueue) {
+	    this.sharedTopologyDiffQueue = sharedTopologyDiffQueue;
+    }
+
+	public void setServiceConfigs(Map<String, List<ServiceConfiguration>> serviceNameToServiceConfigurations) {
+
+		this.serviceNameToServiceConfigurations = serviceNameToServiceConfigurations;
+    }
+	
+	public Map<String, List<ServiceConfiguration>> getServiceConfigs(){
+		return serviceNameToServiceConfigurations;
+	}
+
+	public String getPreviousMessage() {
+	    return previousMessage;
+    }
+
+	public void setPreviousMessage(String previousMessage) {
+	    this.previousMessage = previousMessage;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyConstants.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyConstants.java
new file mode 100644
index 0000000..784284b
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyConstants.java
@@ -0,0 +1,13 @@
+package org.wso2.carbon.adc.topology.mgt.util;
+
+public class TopologyConstants {
+    
+    public static final String TOPIC_NAME = "cloud-controller-topology";
+    public static final String MB_SERVER_IP = "mb.server.ip";
+    public static final String DEFAULT_MB_SERVER_IP = "localhost:5673";
+    
+    public static final String TOPOLOGY_SYNC_CRON = "1 * * * * ? *";
+	public static final String TOPOLOGY_SYNC_TASK_NAME = "TopologySubscriberTaskOfADC";
+	public static final String TOPOLOGY_SYNC_TASK_TYPE = "TOPOLOGY_SUBSCRIBER_TASK";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyMgtUtil.java b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyMgtUtil.java
new file mode 100644
index 0000000..c87c328
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/java/org/wso2/carbon/adc/topology/mgt/util/TopologyMgtUtil.java
@@ -0,0 +1,5 @@
+package org.wso2.carbon.adc.topology.mgt.util;
+
+public class TopologyMgtUtil {
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..33d6c1d
--- /dev/null
+++ b/components/stratos/artifact-deployment-coordinator/org.wso2.carbon.adc.topology.mgt/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,9 @@
+<serviceGroup>
+    <service name="TopologyMgtService" scope="application">
+        <parameter name="ServiceClass">org.wso2.carbon.adc.topology.mgt.service.impl.TopologyManagementServiceImpl</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/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
new file mode 100644
index 0000000..6bdbdf6
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
@@ -0,0 +1,140 @@
+<!--
+# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+  -->
+<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.wso2.carbon</groupId>
+        <artifactId>billing-parent</artifactId>
+        <version>2.1.0</version>
+<relativePath>../../pom.xml</relativePath>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wso2.carbon</groupId>
+    <artifactId>org.wso2.carbon.billing.core</artifactId>
+    <version>2.1.0</version>
+    <packaging>bundle</packaging>
+    <name>WSO2 Carbon - Billing Core</name>
+
+    <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.wso2.carbon.billing.core.*,
+                        </Export-Package>
+                        <!--<Require-Bundle>
+                            drools;visibility:=reexport
+                        </Require-Bundle>-->
+                        <Import-Package>
+                            org.wso2.carbon.rule.*,
+                            org.wso2.carbon.email.sender.api,
+                            org.quartz.*; version=2.1.1,
+                            org.apache.synapse.task.*,
+                            org.wso2.carbon.registry.core.*;version=1.0.1,
+                            org.wso2.carbon.registry.resource.*,
+                            !javax.xml.namespace,
+                            javax.xml.namespace; version=0.0.0,
+                            javax.servlet;version="${imp.pkg.version.javax.servlet}",
+                            javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
+                            org.apache.axiom.*; version="${axiom.osgi.version.range}",
+                            *;resolution:=optional
+                        </Import-Package>
+                        <DynamicImport-Package>*</DynamicImport-Package>
+                    </instructions>
+                </configuration>
+            </plugin>
+            <plugin>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <inherited>true</inherited>
+                <configuration>
+                    <forkMode>pertest</forkMode>
+                    <argLine>-enableassertions</argLine>
+                    <testFailureIgnore>false</testFailureIgnore>
+                    <excludes>
+                        <exclude>**/CashTest.java</exclude>
+                        <exclude>**/MonthlyTriggerCalculatorTest.java</exclude>
+                        <exclude>**/RuleTest.java</exclude>
+                        <exclude>**/CarbonHome1Test.java</exclude>
+                        <exclude>**/InvoiceMsgTest.java</exclude>
+                        <exclude>**/TestUtils.java</exclude>
+                        <exclude>**/TriggerTest.java</exclude>
+                    </excludes>
+                </configuration>
+            </plugin>            
+        </plugins>
+    </build>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.email.sender</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.registry.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.user.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.synapse</groupId>
+            <artifactId>synapse-tasks</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.kernel</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.common</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.rule.backend</artifactId>
+        </dependency>
+        <dependency>
+           <groupId>org.wso2.carbon</groupId>
+           <artifactId>org.wso2.carbon.stratos.common</artifactId>
+       </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ndatasource.core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.wso2.carbon</groupId>
+            <artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId>
+        </dependency>
+    </dependencies>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
new file mode 100644
index 0000000..47ebf03
--- /dev/null
+++ b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.billing.core;
+
+public class BillingConstants {
+    public static final String GROUP_ID = "BillingTasks";
+    public static final String TASK_NAME_KEY = "taskName";
+    public static final String SCHEDULER_KEY = "scheduler";
+    public static final String SCHEDULER_CONTEXT = "schedulerContext";
+    public static final String BILLING_ENGINE_KEY = "billingEngine";
+    public static final String BILLING_CONFIG = "billing-config.xml";
+    public static final String CONFIG_NS = "http://wso2.com/carbon/multitenancy/billing/config";
+    public static final String TRIGGER_CALCULATOR_CLASS_ATTR = "scheduleHelperClass";
+    public static final String TRIGGER_CALCULATOR_SERVICE_ATTR = "scheduleHelperService";
+    public static final String SCHEDULE_CONF_KEY = "schedule";
+    public static final String SCHEDULE_CONF_PARAM_KEY = "parameter";
+    public static final String SCHEDULE_CONF_PARAM_NAME_KEY = "name";
+    public static final String HANDLER = "handler";
+    public static final String HANDLERS = "handlers";
+    public static final String HANDLER_CLASS_ATTR = "class";
+    public static final String HANDLER_SERVICE_ATTR = "service";
+    public static final String SUBSCRIPTION_FILTER_KEY = "subscriptionFilter";
+    public static final String DB_CONFIG = "dbConfig";
+    public static final String TASKS = "tasks";
+    public static final String ATTR_ID = "id";
+    public static final String NS_PREFIX = "";
+    public static final String DBCONFIG_VALIDATION_QUERY = "validationQuery";
+    public static final String DBCONFIG_MAX_WAIT = "maxWait";
+    public static final String DBCONFIG_MIN_IDLE = "minIdle";
+    public static final String DBCONFIG_MAX_ACTIVE = "maxActive";
+    public static final String DBCONFIG_DRIVER_NAME = "driverName";
+    public static final String DBCONFIG_PASSWORD = "password";
+    public static final String DBCONFIG_USER_NAME = "userName";
+    public static final String DBCONFIG_URL = "url";
+    public static final String SUBSCRIPTION_SUBITEM = "subscription";
+    public static final String BANDWIDTH_SUBITEM = "bwOveruse";
+    public static final String STORAGE_SUBITEM = "storageOveruse";
+    public static final String PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-payment-received-customer.xml";
+    public static final String REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-registration-payment-received-customer.xml";
+    public static final String PAYMENT_RECEIVED_EMAIL_WSO2_FILE = "email-payment-received-wso2.xml";
+    public static final String WSO2_BILLING_DS = "WSO2BillingDS";
+}


[03/52] [partial] initial commit to apache incubator. Here just commit WSO2 Stratos code base as it is. After that will start re-factor code to apache

Posted by la...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
new file mode 100755
index 0000000..8470a39
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/beans/TenantInfoBean.java
@@ -0,0 +1,137 @@
+/*
+ *  Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ *  WSO2 Inc. licenses this file to you under the Apache License,
+ *  Version 2.0 (the "License"); you may not use this file except
+ *  in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+package org.wso2.carbon.stratos.common.beans;
+
+import java.util.Calendar;
+
+/**
+ * Bean class for Tenant Information
+ */
+public class TenantInfoBean {
+
+    private String admin; //admin's user name
+    private String firstname;
+    private String lastname;
+    private String adminPassword;
+    private String tenantDomain;
+    private int tenantId;
+    private String email;
+    private boolean active;
+    private String successKey;
+    Calendar createdDate;
+    private String originatedService;
+    private String usagePlan;
+
+    public String getFirstname() {
+        return firstname;
+    }
+
+    public void setFirstname(String firstname) {
+        this.firstname = firstname;
+    }
+
+    public String getLastname() {
+        return lastname;
+    }
+
+    public void setLastname(String lastname) {
+        this.lastname = lastname;
+    }
+
+    public String getEmail() {
+
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public int getTenantId() {
+        return tenantId;
+    }
+
+    public void setTenantId(int tenantId) {
+        this.tenantId = tenantId;
+    }
+
+    public String getTenantDomain() {
+        return tenantDomain;
+    }
+
+    public void setTenantDomain(String tenantDomain) {
+        this.tenantDomain = tenantDomain;
+    }
+
+    public String getAdmin() {
+        return admin;
+    }
+
+    public void setAdmin(String admin) {
+        this.admin = admin;
+    }
+
+    public String getAdminPassword() {
+        return adminPassword;
+    }
+
+    public void setAdminPassword(String adminPassword) {
+        this.adminPassword = adminPassword;
+    }
+
+    public boolean isActive() {
+        return active;
+    }
+
+    public void setActive(boolean active) {
+        this.active = active;
+    }
+
+    public String getSuccessKey() {
+        return successKey;
+    }
+
+    public void setSuccessKey(String successKey) {
+        this.successKey = successKey;
+    }
+
+    public Calendar getCreatedDate() {
+        return createdDate;
+    }
+
+    public void setCreatedDate(Calendar createdDate) {
+        this.createdDate = createdDate;
+    }
+
+    public String getOriginatedService() {
+        return originatedService;
+    }
+
+    public void setOriginatedService(String originatedService) {
+        this.originatedService = originatedService;
+    }
+
+    public String getUsagePlan() {
+        return usagePlan;
+    }
+
+    public void setUsagePlan(String usagePlan) {
+        this.usagePlan = usagePlan;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
new file mode 100644
index 0000000..a776bf2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfig.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class CloudServiceConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+
+    private static final String NAME_ATTR_NAME = "name";
+    private static final String DEFAULT_ATTR_NAME = "default";
+    private static final String LABEL_ELEMENT_NAME = "label";
+    private static final String LINK_ELEMENT_NAME = "link";
+    private static final String ICON_ELEMENT_NAME = "icon";
+    private static final String DESCRIPTION_ELEMENT_NAME = "description";
+    private static final String PERMISSIONS_ELEMENT_NAME = "permissions";
+    private static final String PERMISSION_ELEMENT_NAME = "permission";
+    private static final String PRODUCT_PAGE_URL_ELEMENT_NAME = "productPageURL";
+
+    private String name;
+    private String label;
+    private String link;
+    private String icon;
+    private String description;
+    private List<PermissionConfig> permissionConfigs;
+    boolean defaultActive;
+    private String productPageURL;
+
+    public CloudServiceConfig(OMElement configEle) {
+        permissionConfigs = new ArrayList<PermissionConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator cloudServiceChildIt = configEle.getChildElements();
+        name = configEle.getAttributeValue(new QName(null, NAME_ATTR_NAME));
+        defaultActive = "true".equals(configEle.
+                getAttributeValue(new QName(null, DEFAULT_ATTR_NAME)));
+        while (cloudServiceChildIt.hasNext()) {
+            Object cloudServiceChildObj = cloudServiceChildIt.next();
+            if (!(cloudServiceChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement cloudServiceChildEle = (OMElement) cloudServiceChildObj;
+            if (new QName(CONFIG_NS, LABEL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                label = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, ICON_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                icon = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, LINK_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                link = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PRODUCT_PAGE_URL_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                productPageURL = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, DESCRIPTION_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                description = cloudServiceChildEle.getText();
+            } else if (new QName(CONFIG_NS, PERMISSIONS_ELEMENT_NAME, "").
+                    equals(cloudServiceChildEle.getQName())) {
+                Iterator permissionChildIt = cloudServiceChildEle.getChildElements();
+                while (permissionChildIt.hasNext()) {
+                    Object permissionChildObj = permissionChildIt.next();
+                    if (!(permissionChildObj instanceof OMElement)) {
+                        continue;
+                    }
+                    OMElement permissionChildEle = (OMElement) permissionChildObj;
+
+                    if (new QName(CONFIG_NS, PERMISSION_ELEMENT_NAME, "").
+                            equals(permissionChildEle.getQName())) {
+                        PermissionConfig permissionConfig =
+                                new PermissionConfig(permissionChildEle);
+                        permissionConfigs.add(permissionConfig);
+                    }
+                }
+            }
+
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getLabel() {
+        return label;
+    }
+
+    public void setLabel(String label) {
+        this.label = label;
+    }
+
+    public String getLink() {
+        return link;
+    }
+
+    public void setLink(String link) {
+        this.link = link;
+    }
+
+    public String getIcon() {
+        return icon;
+    }
+
+    public void setIcon(String icon) {
+        this.icon = icon;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<PermissionConfig> getPermissionConfigs() {
+        return permissionConfigs;
+    }
+
+    public void setPermissionConfigs(List<PermissionConfig> permissionConfigs) {
+        this.permissionConfigs = permissionConfigs;
+    }
+
+    public boolean isDefaultActive() {
+        return defaultActive;
+    }
+
+    public void setDefaultActive(boolean defaultActive) {
+        this.defaultActive = defaultActive;
+    }
+
+    public String getProductPageURL() {
+        return productPageURL;
+    }
+
+    public void setProductPageURL(String productPageURL) {
+        this.productPageURL = productPageURL;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
new file mode 100644
index 0000000..b01a385
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServiceConfigParser.java
@@ -0,0 +1,48 @@
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+public class CloudServiceConfigParser {
+
+    private static Log log = LogFactory.getLog(CloudServiceConfigParser.class);
+
+    private static class SynchronizingClass {
+    }
+
+    private static final SynchronizingClass loadlock = new SynchronizingClass();
+
+    private static CloudServicesDescConfig cloudServicesDescConfig = null;
+
+    private static final String CONFIG_FILENAME = "cloud-services-desc.xml";
+
+    public static CloudServicesDescConfig loadCloudServicesConfiguration() throws Exception {
+        if (cloudServicesDescConfig != null) {
+            return cloudServicesDescConfig;
+        }
+
+        synchronized (loadlock) {
+            if (cloudServicesDescConfig == null) {
+                try {
+                    String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator + 
+                            StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator + CONFIG_FILENAME;
+                    OMElement configElement = CommonUtil.buildOMElement(new FileInputStream(configFileName));
+                    cloudServicesDescConfig = new CloudServicesDescConfig(configElement);
+                } catch (Exception e) {
+                    String msg = "Error in building the cloud service configuration.";
+                    log.error(msg, e);
+                    throw new Exception(msg, e);
+                }
+            }
+        }
+        return cloudServicesDescConfig;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
new file mode 100644
index 0000000..27d3f9e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/CloudServicesDescConfig.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.xml.namespace.QName;
+import java.util.*;
+
+public class CloudServicesDescConfig {
+    private static final Log log = LogFactory.getLog(CloudServicesDescConfig.class);
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String CLOUD_SERVICE_ELEMENT_NAME = "cloudService";
+
+    Map<String, CloudServiceConfig> cloudServiceConfigs;
+
+    public CloudServicesDescConfig(OMElement configEle) {
+        // as the cloud service configs are kept in an order, we use an ordered map.
+        cloudServiceConfigs = new LinkedHashMap<String, CloudServiceConfig>();
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, CLOUD_SERVICE_ELEMENT_NAME, "").
+                    equals(configChildEle.getQName())) {
+                CloudServiceConfig cloudServiceConfig = new CloudServiceConfig(configChildEle);
+                String name = cloudServiceConfig.getName();
+                cloudServiceConfigs.put(name, cloudServiceConfig);
+            }
+        }
+    }
+
+    public Map<String, CloudServiceConfig> getCloudServiceConfigs() {
+        return cloudServiceConfigs;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
new file mode 100644
index 0000000..5171019
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/config/PermissionConfig.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.config;
+
+import org.apache.axiom.om.OMElement;
+
+import javax.xml.namespace.QName;
+import java.util.Iterator;
+
+public class PermissionConfig {
+    private static final String CONFIG_NS = "http://wso2.com/carbon/cloud/mgt/services";
+    private static final String PATH = "path";
+    private static final String NAME = "name";
+    String name;
+    String path;
+
+    public PermissionConfig(OMElement configEle) {
+        serialize(configEle);
+    }
+
+    public void serialize(OMElement configEle) {
+
+        Iterator configChildIt = configEle.getChildElements();
+        while (configChildIt.hasNext()) {
+            Object configChildObj = configChildIt.next();
+            if (!( configChildObj instanceof OMElement)) {
+                continue;
+            }
+            OMElement configChildEle = (OMElement)configChildObj;
+            if (new QName(CONFIG_NS, NAME, "").
+                    equals(configChildEle.getQName())) {
+                name = configChildEle.getText();
+            } else if (new QName(CONFIG_NS, PATH, "").
+                    equals(configChildEle.getQName())) {
+                path = configChildEle.getText();
+            }
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
new file mode 100644
index 0000000..bbc3dd9
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/StratosConstants.java
@@ -0,0 +1,143 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.stratos.common.constants;
+
+import java.io.File;
+
+public class StratosConstants {
+
+    public static final String CLOUD_SERVICE_IS_ACTIVE_PROP_KEY = "active";
+
+    public static final String CLOUD_SERVICE_INFO_STORE_PATH =
+            "/repository/components/org.wso2.stratos/cloud-manager/cloud-services";
+
+    public static final String TENANT_USER_VALIDATION_STORE_PATH =
+            "/repository/components/org.wso2.carbon.validations";
+    public static final String ADMIN_EMAIL_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.email-confirmation-flag";
+    public static final String TENANT_DOMAIN_VERIFICATION_FLAG_PATH =
+            "/repository/components/org.wso2.carbon.domain-confirmation-flag";
+
+    public static final String DOMAIN_VALIDATOR_INFO_PATH =
+            "/repository/components/org.wso2.carbon.domain-validator-info";
+
+    public static final String TENANT_CREATION_THEME_PAGE_TOKEN =
+            "/repository/components/org.wso2.carbon.theme-page-token";
+
+    public static final String TENANT_PACKAGE_INFO_PATH =
+            "/repository/components/org.wso2.carbon.package-info";
+
+    public static final String ALL_THEMES_PATH =
+            "/repository/components/org.wso2.carbon.all-themes";
+
+    public static final String THROTTLING_RULES_PATH =
+            "/repository/components/org.wso2.carbon.throttling-rules";
+
+    public static final String ORIGINATED_SERVICE_PATH =
+            "/repository/components/org.wso2.carbon.originated-service";
+
+    public static final String PATH_SEPARATOR = "/";
+
+    public static final String CLOUD_SERVICE_ICONS_STORE_PATH =
+            "/repository/components/org.wso2.carbon.cloud-manager/" +
+                    "cloud-services-icons";
+
+    public static final String VALIDATION_KEY_RESOURCE_NAME = "validation-key";
+    public static final String INCOMING_PATH_DIR = "incoming";
+    public static final String OUTGOING_PATH_DIR = "outgoing";
+    public static final String MULTITENANCY_SCHEDULED_TASK_ID = "multitenancyScheduledTask";
+    public static final String MULTITENANCY_VIEWING_TASK_ID = "multitenancyViewingTask";
+
+    public static final String INVALID_TENANT = "invalidTenant";
+    public static final String INACTIVE_TENANT = "inactiveTenant";
+    public static final String ACTIVE_TENANT = "activeTenant";
+    public static final String IS_EMAIL_VALIDATED = "isEmailValidated";
+    public static final String IS_CREDENTIALS_ALREADY_RESET = "isCredentialsReset";
+    public static final String TENANT_ADMIN = "tenantAdminUsername";
+
+    public static final String CLOUD_MANAGER_SERVICE = "WSO2 Stratos Manager";
+    public static final String CLOUD_IDENTITY_SERVICE = "WSO2 Stratos Identity";
+    public static final String CLOUD_GOVERNANCE_SERVICE = "WSO2 Stratos Governance";
+    public static final String CLOUD_ESB_SERVICE = "WSO2 Stratos Enterprise Service Bus";
+
+    // keystore mgt related Constants
+    public static final String TENANT_KS = "/repository/security/key-stores/";
+    public static final String TENANT_PUB_KEY = "/repository/security/pub-key";
+    public static final String PROP_TENANT_KS_TYPE = "key-store-type";
+    public static final String PROP_TENANT_KS_PASSWD = "key-store-password";
+    public static final String PROP_TENANT_KS_PRIV_KEY_PASSWD = "priv-key-password";
+    public static final String PROP_TENANT_KS_ALIAS = "alias";
+
+    // constants related to redirection
+
+    public static final String UNVERIFIED_ACCOUNT_DOMAIN_SUFFIX = "-unverified";
+    public static final String TENANT_SPECIFIC_URL_RESOLVED = "tenant-sepcific-url-resolved";
+    public static final String SUFFIXED_UNVERIFIED_SESSION_FLAG = "temp-suffixed-unverified";
+
+    // metering constants
+    public static final String THROTTLING_ALL_ACTION = "all_actions";
+    public static final String THROTTLING_IN_DATA_ACTION = "in_data_action"; //this covers registry capacity + registry bandwidth
+    public static final String THROTTLING_OUT_DATA_ACTION = "out_data_action"; //this covers registry bandwidth
+    public static final String THROTTLING_ADD_USER_ACTION = "add_user_action";
+    public static final String THROTTLING_SERVICE_IN_BANDWIDTH_ACTION = "service_in_bandwith_action";
+    public static final String THROTTLING_SERVICE_OUT_BANDWIDTH_ACTION = "service_out_bandwith_action";
+    public static final String THROTTLING_WEBAPP_IN_BANDWIDTH_ACTION = "webapp_in_bandwith_action";
+    public static final String THROTTLING_WEBAPP_OUT_BANDWIDTH_ACTION = "webapp_out_bandwith_action";
+    public static final String THROTTLING_SERVICE_REQUEST_ACTION = "service_request_action";
+    public static final String THROTTLING_SERVICE_RESPONSE_ACTION = "service_response_action";
+
+    // the session attribute to keep track whether the registry action validated
+    // and the usage persisted
+    public static final String REGISTRY_ACTION_VALIDATED_SESSION_ATTR = "registryActionValidated";
+    public static final String REGISTRY_USAGE_PERSISTED_SESSION_ATTR = "usagePersited";
+
+    // Metering servlet attributes
+    public static final String SERVICE_NAME_SERVLET_ATTR = "meteringServiceName";
+    public static final String TENANT_ID_SERVLET_ATTR = "tenantId";
+    public static final String ADMIN_SERVICE_SERVLET_ATTR = "adminService";
+
+    // * as a Service impl related constants
+    public static final String ORIGINATED_SERVICE = "originatedService";
+
+    // Configuration file name
+    public static final String STRATOS_CONF_FILE = "stratos.xml";
+    //public static final String STRATOS_CONF_LOC = "repository/conf/";
+    //public static final String STRATOS_CONF_FILE_WITH_PATH = STRATOS_CONF_LOC + STRATOS_CONF_FILE;
+
+    // EULA location
+    public static final String STRATOS_EULA = "eula.xml";
+
+    // EULA default text.
+    public static final String STRATOS_EULA_DEFAULT_TEXT =
+            "Please refer to: " + StratosConstants.STRATOS_TERMS_OF_USAGE +
+                    " for terms and usage and " + StratosConstants.STRATOS_PRIVACY_POLICY +
+                    " for privacy policy of WSO2 Stratos.";
+
+    // Web location of Terms of Usage and privacy policy
+    public static final String STRATOS_TERMS_OF_USAGE =
+            "http://wso2.com/cloud/services/terms-of-use/";
+    public static final String STRATOS_PRIVACY_POLICY =
+            "http://wso2.com/cloud/services/privacy-policy/";
+    public static final String MULTITENANCY_FREE_PLAN = "Demo";
+    public static final String MULTITENANCY_SMALL_PLAN = "SMB";
+    public static final String MULTITENANCY_MEDIUM_PLAN = "Professional";
+    public static final String MULTITENANCY_LARGE_PLAN = "Enterprise";
+    public static final String EMAIL_CONFIG= "email";
+    public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy";
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
new file mode 100644
index 0000000..aa6a922
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/constants/UsageConstants.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.constants;
+
+public class UsageConstants {
+    final public static String ANY_DURATION = "anyDuration";
+
+    public static final String SYSTEM_METERING_PATH =
+            "/repository/components/org.wso2.carbon.system-metering";
+
+    public static final String CUSTOM_METERING_PATH =
+        "/repository/components/org.wso2.carbon.system-metering";
+
+    // the measurements
+    final public static String CAPACITY_USAGE = "capacity-usage";
+    
+    final public static String SERVICE_REQUEST_COUNT = "serviceRequestCount";
+    final public static String SERVICE_RESPONSE_COUNT = "serviceResponseCount";
+    final public static String SERVICE_FAULT_COUNT = "serviceFaultCount";
+    
+    public static final String BANDWIDTH_KEY_PATTERN = "%Bandwidth%";
+    public static final String REGISTRY_BANDWIDTH = "RegistryBandwidth";
+    public static final String SERVICE_BANDWIDTH = "ServiceBandwidth";
+    public static final String WEBAPP_BANDWIDTH = "WebappBandwidth";
+    public static final String IN_LABLE = "-In";
+    public static final String OUT_LABLE = "-Out";
+    public static final String REGISTRY_CONTENT_BANDWIDTH = "ContentBandwidth";
+    
+    final public static String REGISTRY_INCOMING_BW = REGISTRY_BANDWIDTH + IN_LABLE;
+    final public static String REGISTRY_OUTGOING_BW = REGISTRY_BANDWIDTH + OUT_LABLE;
+    final public static String REGISTRY_TOTAL_BW = "registry-total-bw-usage";
+    final public static String NUMBER_OF_USERS = "number-of-users";
+
+    final public static String SERVICE_INCOMING_BW = SERVICE_BANDWIDTH + IN_LABLE;
+    final public static String SERVICE_OUTGOING_BW = SERVICE_BANDWIDTH + OUT_LABLE;
+    final public static String SERVICE_TOTAL_BW = "serviceRequestTotalBw";
+    
+    final public static String WEBAPP_INCOMING_BW = WEBAPP_BANDWIDTH + IN_LABLE;
+    final public static String WEBAPP_OUTGOING_BW = WEBAPP_BANDWIDTH + OUT_LABLE;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
new file mode 100644
index 0000000..678cc63
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/exception/StratosException.java
@@ -0,0 +1,41 @@
+/*
+*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+*  WSO2 Inc. licenses this file to you under the Apache License,
+*  Version 2.0 (the "License"); you may not use this file except
+*  in compliance with the License.
+*  You may obtain a copy of the License at
+*
+*    http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.stratos.common.exception;
+
+/**
+ * This class is defined as the general Exception implementation for Stratos. This can be used
+ * within Stratos components when handling exceptions.
+ */
+public class StratosException extends Exception{
+
+    public StratosException() {
+    }
+
+    public StratosException(String message) {
+        super(message);
+    }
+
+    public StratosException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public StratosException(Throwable cause) {
+        super(cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/internal/CloudCommonServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/internal/CloudCommonServiceComponent.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/internal/CloudCommonServiceComponent.java
new file mode 100644
index 0000000..7549666
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/internal/CloudCommonServiceComponent.java
@@ -0,0 +1,121 @@
+package org.wso2.carbon.stratos.common.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.stratos.common.packages.PackageInfoHolder;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.stratos.common.util.StratosConfiguration;
+import org.wso2.carbon.registry.core.exceptions.RegistryException;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+/**
+ * @scr.component name="stratos.common" immediate="true"
+ * @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="user.realmservice.default"
+ *                interface="org.wso2.carbon.user.core.service.RealmService"
+ *                cardinality="1..1" policy="dynamic" bind="setRealmService"
+ *                unbind="unsetRealmService"
+ */
+public class CloudCommonServiceComponent {
+
+    private static Log log = LogFactory.getLog(CloudCommonServiceComponent.class);
+
+    private static BundleContext bundleContext;
+    private static RealmService realmService;
+    private static RegistryService registryService;
+    private static PackageInfoHolder packageInfos;
+
+    protected void activate(ComponentContext context) {
+        try {
+            bundleContext = context.getBundleContext();
+            if (CommonUtil.getStratosConfig() == null) {
+                StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
+                CommonUtil.setStratosConfig(stratosConfig);
+            }
+
+            // Loading the EULA
+            if (CommonUtil.getEula() == null) {
+                String eula = CommonUtil.loadTermsOfUsage();
+                CommonUtil.setEula(eula);
+            }
+            
+			packageInfos = new PackageInfoHolder();
+			context.getBundleContext().registerService(
+					PackageInfoHolder.class.getName(), packageInfos, null);
+
+            //Register manager configuration OSGI service
+            try {
+                StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
+                bundleContext.registerService(StratosConfiguration.class.getName(), stratosConfiguration, null);
+                if (log.isDebugEnabled()) {
+                    log.debug("******* Cloud Common Service bundle is activated ******* ");
+                }
+            } catch (Exception ex) {
+                String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
+                log.error(msg, ex);
+            }
+        } catch (Throwable e) {
+            log.error("Error in activating Cloud Common Service Component" + e.toString());
+        }
+    }
+
+    protected void deactivate(ComponentContext context) {
+        log.debug("******* Tenant Core bundle is deactivated ******* ");
+    }
+
+    protected void setRegistryService(RegistryService registryService) {
+        CloudCommonServiceComponent.registryService = registryService;
+    }
+
+    protected void unsetRegistryService(RegistryService registryService) {
+        setRegistryService(null);
+    }
+
+    protected void setRealmService(RealmService realmService) {
+        CloudCommonServiceComponent.realmService = realmService;
+    }
+
+    protected void unsetRealmService(RealmService realmService) {
+        setRealmService(null);
+    }
+
+    public static BundleContext getBundleContext() {
+        return bundleContext;
+    }
+
+    public static RegistryService getRegistryService() {
+        return registryService;
+    }
+
+
+    public static RealmService getRealmService() {
+        return realmService;
+    }
+
+    public static TenantManager getTenantManager() {
+        return realmService.getTenantManager();
+    }
+
+    public static UserRegistry getGovernanceSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getGovernanceSystemRegistry(tenantId);
+    }
+
+    public static UserRegistry getConfigSystemRegistry(int tenantId) throws RegistryException {
+        return registryService.getConfigSystemRegistry(tenantId);
+    }
+
+	public static PackageInfoHolder getPackageInfos() {
+		return packageInfos;
+	}
+
+    
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/listeners/TenantMgtListener.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/listeners/TenantMgtListener.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/listeners/TenantMgtListener.java
new file mode 100644
index 0000000..49da83e
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/listeners/TenantMgtListener.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.listeners;
+
+import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+
+public interface TenantMgtListener {
+    public void onTenantCreate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantUpdate(TenantInfoBean tenantInfo) throws StratosException;
+
+    public void onTenantRename(int tenantId, String oldDomainName, 
+                             String newDomainName)throws StratosException;
+    
+    public void onTenantInitialActivation(int tenantId) throws StratosException;
+    
+    public void onTenantActivation(int tenantId) throws StratosException;
+    
+    public void onTenantDeactivation(int tenantId) throws StratosException;
+
+    public void onSubscriptionPlanChange(int tenentId, String oldPlan, 
+                                         String newPlan) throws StratosException;
+    
+    public int getListenerOrder();
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfo.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfo.java
new file mode 100644
index 0000000..869c694
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfo.java
@@ -0,0 +1,93 @@
+package org.wso2.carbon.stratos.common.packages;
+
+/*
+ * Deserialize following XML
+<packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+    <package name="multitenancy-free">
+        <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+        <users>
+            <limit>5</limit>
+            <charge>0</charge> <!-- charge per month -->
+        </users>
+        <resourceVolume>
+            <limit>10</limit> <!--mb per user -->
+        </resourceVolume>
+        <bandwidth>
+            <limit>1000</limit> <!-- mb per user -->
+            <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+        </bandwidth>
+    </package>
+    <package name="multitenancy-small">
+        ...
+    </package>
+</packages>
+ */
+public class PackageInfo {
+	
+	private String name;
+	private int usersLimit;
+	private int subscriptionCharge;
+	private int chargePerUser;
+	private int resourceVolumeLimit;
+	private int bandwidthLimit;
+	private int bandwidthOveruseCharge;
+
+	
+	public String getName() {
+		return name;
+	}
+
+	public void setName(String name) {
+		this.name = name;
+	}
+
+	public int getUsersLimit() {
+		return usersLimit;
+	}
+
+	public void setUsersLimit(int usersLimit) {
+		this.usersLimit = usersLimit;
+	}
+
+	public int getSubscriptionCharge() {
+		return subscriptionCharge;
+	}
+
+	public void setSubscriptionCharge(int subscriptionCharge) {
+		this.subscriptionCharge = subscriptionCharge;
+	}
+
+	public int getChargePerUser() {
+		return chargePerUser;
+	}
+
+	public void setChargePerUser(int chargePerUser) {
+		this.chargePerUser = chargePerUser;
+	}
+
+	public int getResourceVolumeLimit() {
+		return resourceVolumeLimit;
+	}
+
+	public void setResourceVolumeLimit(int resourceVolumeLimit) {
+		this.resourceVolumeLimit = resourceVolumeLimit;
+	}
+
+	public int getBandwidthLimit() {
+		return bandwidthLimit;
+	}
+
+	public void setBandwidthLimit(int bandwidthLimit) {
+		this.bandwidthLimit = bandwidthLimit;
+	}
+
+	public int getBandwidthOveruseCharge() {
+		return bandwidthOveruseCharge;
+	}
+
+	public void setBandwidthOveruseCharge(int bandwidthOveruseCharge) {
+		this.bandwidthOveruseCharge = bandwidthOveruseCharge;
+	}
+
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfoHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfoHolder.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfoHolder.java
new file mode 100644
index 0000000..bf5c1e6
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/packages/PackageInfoHolder.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wso2.carbon.stratos.common.packages;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.xpath.AXIOMXPath;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jaxen.JaxenException;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.exception.StratosException;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.namespace.QName;
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class PackageInfoHolder {
+    private static Log log = LogFactory.getLog(PackageInfoHolder.class);
+    private static final String PACKAGE_DESCRIPTION_CONFIG = "multitenancy-packages.xml";
+    private static final String PACKAGE_DESCRIPTION_CONFIG_NS =
+            "http://wso2.com/carbon/multitenancy/billing/pacakges";
+    
+    List<PackageInfo> multitenancyPackages = new ArrayList<PackageInfo>();
+
+    public PackageInfoHolder() throws StratosException {
+        multitenancyPackages = deserializePackageDescriptionConfig();
+    }
+
+    public List<PackageInfo> getMultitenancyPackages() {
+        return multitenancyPackages;
+    }
+
+    /*
+     * Deserialize following XML
+    <packages xmlns="http://wso2.com/carbon/multitenancy/billing/pacakges">
+        <package name="multitenancy-free">
+            <!--<subscriptionCharge>0</subscriptionCharge>--> <!-- $ per month -->
+            <users>
+                <limit>5</limit>
+                <charge>0</charge> <!-- charge per month -->
+            </users>
+            <resourceVolume>
+                <limit>10</limit> <!--mb per user -->
+            </resourceVolume>
+            <bandwidth>
+                <limit>1000</limit> <!-- mb per user -->
+                <overuseCharge>0</overuseCharge> <!-- $ per user per month -->
+            </bandwidth>
+        </package>
+        <package name="multitenancy-small">
+            ...
+        </package>
+    </packages>
+     */
+    private List<PackageInfo> deserializePackageDescriptionConfig() throws StratosException {
+        String configFilePath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
+                StratosConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
+                PACKAGE_DESCRIPTION_CONFIG;
+        
+        OMElement packageConfigs;
+        try {
+            packageConfigs = CommonUtil.buildOMElement(new FileInputStream(configFilePath));
+        } catch (Exception e) {
+            String msg = "Error in deserializing the packageConfigs file: " + configFilePath + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+
+        @SuppressWarnings("unchecked")
+        Iterator<OMElement> packageConfigsChildsIt = packageConfigs.getChildElements();
+        while (packageConfigsChildsIt.hasNext()) {
+            OMElement packageConfigEle = packageConfigsChildsIt.next();
+            if (!new QName(PACKAGE_DESCRIPTION_CONFIG_NS, "package").equals(
+                    packageConfigEle.getQName())) {
+                continue;
+            }
+            
+            PackageInfo multitenancyPackage = new PackageInfo();
+            String packageName = packageConfigEle.getAttributeValue(new QName("name"));
+            String subscriptionCharge = getPackageConfigValue("subscriptionCharge", packageConfigEle);
+            String usersLimit = getPackageConfigValue("users.limit", packageConfigEle);
+            String usersCharge = getPackageConfigValue("users.charge", packageConfigEle);
+
+            String resourceVolumeLimit =
+                    getPackageConfigValue("resourceVolume.limit", packageConfigEle);
+            String resourceVolumeOveruseCharge =
+                    getPackageConfigValue("resourceVolume.overuseCharge", packageConfigEle);
+            String bandwidthLimit = getPackageConfigValue("bandwidth.limit", packageConfigEle);
+            String bandwidthOveruseCharge =
+                    getPackageConfigValue("bandwidth.overuseCharge", packageConfigEle);
+            int usersLimitInt = -1;
+            if (!usersLimit.equals("unlimited")) {
+                usersLimitInt = Integer.parseInt(usersLimit);
+            }
+            int resourceVolumeLimitInt = -1;
+            if (!resourceVolumeLimit.equals("unlimited")) {
+                resourceVolumeLimitInt = Integer.parseInt(resourceVolumeLimit);
+            }
+            int bandwidthLimitInt = -1;
+            if (!bandwidthLimit.equals("unlimited")) {
+                bandwidthLimitInt = Integer.parseInt(bandwidthLimit);
+            }
+
+            multitenancyPackage.setName(packageName);
+            //In the PackageInfo class subscriptionCharge, chargeperUser and bandwidthOverUsageCharge
+            //are declared as Integers. I think it is better to change them to float. If somebody
+            //enters a float value to the conf file it will cause an exception here
+            multitenancyPackage.setSubscriptionCharge(Integer.parseInt(subscriptionCharge));
+            multitenancyPackage.setUsersLimit(usersLimitInt);
+       //   multitenancyPackage.setChargePerUser(Integer.parseInt(usersCharge));
+            multitenancyPackage.setResourceVolumeLimit(resourceVolumeLimitInt);
+            multitenancyPackage.setBandwidthLimit(bandwidthLimitInt);
+          //  multitenancyPackage.setBandwidthOveruseCharge(Integer.parseInt(bandwidthOveruseCharge));
+
+            multitenancyPackages.add(multitenancyPackage);
+        }
+        return multitenancyPackages;
+    }
+
+    private String getPackageConfigValue(String key, OMElement packageNode) throws StratosException {
+        String qualifiedKey = "ns:" + key.replaceAll("\\.", "/ns:");
+        AXIOMXPath xpathExpression;
+        try {
+            xpathExpression = new AXIOMXPath(qualifiedKey);
+            xpathExpression.addNamespace("ns", PACKAGE_DESCRIPTION_CONFIG_NS);
+            List valueNodes = xpathExpression.selectNodes(packageNode);
+            if (valueNodes.isEmpty()) {
+                if (log.isDebugEnabled()) {
+                    String msg = "No results found parsing package configuration for key: " + 
+                            qualifiedKey + ".";
+                    log.debug(msg);
+                }
+                return null;
+            }
+            OMElement valueNode = (OMElement) valueNodes.get(0);
+            return valueNode.getText();
+        } catch (JaxenException e) {
+            String msg = "Error in retrieving the key: " + qualifiedKey + ".";
+            log.error(msg, e);
+            throw new StratosException(msg, e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/services/PackageInfoService.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/services/PackageInfoService.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/services/PackageInfoService.java
new file mode 100644
index 0000000..52ec2e1
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/services/PackageInfoService.java
@@ -0,0 +1,16 @@
+package org.wso2.carbon.stratos.common.services;
+
+import java.util.List;
+
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.stratos.common.packages.PackageInfo;
+
+public class PackageInfoService {
+
+	public PackageInfo[] getPackageInfos() throws Exception {
+		List<PackageInfo> list = CloudCommonServiceComponent.getPackageInfos().
+		                                                     getMultitenancyPackages();
+		PackageInfo[] packageInfos = list.toArray(new PackageInfo[list.size()]);
+		return packageInfos;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/ClaimsMgtUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/ClaimsMgtUtil.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/ClaimsMgtUtil.java
new file mode 100644
index 0000000..f3e03c7
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/ClaimsMgtUtil.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.wso2.carbon.stratos.common.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.user.core.UserCoreConstants;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.core.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+/*
+ * This class handles the parameters that are input during the registration
+ * which later are
+ * stored as claims.
+ * 
+ * Current claims are:
+ * First Name - GIVEN_NAME
+ * Last Name - SURNAME
+ */
+public class ClaimsMgtUtil {
+
+    private static final Log log = LogFactory.getLog(ClaimsMgtUtil.class);
+
+    /* Methods to get the first and last names from the getNames() */
+    /**
+     * gets first name
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws Exception
+     *             if error in getting the first name
+     */
+    public static String getFirstName(RealmService realmService, int tenantId)throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[0];
+    }
+
+    /**
+     * gets last name
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws Exception
+     *             if error in getting the last name
+     */
+    public static String getLastName(RealmService realmService, int tenantId) throws Exception {
+        String names[] = getNames(realmService, tenantId);
+        return names[1];
+    }
+
+    /**
+     * Gets the first name of a tenant admin to address him/her in the
+     * notifications
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant Id
+     * @return first name / calling name
+     * @throws Exception
+     *             if unable to retrieve the admin name
+     */
+    public static String[] getNames(RealmService realmService, int tenantId) throws Exception {
+        String[] names = new String[2];
+        String firstname = "", lastname = "";
+        try {
+            firstname = getFirstNamefromUserStoreManager(realmService, tenantId);
+        } catch (Exception ignore) {
+            if (log.isDebugEnabled()) {
+                // Not exceptions,due to the existence of tenants with no full name.
+                String msg = "Unable to get the firstname from the user store manager";
+                log.debug(msg, ignore);
+            }
+        }
+        if (firstname != null && !firstname.trim().equals("")) {
+            lastname = getLastNamefromUserStoreManager(realmService, tenantId);
+            if ((lastname != null) && (!lastname.trim().equals(""))) {
+                names[0] = firstname;
+                names[1] = lastname;
+            } else {
+                // no last name - fullname was considered givenname;
+                names = getNamesfromFullName(realmService, firstname);
+            }
+        } else { 
+            // Work around for old tenants - where even full name is not input.
+            if (log.isDebugEnabled()) {
+                log.debug("First name is not available");
+            }
+            try {
+                firstname = getAdminUserNameFromTenantId(realmService, tenantId);
+                names[0] = firstname;
+                names[1] = lastname;
+            } catch (Exception e) {
+                String msg = "Unable to get the admin Name from the user store manager";
+                log.error(msg, e);
+                throw new Exception(msg, e);
+            }
+        }
+        return names;
+    }
+
+    /**
+     * Method to get the name of the admin user given the tenant id
+     * 
+     * @param tenantId
+     *            tenant id
+     * @return admin user name
+     * @throws Exception
+     *             UserStoreException
+     */
+    public static String getAdminUserNameFromTenantId(RealmService realmService, int tenantId)
+                                                                                              throws Exception {
+        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
+            return realmService.getBootstrapRealmConfiguration().getAdminUserName();
+        }
+        String tenantAdminName ="";
+        try {
+            if (realmService.getTenantManager().getTenant(tenantId) != null) {
+                tenantAdminName = realmService.getTenantManager().getTenant(tenantId).getAdminName();
+            }
+        } catch (org.wso2.carbon.user.api.UserStoreException e) {
+            String msg = "Unable to retrieve the admin name for the tenant with the tenant Id: " +
+                         tenantId;
+            log.error(msg, e);
+            throw new Exception(msg, e);
+        }
+        return tenantAdminName;
+    }
+
+    /**
+     * Let's split the givenname into two.
+     * 
+     * @param fullName
+     *            full name of the tenant admin
+     * @return first name
+     */
+    public static String[] getNamesfromFullName(RealmService realmService, String fullName) {
+        String[] names = new String[0];
+
+        if (!fullName.trim().equals("")) {
+            names = fullName.split(" ", 2); // split by space.
+        }
+        return names; // first entry as the calling name.
+    }
+
+    /**
+     * Get the claims from the user store manager
+     * 
+     * @param tenant
+     *            tenant information
+     * @param tenantId
+     *            tenantId
+     * @param claim
+     *            claim name
+     * @return claim value
+     * @throws org.wso2.carbon.user.core.UserStoreException
+     *             exception in getting the user store manager
+     */
+    public static String getClaimfromUserStoreManager(RealmService realmService, int tenantId,
+                                                      String claim) throws UserStoreException {
+        UserStoreManager userStoreManager = null;
+        String claimValue = "";
+        try {
+            if (realmService.getTenantUserRealm(tenantId) != null) {
+                userStoreManager =
+                        (UserStoreManager) realmService.getTenantUserRealm(tenantId)
+                                .getUserStoreManager();
+            }
+
+        } catch (Exception e) {
+            String msg = "Error retrieving the user store manager for the tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+        try {
+            if (userStoreManager != null) {
+                claimValue =
+                        userStoreManager.getUserClaimValue(
+                                getAdminUserNameFromTenantId(realmService, tenantId), claim,
+                                UserCoreConstants.DEFAULT_PROFILE);
+            }
+            return claimValue;
+        } catch (Exception e) {
+            String msg = "Unable to retrieve the claim for the given tenant";
+            log.error(msg, e);
+            throw new UserStoreException(msg, e);
+        }
+    }
+
+    /**
+     * Gets first name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return first name
+     * @throws UserStoreException
+     *             , if error in getting the claim GIVEN_NAME
+     */
+    public static String getFirstNamefromUserStoreManager(RealmService realmService,
+                                                          int tenantId) throws UserStoreException {
+        try {
+            return getClaimfromUserStoreManager(realmService, tenantId,
+                                                UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
+        } catch (Exception e) {
+            String msg = "First Name not found for the tenant";
+            log.debug(msg, e);
+            return ""; // returns empty string
+        }
+    }
+
+    /**
+     * Gets last name from the user store manager
+     * 
+     * @param tenant
+     *            tenant
+     * @param tenantId
+     *            tenant id
+     * @return last name
+     * @throws UserStoreException
+     *             , if error in getting the claim SURNAME
+     */
+    public static String getLastNamefromUserStoreManager(RealmService realmService,
+                                                         int tenantId) throws UserStoreException {
+        String lastname = "";
+        try {
+            lastname = getClaimfromUserStoreManager(realmService, tenantId,
+                                                    UserCoreConstants.ClaimTypeURIs.SURNAME);
+        } catch (Exception e) {
+            String msg = "Last Name not found for the tenant";
+            log.debug(msg, e);
+        }
+        return lastname; // returns empty string, if couldn't get last name from
+                         // userStore manager
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/c1efa393/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CloudServicesUtil.java
----------------------------------------------------------------------
diff --git a/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CloudServicesUtil.java b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CloudServicesUtil.java
new file mode 100644
index 0000000..e8089d2
--- /dev/null
+++ b/components/stratos/org.wso2.carbon.stratos.common/2.1.0/src/main/java/org/wso2/carbon/stratos/common/util/CloudServicesUtil.java
@@ -0,0 +1,182 @@
+package org.wso2.carbon.stratos.common.util;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.stratos.common.config.CloudServiceConfig;
+import org.wso2.carbon.stratos.common.config.CloudServicesDescConfig;
+import org.wso2.carbon.stratos.common.config.PermissionConfig;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.internal.CloudCommonServiceComponent;
+import org.wso2.carbon.registry.core.Collection;
+import org.wso2.carbon.registry.core.RegistryConstants;
+import org.wso2.carbon.registry.core.Resource;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.UserStoreException;
+import org.wso2.carbon.user.mgt.UserMgtConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+public class CloudServicesUtil {
+
+    private static final Log log = LogFactory.getLog(CloudServicesUtil.class);
+    // TODO protect using Java security
+
+    public static void activateAllServices(CloudServicesDescConfig cloudServicesDesc, int tenantId) throws Exception {
+
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                                                                          cloudServicesDesc.getCloudServiceConfigs().
+                                                                                            values();
+        if (cloudServiceConfigList != null) {
+            for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+                if (cloudServiceConfig.isDefaultActive()) {
+                    String cloudServiceName = cloudServiceConfig.getName();
+                    try {
+                        if (!CloudServicesUtil.isCloudServiceActive(cloudServiceName, tenantId)) {
+                            CloudServicesUtil.setCloudServiceActive(true,
+                                                                    cloudServiceName,
+                                                                    tenantId,
+                                                                    cloudServicesDesc.getCloudServiceConfigs().
+                                                                                      get(cloudServiceName));
+                        }
+                    } catch (Exception e) {
+                        String msg = "Error in activating the cloud service at the tenant" +
+                                     "creation. tenant id: " + tenantId + ", service name: " +
+                                     cloudServiceName;
+                        log.error(msg, e);
+                        throw new UserStoreException(msg, e);
+                    }
+                }
+            }
+        }     
+    }
+
+    public static void activateOriginalAndCompulsoryServices(CloudServicesDescConfig cloudServicesDesc,
+                                                             String originalService,
+                                                             int tenantId) throws Exception {
+
+        Map<String, CloudServiceConfig> cloudServiceConfigs =
+                                                              cloudServicesDesc.getCloudServiceConfigs();
+        if (CloudServicesUtil.isServiceNameValid(cloudServicesDesc, originalService)) {
+            if (!CloudServicesUtil.isCloudServiceActive(originalService, tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true, originalService, tenantId,
+                                                        cloudServiceConfigs.get(originalService));
+                log.info("Successfully activated the " + originalService + " for the tenant " +
+                         tenantId);
+            }
+            // register the compulsory services
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_IDENTITY_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_IDENTITY_SERVICE));
+            }
+            if (!CloudServicesUtil.isCloudServiceActive(StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId)) {
+                CloudServicesUtil.setCloudServiceActive(true,
+                                                        StratosConstants.CLOUD_GOVERNANCE_SERVICE,
+                                                        tenantId,
+                                                        cloudServiceConfigs.get(StratosConstants.CLOUD_GOVERNANCE_SERVICE));
+            }
+        } else {
+            log.warn("Unable to activate the " + originalService + " for the tenant " + tenantId);
+        }
+
+    }
+
+    public static void setCloudServiceActive(boolean active,
+                                             String cloudServiceName,
+                                             int tenantId, CloudServiceConfig cloudServiceConfig)
+                                                                                                 throws Exception {
+        if (cloudServiceConfig.getLabel() == null) {
+            // for the non-labled services, we are not setting/unsetting the
+            // service active
+            return;
+        }
+
+        UserRegistry govRegistry =
+                CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                        MultitenantConstants.SUPER_TENANT_ID);
+        UserRegistry configRegistry = CloudCommonServiceComponent.getConfigSystemRegistry(tenantId);
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+        } else {
+            cloudServiceInfoResource = govRegistry.newCollection();
+        }
+        cloudServiceInfoResource.setProperty(StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY,
+                                             active ? "true" : "false");
+        govRegistry.put(cloudServiceInfoPath, cloudServiceInfoResource);
+
+        // then we will copy the permissions
+        List<PermissionConfig> permissionConfigs = cloudServiceConfig.getPermissionConfigs();
+        for (PermissionConfig permissionConfig : permissionConfigs) {
+            String path = permissionConfig.getPath();
+            String name = permissionConfig.getName();
+            if (active) {
+                if (!configRegistry.resourceExists(path)) {
+                    Collection collection = configRegistry.newCollection();
+                    collection.setProperty(UserMgtConstants.DISPLAY_NAME, name);
+                    configRegistry.put(path, collection);
+                }
+            } else {
+                if (configRegistry.resourceExists(path)) {
+                    configRegistry.delete(path);
+                }
+            }
+        }
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId) throws Exception {
+        UserRegistry govRegistry = CloudCommonServiceComponent.getGovernanceSystemRegistry(
+                                                                                           MultitenantConstants.SUPER_TENANT_ID);
+        return isCloudServiceActive(cloudServiceName, tenantId, govRegistry);
+    }
+
+    public static boolean isCloudServiceActive(String cloudServiceName,
+                                               int tenantId, UserRegistry govRegistry)
+                                                                                      throws Exception {
+        // The cloud manager is always active
+        if (StratosConstants.CLOUD_MANAGER_SERVICE.equals(cloudServiceName)) {
+            return true;
+        }
+
+        String cloudServiceInfoPath = StratosConstants.CLOUD_SERVICE_INFO_STORE_PATH +
+                                      RegistryConstants.PATH_SEPARATOR + tenantId +
+                                      RegistryConstants.PATH_SEPARATOR + cloudServiceName;
+        Resource cloudServiceInfoResource;
+        if (govRegistry.resourceExists(cloudServiceInfoPath)) {
+            cloudServiceInfoResource = govRegistry.get(cloudServiceInfoPath);
+            String isActiveStr =
+                                 cloudServiceInfoResource.getProperty(
+                                                         StratosConstants.CLOUD_SERVICE_IS_ACTIVE_PROP_KEY);
+            return "true".equals(isActiveStr);
+        }
+        return false;
+    }
+
+    public static boolean isServiceNameValid(CloudServicesDescConfig cloudServicesDesc,
+                                               String cloudServiceName) {
+        if(cloudServiceName == null) {
+            return false;
+        }
+        java.util.Collection<CloudServiceConfig> cloudServiceConfigList =
+                cloudServicesDesc.getCloudServiceConfigs().values();
+        if (cloudServiceName.equals(StratosConstants.CLOUD_MANAGER_SERVICE)) {
+            return false;
+        }
+        for (CloudServiceConfig cloudServiceConfig : cloudServiceConfigList) {
+            if (cloudServiceConfig.getName().equals(cloudServiceName)) {
+                return true;
+            }
+        }
+        return false;
+    }
+}