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:20 UTC

[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

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>