You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by sa...@apache.org on 2013/07/02 11:37:43 UTC

[01/23] Refactoring org.wso2.carbon to org.apache.stratos

Updated Branches:
  refs/heads/master 335eb4188 -> ee2ab7836


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 346b3ca..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 7245a2a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 187c261..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index d30e3f9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 0298c4d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 261f705..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 7c354e4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 71e6e35..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?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/ee2ab783/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
deleted file mode 100644
index 3aaf3de..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,96 +0,0 @@
-<?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>


[09/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index a523b60..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 403938f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- *  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/ee2ab783/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
deleted file mode 100644
index 89cce4c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 04260fd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 68e968e..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 0027f16..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 5530ed1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index e9d760a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index e12d5d2..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 862b1fd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 697ae77..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 8c92238..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index e99f5d7..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 0b9fbf3..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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;
-    }
-}


[12/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 05f3d8b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
+++ /dev/null
@@ -1,2557 +0,0 @@
-/*
- * 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 (SQLExceptio

<TRUNCATED>

[17/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.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.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/get_invoice_by_id_ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/pom.xml b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/pom.xml
new file mode 100644
index 0000000..03fb6c5
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.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>


[07/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 05f3d8b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
+++ /dev/null
@@ -1,2557 +0,0 @@
-/*
- * 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 (SQLExceptio

<TRUNCATED>

[08/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index cadc052..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 0dc39e1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 0990d74..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index d745d8a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 630db9f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 131430f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index ad697e9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index b6a0951..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- *  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);
-        }
-    }
-}


[22/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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;
+    }    
+}


[18/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/pom.xml b/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/pom.xml
new file mode 100644
index 0000000..e2162ab
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.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.apache.stratos.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/clients/BillingServiceClient.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.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.apache.stratos.billing.mgt.ui/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/ui/utils/BillingUtil.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.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.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/JSResources.properties b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.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.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/org/wso2/carbon/billing/mgt/ui/i18n/Resources.properties b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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);
+    }
+
+%>


[05/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 9b4f609..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index af722bd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-config.xml
+++ /dev/null
@@ -1,83 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 1905308..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
+++ /dev/null
@@ -1,15 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index c2fcd09..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3a3f22d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-registration.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3f3b8ea..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/email-update.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3bde368..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 7dc9d8b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 25e09e8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome1/repository/conf/notification.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index abd2f55..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-config.xml
+++ /dev/null
@@ -1,86 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 1905308..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
+++ /dev/null
@@ -1,15 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index c2fcd09..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3a3f22d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-registration.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3f3b8ea..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/email-update.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3bde368..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 0239204..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 25e09e8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/resources/carbonhome2/repository/conf/notification.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index e2162ab..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/pom.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<?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/ee2ab783/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
deleted file mode 100644
index 82b57fe..0000000
--- 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
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 97f4e18..0000000
--- 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
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- *  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/ee2ab783/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
deleted file mode 100644
index 1b8a348..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,100 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index bf90999..0000000
--- 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
+++ /dev/null
@@ -1 +0,0 @@
-empty=To make sure the js properties file is not empty

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 7d0bbbc..0000000
--- 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
+++ /dev/null
@@ -1,52 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index 3821477..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_discount_ajaxprocessor.jsp
+++ /dev/null
@@ -1,66 +0,0 @@
-<%--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 25badd8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_payment-ajaxprocessor.jsp
+++ /dev/null
@@ -1,56 +0,0 @@
-<%--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 987a946..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/add_registration_payment-ajaxprocessor.jsp
+++ /dev/null
@@ -1,79 +0,0 @@
-<%--
- ~ 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);
-    }
-
-%>


[16/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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);
+    }
+
+}


[04/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index d0cc589..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/adjustments.jsp
+++ /dev/null
@@ -1,196 +0,0 @@
-<!--
-~ 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/ee2ab783/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
deleted file mode 100644
index 2ebbe74..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index 62e0509..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/css/billing.css
+++ /dev/null
@@ -1,58 +0,0 @@
-/*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/ee2ab783/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
deleted file mode 100644
index b3ab062..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/discounts.jsp
+++ /dev/null
@@ -1,182 +0,0 @@
-<!--
-~ 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/ee2ab783/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
deleted file mode 100644
index fc710f8..0000000
Binary files a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/add-org.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 333254b..0000000
Binary files a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/billing.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 0c9ff59..0000000
Binary files a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/images/paypal.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index c790c9f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/docs/userguide.html
+++ /dev/null
@@ -1,75 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 0b59e37..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/find_invoices_ajaxprocessor.jsp
+++ /dev/null
@@ -1,47 +0,0 @@
-<%--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 8e6d721..0000000
--- 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
+++ /dev/null
@@ -1,25 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index f21abdb..0000000
Binary files a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/logo.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 47ca2fd..0000000
Binary files a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/images/view-invoice.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 12dda0d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/interim_invoice.jsp
+++ /dev/null
@@ -1,355 +0,0 @@
-<!--
-~ 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/ee2ab783/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
deleted file mode 100644
index f33576c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/make_adjustment_ajaxprocessor.jsp
+++ /dev/null
@@ -1,49 +0,0 @@
-<%--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 67bf09a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/past_invoice.jsp
+++ /dev/null
@@ -1,470 +0,0 @@
-<!--
-~ 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/ee2ab783/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
deleted file mode 100644
index 648086f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/prepare_checkout_ajaxprocessor.jsp
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 53354b8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt.ui/2.1.0/src/main/resources/web/tenant-billing/view_balance.jsp
+++ /dev/null
@@ -1,171 +0,0 @@
-<!--
-~ 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/ee2ab783/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
deleted file mode 100644
index ff01860..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/pom.xml
+++ /dev/null
@@ -1,116 +0,0 @@
-<!--
-# 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>


[21/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/internal/Util.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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);
+        }
+    }
+}


[03/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index cd9b4bd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
+++ /dev/null
@@ -1,201 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index 6486767..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 8b88b99..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 76ff4e6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 994a161..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index ffddda0..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 5490e9f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 87a716c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 68cf24b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackage.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 7245a2a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyPackageSubItem.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index d9c5ef2..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/handlers/MultitenancySubscriptionFeedingHandler.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index d30e3f9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/internal/MultitenancyBillingServiceComponent.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 0298c4d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingDataAccessService.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * 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);
-    }
-
-}


[15/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/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
deleted file mode 100644
index 6bdbdf6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
+++ /dev/null
@@ -1,140 +0,0 @@
-<!--
-# 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/ee2ab783/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
deleted file mode 100644
index 47ebf03..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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";
-}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 4ab16ff..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
+++ /dev/null
@@ -1,462 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 8d97dc1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2aae5a4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2e7e0fc..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index a523b60..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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);
-    }
-}


[19/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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) {
+            }
+        }
+    }
+}


[20/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/DataAccessObject.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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 (SQL

<TRUNCATED>

[14/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 403938f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- *  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/ee2ab783/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
deleted file mode 100644
index 89cce4c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 04260fd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 68e968e..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 0027f16..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingConfiguration.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 5530ed1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/conf/BillingTaskConfiguration.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index e9d760a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Cash.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index cbd1d80..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Customer.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 862b1fd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Discount.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 697ae77..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Invoice.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 66b156b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Item.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index e99f5d7..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Payment.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 0b9fbf3..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/dataobjects/Subscription.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index cadc052..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultFinalizingHandler.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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);
-            }
-        }
-    }
-}


[11/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index bae3df9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 269beb5..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index c589431..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 4eb8cad..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 3d450f9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index fadbb2c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 00e078a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 37df06b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 78ea40d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 500adb5..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 9ddc2d1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/CashTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 6ac08d6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index a5e9bf2..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2cb029f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 54dc574..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 126939f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 395d86b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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) {
-            }
-        }
-    }
-}


[06/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index bae3df9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/jdbc/Transaction.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 269beb5..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingJob.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index c589431..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/BillingScheduler.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 4eb8cad..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/ScheduleHelper.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 3d450f9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/SchedulerContext.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index fadbb2c..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/MonthlyScheduleHelper.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 00e078a..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/scheduler/scheduleHelpers/OneTimeScheduleHelper.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 37df06b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/CustomerUtils.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 78ea40d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/utilities/DataSourceHolder.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 500adb5..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CarbonHome1Test.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 9ddc2d1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/CashTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 6ac08d6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerCalculator.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index a5e9bf2..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/FiveSecondTriggerTester.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2cb029f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/InvoiceMsgTest.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 54dc574..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/MonthlyTriggerCalculatorTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 126939f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/RuleTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 395d86b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/test/java/org/wso2/carbon/billing/test/TestUtils.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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) {
-            }
-        }
-    }
-}


[13/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 0dc39e1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/DefaultSubscriptionFeedingHandler.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 0990d74..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/EmailSendingHandler.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 99fd286..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/InvoiceCalculationHandler.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 630db9f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/RuleHandler.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 131430f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/handlers/SubscriptionTreeBuildingHandler.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index ad697e9..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/BillingServiceComponent.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index b6a0951..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/internal/Util.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- *  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);
-        }
-    }
-}


[02/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 261f705..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 7c354e4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
-*  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/ee2ab783/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
deleted file mode 100644
index 71e6e35..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/component.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?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/ee2ab783/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
deleted file mode 100644
index 3aaf3de..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.0/src/main/resources/META-INF/services.xml
+++ /dev/null
@@ -1,96 +0,0 @@
-<?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/ee2ab783/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
deleted file mode 100644
index 03fb6c5..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/pom.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<!--
-# 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/ee2ab783/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
deleted file mode 100644
index cd9b4bd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/DefaultTenantBilling.java
+++ /dev/null
@@ -1,201 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index eacb0d4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/api/MultitenancyBillingInfo.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 8b88b99..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BilledEntry.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 76ff4e6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/BillingPeriod.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 994a161..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyInvoice.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index ffddda0..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancyPurchaseOrder.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 5490e9f..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/beans/MultitenancySubscription.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 5d8aea6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/dataobjects/MultitenancyCustomer.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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;
-    }
-}


[10/23] Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/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
deleted file mode 100644
index 9b4f609..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/java/org/wso2/carbon/billing/test/TriggerTest.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index af722bd..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-config.xml
+++ /dev/null
@@ -1,83 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 1905308..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/billing-rules1.drl
+++ /dev/null
@@ -1,15 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index c2fcd09..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration-complete.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3a3f22d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-registration.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3f3b8ea..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/email-update.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3bde368..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-billing-rule.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 7dc9d8b..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/multitenancy-packages.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 25e09e8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome1/repository/conf/notification.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index abd2f55..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-config.xml
+++ /dev/null
@@ -1,86 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 1905308..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/billing-rules1.drl
+++ /dev/null
@@ -1,15 +0,0 @@
-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/ee2ab783/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
deleted file mode 100644
index c2fcd09..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration-complete.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3a3f22d..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-registration.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3f3b8ea..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/email-update.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 3bde368..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-billing-rule.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 0239204..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/multitenancy-packages.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index 25e09e8..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/test/resources/carbonhome2/repository/conf/notification.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<!--
- ~ 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/ee2ab783/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
deleted file mode 100644
index e7837b0..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/pom.xml
+++ /dev/null
@@ -1,140 +0,0 @@
-<!--
-# 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/ee2ab783/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
deleted file mode 100644
index 6979f65..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index b6f8265..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
+++ /dev/null
@@ -1,466 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 8d97dc1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2aae5a4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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/ee2ab783/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
deleted file mode 100644
index 2e7e0fc..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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;
-}


[23/23] git commit: Refactoring org.wso2.carbon to org.apache.stratos

Posted by sa...@apache.org.
Refactoring org.wso2.carbon to org.apache.stratos


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

Branch: refs/heads/master
Commit: ee2ab7836875178a94bdc043e871ace2223b278b
Parents: 335eb41
Author: Sajith Kariyawasam <sa...@wso2.com>
Authored: Tue Jul 2 15:07:21 2013 +0530
Committer: Sajith Kariyawasam <sa...@wso2.com>
Committed: Tue Jul 2 15:07:21 2013 +0530

----------------------------------------------------------------------
 .../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 ++
 .../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 +
 .../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 49926 -> 0 bytes
 .../web/tenant-billing/docs/images/billing.png  |  Bin 4264 -> 0 bytes
 .../web/tenant-billing/docs/images/paypal.png   |  Bin 9298 -> 0 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 5977 -> 0 bytes
 .../web/tenant-billing/images/view-invoice.gif  |  Bin 1014 -> 0 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 -
 295 files changed, 14518 insertions(+), 26516 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/pom.xml b/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/pom.xml
new file mode 100644
index 0000000..e7837b0
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingException.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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;
+}

http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingManager.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/BillingTenantMgtListenerImpl.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/DataAccessManager.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/OutstandingBalanceInfoBean.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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/ee2ab783/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.core/2.1.3/src/main/java/org/wso2/carbon/billing/core/beans/PaginatedBalanceInfoBean.java b/components/stratos/billing/org.apache.stratos.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.apache.stratos.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()]);
+    }
+}