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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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