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:38:03 UTC

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

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);
+        }
+    }
+}