You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stratos.apache.org by sa...@apache.org on 2013/07/02 11:37:57 UTC
[15/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.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
new file mode 100644
index 0000000..261f705
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/services/BillingService.java
@@ -0,0 +1,606 @@
+/*
+* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.services;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.billing.core.BillingConstants;
+import org.wso2.carbon.billing.core.BillingEngine;
+import org.wso2.carbon.billing.core.BillingEngineContext;
+import org.wso2.carbon.billing.core.BillingManager;
+import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
+import org.wso2.carbon.billing.core.beans.PaginatedBalanceInfoBean;
+import org.wso2.carbon.billing.core.dataobjects.*;
+import org.wso2.carbon.billing.mgt.beans.*;
+import org.wso2.carbon.billing.mgt.util.Util;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil;
+import org.wso2.carbon.stratos.common.util.CommonUtil;
+import org.wso2.carbon.core.AbstractAdmin;
+import org.wso2.carbon.registry.core.session.UserRegistry;
+import org.wso2.carbon.user.core.tenant.Tenant;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.utils.DataPaginator;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.text.SimpleDateFormat;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class BillingService extends AbstractAdmin {
+
+ private static final Log log = LogFactory.getLog(BillingService.class);
+
+ /**
+ * Gets the available billing periods of the available invoices for the
+ * current customer. Tenant id is taken from registry
+ * @return an array of BillingPeriod objects
+ * @throws Exception Exception
+ */
+ public BillingPeriod[] getAvailableBillingPeriods() throws Exception {
+ UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+ return getAvailableBillingPeriods(registry);
+ }
+
+ /**
+ * Gets the available billigs dates of a given tenant
+ * @param tenantDomain is the tenant domain
+ * @return an array of BillingPeriods
+ * @throws Exception if an error occurs during the process
+ */
+ public BillingPeriod[] getAvailableBillingPeriodsBySuperTenant(String tenantDomain) throws Exception{
+
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+ List<Customer> customers = billingEngine.getCustomersWithName(tenantDomain);
+ if(customers.size()>0){
+ return getBillingPeriodsFromInvoices(billingEngine.getInvoices(customers.get(0)));
+ }else{
+ return new BillingPeriod[0];
+ }
+ }
+
+ /**
+ * Gets the invoice with a given invoice id
+ * @param invoiceId is the id of the invoice expected
+ * @return a MultitenancyInvoice object
+ * @throws Exception Exception
+ */
+ public MultitenancyInvoice getPastInvoice(int invoiceId) throws Exception {
+ UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+ return getPastInvoiceById(registry, invoiceId);
+ }
+
+ /**
+ * Gets the current invoice (interim invoice) of the current customer.
+ * Tenant id is taken from the registry
+ * @return a MultitenancyInvoice object
+ * @throws Exception Exception
+ */
+ public MultitenancyInvoice getCurrentInvoice() throws Exception {
+ UserRegistry registry = (UserRegistry) getGovernanceUserRegistry();
+ return getCurrentInvoiceOfCustomer(registry);
+ }
+
+ /**
+ * Adds a payment record to the BC_PAYMENT table. Sends a notification email
+ * after adding the record
+ * @param payment is the Payment object which contains the payment record details
+ * @param amount is the paid amount (had to pass this as a string)
+ * @return the payment id for the added record
+ * @throws Exception if an error occurs during the operation
+ */
+ public int addPayment(Payment payment, String amount) throws Exception {
+ int paymentId = addPaymentRecord(payment, amount);
+ if(paymentId>0){
+ payment.setId(paymentId);
+ sendPaymentReceivedEmail(payment);
+ }
+ return paymentId;
+ }
+
+ /**
+ * Adds a payment record to the BC_REGISTRATION_PAYMENT table. Sends a notification email
+ * after adding the record
+ *
+ * @param payment the Payment object which contains the payment record details
+ * @param amount the registration fee paid
+ * @param usagePlan the registered usage plan
+ * @return the payment id for the added record
+ * @throws Exception thrown if an error occurs while adding the record
+ */
+ public int addRegistrationPayment(Payment payment, String amount, String usagePlan)
+ throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ Cash cashAmount = new Cash(amount);
+ payment.setAmount(cashAmount);
+ int paymentId = billingEngine.addRegistrationPayment(payment, usagePlan);
+ if (paymentId > 0) {
+ payment.setId(paymentId);
+ sendRegistrationPaymentReceivedEmail(payment);
+ }
+ return paymentId;
+ }
+
+ /**
+ * Adds a payment record for invoice adjustment purposes
+ * @param payment is the Payment object which contains the adjustment details
+ * @param amount is the adjustment amount (had to pass this as a string)
+ * @return the payment id for the added adjustment record
+ * @throws Exception if an error occurs during the operation
+ */
+ public int makeAdjustment(Payment payment, String amount) throws Exception {
+ return addPaymentRecord(payment, amount);
+ }
+
+ private int addPaymentRecord(Payment payment, String amount) throws Exception{
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ Cash cashAmount = new Cash(amount);
+ payment.setAmount(cashAmount);
+ if(payment.getInvoice()!=null){
+ payment.setSubscriptions(billingEngine.getInvoiceSubscriptions(payment.getInvoice().getId()));
+ }
+ int paymentId = billingEngine.addPayment(payment);
+ return paymentId;
+ }
+
+ /**
+ * Gets the paginated BalanceInfoBean to be shown for the super tenant in the paginated mode
+ * @param pageNumber is the expected page number
+ * @return a PaginatedBalanceInfoBean object
+ * @throws Exception Exception
+ */
+ public PaginatedBalanceInfoBean getPaginatedBalances(int pageNumber) throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalances(null); //no tenant domain
+ PaginatedBalanceInfoBean paginatedBalanceBean = new PaginatedBalanceInfoBean();
+ DataPaginator.doPaging(pageNumber, balanceBeans, paginatedBalanceBean);
+
+ return paginatedBalanceBean;
+ }
+
+ /**
+ * Gets OutstandingBalanceInfo bean(s).
+ * @param tenantDomain is the domain of the expected tenant which the super-tenant
+ * wants to view the balance. If this is null, balance info of all the tenants will be shown
+ * @return an array of OutstandingBalanceInfoBeans
+ * @throws Exception Exception
+ */
+ public OutstandingBalanceInfoBean[] getOutstandingBalance(String tenantDomain) throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ List<OutstandingBalanceInfoBean> balanceBeans = billingEngine.getAllOutstandingBalanceInfoBeans(tenantDomain);
+ return balanceBeans.toArray(new OutstandingBalanceInfoBean[balanceBeans.size()]);
+ }
+
+ /**
+ * Adds a discount entry
+ * @param discount is the discount object which contains discount information
+ * @param tenantDomain is passed to get the tenant id and set to the discount object
+ * @return true or false based on the result of the operation
+ * @throws Exception if an error occurs during the operation
+ */
+ public boolean addDiscount (Discount discount, String tenantDomain) throws Exception {
+ TenantManager tenantManager = Util.getRealmService().getTenantManager();
+ int tenantId = tenantManager.getTenantId(tenantDomain);
+ if(tenantId== MultitenantConstants.INVALID_TENANT_ID){
+ throw new Exception("Invalid tenant domain submitted for a discount");
+ }
+ discount.setTenantId(tenantId);
+
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+ boolean added = billingEngine.addDiscount(discount);
+ if(added){
+ log.info("Discount entry added for tenant: " + discount.getTenantId());
+ }
+ return added;
+ }
+
+ /**
+ * Gets the past invoice for a given invoice id
+ * @param registry is the GovernanceUserRegistry
+ * @param invoiceId is the expected invoice id
+ * @return a MultitenancyInvoice object
+ * @throws Exception Exception
+ */
+ private MultitenancyInvoice getPastInvoiceById(UserRegistry registry,
+ int invoiceId) throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+ Invoice invoice = billingEngine.getInvoice(invoiceId);
+ if (invoice == null) {
+ return null;
+ }
+
+ Customer customer = getCurrentCustomer(registry, billingEngine);
+ if (customer == null || customer.getId() != invoice.getCustomer().getId()) {
+ String msg = "Trying to looking at an invoice of another customer, customer: " +
+ (customer == null ? "unknown" : customer.getId()) + ", invoice: " +
+ invoice.getId() + ".";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+
+ MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+ multitenancyInvoice.setInvoiceId(invoice.getId());
+ multitenancyInvoice.setBillingDate(invoice.getDate());
+ multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+ multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+ multitenancyInvoice.setStartDate(invoice.getStartDate());
+ multitenancyInvoice.setEndDate(invoice.getEndDate());
+ multitenancyInvoice.setTotalCost(invoice.getTotalCost().serializeToString());
+ multitenancyInvoice.setTotalPayments(invoice.getTotalPayment().serializeToString());
+
+ List<Subscription> subscriptions = invoice.getSubscriptions();
+ MultitenancySubscription[] multitenancySubscriptions =
+ new MultitenancySubscription[subscriptions.size()];
+ for (int i = 0; i < subscriptions.size(); i++) {
+ Subscription subscription = subscriptions.get(i);
+ MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+ multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+ multitenancySubscription.setActiveSince(subscription.getActiveSince());
+ multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+ multitenancySubscription.setActive(subscription.isActive());
+
+ // now iterating the items
+ List<Item> billedItems = billingEngine.getBilledItems(subscription);
+ BilledEntry[] itemEntries = new BilledEntry[billedItems.size()];
+ for (int j = 0; j < billedItems.size(); j++) {
+ Item billedItem = billedItems.get(j);
+ if (billedItem.getName().equals(multitenancySubscription.getSubscribedPackage())) {
+ // ignoring the parent item..
+ continue;
+ }
+ BilledEntry itemEntry = new BilledEntry();
+ itemEntry.setName(billedItem.getDescription());
+ itemEntry.setCost(billedItem.getCost().serializeToString());
+ itemEntries[j] = itemEntry;
+ }
+ multitenancySubscription.setBilledEntries(itemEntries);
+ multitenancySubscriptions[i] = multitenancySubscription;
+ }
+
+ multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+ // getting the purchase orders
+ List<Payment> payments = invoice.getPayments();
+ if (payments != null) {
+ MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+ new MultitenancyPurchaseOrder[payments.size()];
+
+ for (int i = 0; i < payments.size(); i++) {
+ Payment payment = payments.get(i);
+ MultitenancyPurchaseOrder multitenancyPurchaseOrder =
+ new MultitenancyPurchaseOrder();
+
+ multitenancyPurchaseOrder.setId(payment.getId());
+ multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+ multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+ multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+ multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+ }
+ multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+ }
+
+ return multitenancyInvoice;
+ }
+
+ /**
+ * Gets the interim invoice of the current customer
+ * @param registry is the GovernanceUserRegistry
+ * @return an MultiTenancyInvoice object
+ * @throws Exception Exception
+ */
+ private MultitenancyInvoice getCurrentInvoiceOfCustomer(UserRegistry registry) throws Exception {
+ // we have to generate the invoice for this.
+
+
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngineViewer =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ Customer customer = getCurrentCustomer(registry, billingEngineViewer);
+ if (customer == null) {
+ // no customer => no invoices
+ return null;
+ }
+
+ BillingEngineContext billingEngineContext = new BillingEngineContext();
+ billingEngineContext.setCustomer(customer);
+ billingEngineViewer.generateBill(billingEngineContext);
+
+ // reloading the customer with new updates
+ customer = billingEngineContext.getCustomer();
+ Invoice invoice = customer.getActiveInvoice();
+
+ // convert it and return
+ if (invoice == null) {
+ return null;
+ }
+
+ if (customer.getId() != invoice.getCustomer().getId()) {
+ String msg = "Trying to looking at an invoice of another customer, customer: " +
+ customer.getId() + ", invoice: " + invoice.getId() + ".";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+
+ MultitenancyInvoice multitenancyInvoice = new MultitenancyInvoice();
+ multitenancyInvoice.setBillingDate(invoice.getDate());
+ multitenancyInvoice.setBoughtForward(invoice.getBoughtForward().serializeToString());
+ multitenancyInvoice.setCarriedForward(invoice.getCarriedForward().serializeToString());
+ multitenancyInvoice.setEndDate(invoice.getEndDate());
+ multitenancyInvoice.setInvoiceId(invoice.getId());
+ multitenancyInvoice.setStartDate(invoice.getStartDate());
+
+ // getting the purchase orders
+ List<Payment> payments = invoice.getPayments();
+ MultitenancyPurchaseOrder[] multitenancyPurchaseOrders =
+ new MultitenancyPurchaseOrder[payments.size()];
+ for (int i = 0; i < payments.size(); i++) {
+ Payment payment = payments.get(i);
+ MultitenancyPurchaseOrder multitenancyPurchaseOrder = new MultitenancyPurchaseOrder();
+ multitenancyPurchaseOrder.setId(payment.getId());
+ multitenancyPurchaseOrder.setPaymentDate(payment.getDate());
+ multitenancyPurchaseOrder.setPayment(payment.getAmount().serializeToString());
+ multitenancyPurchaseOrder.setTransactionId(payment.getDescription());
+ multitenancyPurchaseOrders[i] = multitenancyPurchaseOrder;
+ }
+ multitenancyInvoice.setPurchaseOrders(multitenancyPurchaseOrders);
+
+ List<Subscription> subscriptions = invoice.getSubscriptions();
+ MultitenancySubscription[] multitenancySubscriptions =
+ new MultitenancySubscription[subscriptions.size()];
+ for (int i = 0; i < subscriptions.size(); i++) {
+ Subscription subscription = subscriptions.get(i);
+ MultitenancySubscription multitenancySubscription = new MultitenancySubscription();
+ multitenancySubscription.setSubscribedPackage(subscription.getItem().getName());
+ multitenancySubscription.setActiveSince(subscription.getActiveSince());
+ multitenancySubscription.setActiveUntil(subscription.getActiveUntil());
+ multitenancySubscription.setActive(subscription.isActive());
+
+ BilledEntry[] itemEntries;
+ List<? extends Item> subItems = subscription.getItem().getChildren();
+ if(subItems!=null){
+ itemEntries = new BilledEntry[subItems.size()];
+ for(int j=0; j<subItems.size(); j++){
+ BilledEntry billedEntry = new BilledEntry();
+ Item billedItem = subItems.get(j);
+ billedEntry.setName(billedItem.getDescription()); //description
+ if(billedItem.getCost()!=null){
+ billedEntry.setCost(billedItem.getCost().toString()); //cost
+ }else{
+ billedEntry.setCost(new Cash("$0").toString());
+ }
+ itemEntries[j] = billedEntry;
+ }
+ }else{
+ itemEntries = new BilledEntry[0];
+ }
+
+
+ multitenancySubscription.setBilledEntries(itemEntries);
+ multitenancySubscriptions[i] = multitenancySubscription;
+ }
+ multitenancyInvoice.setSubscriptions(multitenancySubscriptions);
+
+ Cash totalCost = invoice.getTotalCost();
+ if (totalCost == null) {
+ totalCost = new Cash("$0");
+ }
+ multitenancyInvoice.setTotalCost(totalCost.serializeToString());
+
+ Cash totalPaymentCash = invoice.getTotalPayment();
+ if (totalPaymentCash == null) {
+ totalPaymentCash = new Cash("$0");
+ }
+ multitenancyInvoice.setTotalPayments(totalPaymentCash.serializeToString());
+
+ return multitenancyInvoice;
+ }
+
+ /**
+ * Gets the tenant is and then fills the customer details
+ * @param userRegistry to get the tenant id
+ * @param billingEngine to fill the customer details
+ * @return a customer object
+ * @throws Exception Exception
+ */
+ private Customer getCurrentCustomer(UserRegistry userRegistry,
+ BillingEngine billingEngine) throws Exception {
+ int currentTenantId = userRegistry.getTenantId();
+ TenantManager tenantManger = Util.getRealmService().getTenantManager();
+ Tenant currentTenant = (Tenant) tenantManger.getTenant(currentTenantId);
+
+ List<Customer> customers = billingEngine.getCustomersWithName(currentTenant.getDomain());
+ if (customers == null || customers.isEmpty()) {
+ return null;
+ }
+ return customers.get(0);
+ }
+
+ private BillingPeriod[] getAvailableBillingPeriods(UserRegistry registry) throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+ Customer customer = getCurrentCustomer(registry, billingEngine);
+ if (customer == null) {
+ return new BillingPeriod[0];
+ }
+
+ List<Invoice> invoices = billingEngine.getInvoices(customer);
+ if (invoices == null || invoices.size() == 0) {
+ return new BillingPeriod[0];
+ }
+
+ return getBillingPeriodsFromInvoices(invoices);
+ }
+
+ /**
+ * Get the billing period details when given the invoices
+ * @param invoices is list of invoices
+ * @return an array of billing periods
+ */
+ private BillingPeriod[] getBillingPeriodsFromInvoices(List<Invoice> invoices){
+ BillingPeriod[] billingPeriods = new BillingPeriod[invoices.size()];
+ int index = 0;
+ for (Invoice invoice : invoices) {
+ BillingPeriod billingPeriod = new BillingPeriod();
+ billingPeriod.setInvoiceId(invoice.getId());
+ billingPeriod.setStartDate(invoice.getStartDate());
+ billingPeriod.setEndDate(invoice.getEndDate());
+ billingPeriod.setInvoiceDate(invoice.getDate());
+ billingPeriods[index++] = billingPeriod;
+ }
+ return billingPeriods;
+ }
+
+ /**
+ * Sends the payment received email to the customer
+ * @param payment is the payment object with the payment details
+ * @throws Exception Exception
+ */
+ private void sendPaymentReceivedEmail(Payment payment) throws Exception{
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+ if(payment.getInvoice()!=null){
+ Invoice invoice = billingEngine.getInvoice(payment.getInvoice().getId());
+ if(invoice!=null){
+ Customer customer = invoice.getCustomer();
+ if(customer!=null){
+ Map<String, String> mailParameters = new HashMap<String, String>();
+ mailParameters.put("date",
+ new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+ mailParameters.put("transaction-id", payment.getDescription());
+ mailParameters.put("amount", payment.getAmount().toString());
+ mailParameters.put("invoice-id", String.valueOf(payment.getInvoice().getId()));
+
+ try{
+ String customerName =
+ ClaimsMgtUtil.getFirstName(Util.getRealmService(), customer.getId());
+ if(customerName!=null){
+ mailParameters.put("customer-name", customerName);
+ }else{
+ mailParameters.put("customer-name", "");
+ }
+
+ }catch(Exception e){
+ log.error("Could not get tenant information for tenant: " +
+ customer.getName() + "\n" + e.getMessage());
+ mailParameters.put("customer-name", "");
+ }
+
+ //sending the mail to the customer
+ billingEngine.sendPaymentReceivedEmail(
+ customer.getEmail(),
+ BillingConstants.PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+ mailParameters);
+
+ String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+ //customer's first name is not important to finance team. Therefore it is
+ //being replace with the domain name
+ mailParameters.put("customer-name", customer.getName());
+ billingEngine.sendPaymentReceivedEmail(
+ financeEmail,
+ BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+ mailParameters
+ );
+ }else{
+ String msg = "Cannot send email to customer. Customer details not available";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+ }else{
+ String msg = "Cannot send email to customer. Invoice details not available";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+ }else{
+ String msg = "Cannot send email to customer. Invoice Id is not available";
+ log.error(msg);
+ throw new Exception(msg);
+ }
+ }
+
+
+ private void sendRegistrationPaymentReceivedEmail(Payment payment) throws Exception {
+ BillingManager billingManager = Util.getBillingManager();
+ BillingEngine billingEngine = billingManager.getBillingEngine(StratosConstants.MULTITENANCY_VIEWING_TASK_ID);
+
+ String tenantDomain = payment.getDescription().split(" ")[0];
+ int tenantId = Util.getTenantManager().getTenantId(tenantDomain);
+ Tenant tenant = (Tenant) Util.getTenantManager().getTenant(tenantId);
+
+ Map<String, String> mailParameters = new HashMap<String, String>();
+ mailParameters.put("date", new SimpleDateFormat("dd-MMM-yyyy").format(payment.getDate()));
+ mailParameters.put("transaction-id", payment.getDescription().split(" ")[1]);
+ mailParameters.put("amount", payment.getAmount().toString());
+ mailParameters.put("invoice-id", "Registration - " + tenantDomain);
+ mailParameters.put("tenant-domain", tenantDomain);
+
+ String customerName = null;
+ String customerEmail = tenant.getEmail();
+ try {
+ customerName = ClaimsMgtUtil.getFirstName(Util.getRealmService(), tenantId);
+ if (customerName != null) {
+ mailParameters.put("customer-name", customerName);
+ } else {
+ mailParameters.put("customer-name", "");
+ }
+
+ } catch (Exception e) {
+ log.error("Could not get tenant information for tenant: " +
+ customerName + "\n" + e.getMessage());
+ mailParameters.put("customer-name", "");
+ }
+
+ //sending the mail to the customer
+ billingEngine.sendPaymentReceivedEmail(
+ customerEmail,
+ BillingConstants.REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE,
+ mailParameters);
+
+ String financeEmail = CommonUtil.getStratosConfig().getFinanceNotificationEmail();
+ //customer's first name is not important to finance team. Therefore it is
+ //being replace with the domain name
+ mailParameters.put("customer-name", customerName);
+ billingEngine.sendPaymentReceivedEmail(
+ financeEmail,
+ BillingConstants.PAYMENT_RECEIVED_EMAIL_WSO2_FILE,
+ mailParameters
+ );
+
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
new file mode 100644
index 0000000..7c354e4
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/java/org/wso2/carbon/billing/mgt/util/Util.java
@@ -0,0 +1,173 @@
+/*
+* Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.billing.mgt.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.util.tracker.ServiceTracker;
+import org.wso2.carbon.billing.core.*;
+import org.wso2.carbon.billing.mgt.api.DefaultTenantBilling;
+import org.wso2.carbon.billing.mgt.api.MultitenancyBillingInfo;
+import org.wso2.carbon.billing.mgt.handlers.MultitenancySubscriptionFeedingHandler;
+import org.wso2.carbon.stratos.common.TenantBillingService;
+import org.wso2.carbon.stratos.common.constants.StratosConstants;
+import org.wso2.carbon.registry.core.service.RegistryService;
+import org.wso2.carbon.usage.api.TenantUsageRetriever;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+import org.wso2.carbon.throttling.agent.ThrottlingAgent;
+import org.wso2.carbon.utils.ConfigurationContextService;
+
+public class Util {
+ private static BillingManager billingManager = null;
+ private static DataAccessManager dataAccessManager = null;
+ private static RegistryService registryService;
+ private static RealmService realmService;
+ private static TenantUsageRetriever tenantUsageRetriever;
+ private static MultitenancyBillingInfo billingInfo;
+
+ public static ConfigurationContextService getContextService() {
+ return contextService;
+ }
+
+ public static void setContextService(ConfigurationContextService contextService) {
+ Util.contextService = contextService;
+ }
+
+ private static ServiceTracker throttlingRuleInvokerTracker = null;
+ private static BundleContext bundleContext;
+ private static Log log = LogFactory.getLog(Util.class);
+ private static ConfigurationContextService contextService;
+
+ public static synchronized void setRegistryService(RegistryService service) {
+ if (registryService == null) {
+ registryService = service;
+ }
+ }
+
+ public static synchronized void setRealmService(RealmService service) {
+ if (realmService == null) {
+ realmService = service;
+ }
+ }
+
+ public static void setTenantUsageRetriever(TenantUsageRetriever tenantUsageRetriever) {
+ Util.tenantUsageRetriever = tenantUsageRetriever;
+ }
+
+ public static RealmService getRealmService() {
+ return realmService;
+ }
+
+ public static RegistryService getRegistryService() {
+ return registryService;
+ }
+
+ public static TenantUsageRetriever getTenantUsageRetriever() {
+ return tenantUsageRetriever;
+ }
+
+ public static TenantManager getTenantManager() {
+ if (realmService == null) {
+ return null;
+ }
+ return realmService.getTenantManager();
+ }
+
+ public static BillingManager getBillingManager() {
+ return billingManager;
+ }
+
+ public static void setBillingManager(BillingManager billingManager) {
+ Util.billingManager = billingManager;
+ }
+
+ public static void registerSubscriptionFeedingHandlers(BundleContext bundleContext) {
+ bundleContext.registerService(BillingHandler.class.getName(),
+ new MultitenancySubscriptionFeedingHandler(), null);
+ }
+
+ public static void registerTenantBillingService(BundleContext bundleContext) {
+ bundleContext.registerService(TenantBillingService.class.getName(),
+ new DefaultTenantBilling(), null);
+ }
+
+ public static void scheduleBilling() throws BillingException {
+ BillingEngine billingEngine =
+ billingManager.getBillingEngine(StratosConstants.MULTITENANCY_SCHEDULED_TASK_ID);
+ if (billingEngine != null) {
+ billingEngine.scheduleBilling();
+ } else {
+ log.info("No billing engine for scheduled tasks");
+ }
+
+ }
+
+ public static void registerBillingInfo(BundleContext bundleContext) throws Exception {
+ billingInfo = new MultitenancyBillingInfo();
+ bundleContext.registerService(MultitenancyBillingInfo.class.getName(), billingInfo, null);
+ }
+
+ public static MultitenancyBillingInfo getMultitenancyBillingInfo() {
+ return billingInfo;
+ }
+
+ public static DataAccessManager getDataAccessManager() {
+ return dataAccessManager;
+ }
+
+ public static void setDataAccessManager(DataAccessManager dataAccessManager) {
+ Util.dataAccessManager = dataAccessManager;
+ }
+
+ public static void initDataAccessManager() {
+ DataAccessManager dataAccessManager = new DataAccessManager(
+ billingManager.getBillingConfiguration().getDataSource());
+ Util.dataAccessManager = dataAccessManager;
+ }
+
+ /**
+ * This method used to create service tracker that tracks throttlingAgent service which
+ * registered when throttling agent starts
+ *
+ * @param bundleContext bundle context that belongs to component
+ */
+ public static void initializeThrottling(BundleContext bundleContext) {
+ throttlingRuleInvokerTracker = new ServiceTracker(bundleContext, ThrottlingAgent.class.getName(),
+ null);
+ throttlingRuleInvokerTracker.open();
+ }
+
+ /**
+ * This method updates the throttling rules for given tenant and update the cache at manager
+ *
+ * @param tenantId Tenant Id of the tenant that need to update throttling rules at manager
+ */
+ public static void executeThrottlingRules(int tenantId) {
+ try {
+ ThrottlingAgent embeddedRuleInvoker =
+ (ThrottlingAgent) throttlingRuleInvokerTracker.getService();
+ if (embeddedRuleInvoker != null) {
+ embeddedRuleInvoker.executeThrottlingRules(tenantId);
+ }
+ } catch (Exception e) {
+ log.error("Error in executing throttling rules in manager" + e.toString());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
new file mode 100644
index 0000000..71e6e35
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/component.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<component xmlns="http://products.wso2.org/carbon">
+ <ManagementPermissions>
+ <ManagementPermission>
+ <DisplayName>Billing</DisplayName>
+ <ResourceId>/permission/admin/billing</ResourceId>
+ </ManagementPermission>
+ <ManagementPermission>
+ <DisplayName>View Invoice</DisplayName>
+ <ResourceId>/permission/admin/billing/invoice</ResourceId>
+ </ManagementPermission>
+ </ManagementPermissions>
+</component>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
new file mode 100644
index 0000000..3aaf3de
--- /dev/null
+++ b/components/stratos/billing/org.apache.stratos.billing.mgt/2.1.3/src/main/resources/META-INF/services.xml
@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+ <!--
+ ! ! Copyright 2006 The Apache Software Foundation. ! ! Licensed under
+ the Apache License, Version 2.0 (the "License"); ! you may not use
+ this file except in compliance with the License. ! You may obtain a
+ copy of the License at ! ! http://www.apache.org/licenses/LICENSE-2.0
+ ! ! Unless required by applicable law or agreed to in writing,
+ software ! distributed under the License is distributed on an "AS IS"
+ BASIS, ! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ or implied. ! See the License for the specific language governing
+ permissions and ! limitations under the License. !
+ -->
+<serviceGroup>
+
+ <service name="MultitenancyBillingService" scope="transportsession">
+ <transports>
+ <transport>https</transport>
+ </transports>
+
+ <parameter name="ServiceClass" locked="false">
+ org.wso2.carbon.billing.mgt.services.BillingService
+ </parameter>
+
+ <parameter name="adminService" locked="true">true</parameter>
+
+ <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+ <operation name="getPaginatedBalances">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="getOutstandingBalance">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="getAvailableBillingPeriodsBySuperTenant">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="makeAdjustment">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="addRegistrationPayment">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+ </service>
+
+ <service name="BillingDataAccessService" scope="transportsession">
+ <parameter name="AuthorizationAction" locked="true">/permission/admin/billing/invoice</parameter>
+
+ <transports>
+ <transport>https</transport>
+ </transports>
+
+ <parameter name="ServiceClass" locked="false">
+ org.wso2.carbon.billing.mgt.services.BillingDataAccessService
+ </parameter>
+
+ <parameter name="adminService" locked="true">true</parameter>
+
+ <operation name="changeSubscriptionBySuperTenant">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="deactivateActiveSubscriptionBySuperTenant">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="getActiveSubscriptionOfCustomerBySuperTenant">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="addSubscription">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="getSubscription">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="getInactiveSubscriptionsOfCustomer">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="activateSubscription">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+
+ <operation name="changeSubscriptionForTenant">
+ <parameter name="superTenantService" locked="true">true</parameter>
+ </operation>
+ </service>
+
+ <parameter name="hiddenService" locked="true">true</parameter>
+</serviceGroup>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
deleted file mode 100644
index 6bdbdf6..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/pom.xml
+++ /dev/null
@@ -1,140 +0,0 @@
-<!--
-# Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <parent>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>billing-parent</artifactId>
- <version>2.1.0</version>
-<relativePath>../../pom.xml</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.billing.core</artifactId>
- <version>2.1.0</version>
- <packaging>bundle</packaging>
- <name>WSO2 Carbon - Billing Core</name>
-
- <build>
-
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-scr-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
-
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- <Bundle-Name>${project.artifactId}</Bundle-Name>
- <Export-Package>
- org.wso2.carbon.billing.core.*,
- </Export-Package>
- <!--<Require-Bundle>
- drools;visibility:=reexport
- </Require-Bundle>-->
- <Import-Package>
- org.wso2.carbon.rule.*,
- org.wso2.carbon.email.sender.api,
- org.quartz.*; version=2.1.1,
- org.apache.synapse.task.*,
- org.wso2.carbon.registry.core.*;version=1.0.1,
- org.wso2.carbon.registry.resource.*,
- !javax.xml.namespace,
- javax.xml.namespace; version=0.0.0,
- javax.servlet;version="${imp.pkg.version.javax.servlet}",
- javax.servlet.http;version="${imp.pkg.version.javax.servlet}",
- org.apache.axiom.*; version="${axiom.osgi.version.range}",
- *;resolution:=optional
- </Import-Package>
- <DynamicImport-Package>*</DynamicImport-Package>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <inherited>true</inherited>
- <configuration>
- <forkMode>pertest</forkMode>
- <argLine>-enableassertions</argLine>
- <testFailureIgnore>false</testFailureIgnore>
- <excludes>
- <exclude>**/CashTest.java</exclude>
- <exclude>**/MonthlyTriggerCalculatorTest.java</exclude>
- <exclude>**/RuleTest.java</exclude>
- <exclude>**/CarbonHome1Test.java</exclude>
- <exclude>**/InvoiceMsgTest.java</exclude>
- <exclude>**/TestUtils.java</exclude>
- <exclude>**/TriggerTest.java</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.email.sender</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.registry.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.user.core</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.synapse</groupId>
- <artifactId>synapse-tasks</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.rule.kernel</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.rule.common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.rule.backend</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.stratos.common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.ndatasource.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.wso2.carbon</groupId>
- <artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId>
- </dependency>
- </dependencies>
-</project>
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
deleted file mode 100644
index 47ebf03..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingConstants.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-public class BillingConstants {
- public static final String GROUP_ID = "BillingTasks";
- public static final String TASK_NAME_KEY = "taskName";
- public static final String SCHEDULER_KEY = "scheduler";
- public static final String SCHEDULER_CONTEXT = "schedulerContext";
- public static final String BILLING_ENGINE_KEY = "billingEngine";
- public static final String BILLING_CONFIG = "billing-config.xml";
- public static final String CONFIG_NS = "http://wso2.com/carbon/multitenancy/billing/config";
- public static final String TRIGGER_CALCULATOR_CLASS_ATTR = "scheduleHelperClass";
- public static final String TRIGGER_CALCULATOR_SERVICE_ATTR = "scheduleHelperService";
- public static final String SCHEDULE_CONF_KEY = "schedule";
- public static final String SCHEDULE_CONF_PARAM_KEY = "parameter";
- public static final String SCHEDULE_CONF_PARAM_NAME_KEY = "name";
- public static final String HANDLER = "handler";
- public static final String HANDLERS = "handlers";
- public static final String HANDLER_CLASS_ATTR = "class";
- public static final String HANDLER_SERVICE_ATTR = "service";
- public static final String SUBSCRIPTION_FILTER_KEY = "subscriptionFilter";
- public static final String DB_CONFIG = "dbConfig";
- public static final String TASKS = "tasks";
- public static final String ATTR_ID = "id";
- public static final String NS_PREFIX = "";
- public static final String DBCONFIG_VALIDATION_QUERY = "validationQuery";
- public static final String DBCONFIG_MAX_WAIT = "maxWait";
- public static final String DBCONFIG_MIN_IDLE = "minIdle";
- public static final String DBCONFIG_MAX_ACTIVE = "maxActive";
- public static final String DBCONFIG_DRIVER_NAME = "driverName";
- public static final String DBCONFIG_PASSWORD = "password";
- public static final String DBCONFIG_USER_NAME = "userName";
- public static final String DBCONFIG_URL = "url";
- public static final String SUBSCRIPTION_SUBITEM = "subscription";
- public static final String BANDWIDTH_SUBITEM = "bwOveruse";
- public static final String STORAGE_SUBITEM = "storageOveruse";
- public static final String PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-payment-received-customer.xml";
- public static final String REGISTRATION_PAYMENT_RECEIVED_EMAIL_CUSTOMER_FILE = "email-registration-payment-received-customer.xml";
- public static final String PAYMENT_RECEIVED_EMAIL_WSO2_FILE = "email-payment-received-wso2.xml";
- public static final String WSO2_BILLING_DS = "WSO2BillingDS";
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
deleted file mode 100644
index 4ab16ff..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngine.java
+++ /dev/null
@@ -1,462 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.billing.core.beans.OutstandingBalanceInfoBean;
-import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
-import org.wso2.carbon.billing.core.dataobjects.*;
-import org.wso2.carbon.billing.core.internal.Util;
-import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
-import org.wso2.carbon.billing.core.scheduler.BillingScheduler;
-import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
-import org.wso2.carbon.billing.core.utilities.CustomerUtils;
-import org.wso2.carbon.email.sender.api.EmailSender;
-import org.wso2.carbon.email.sender.api.EmailSenderConfiguration;
-import org.wso2.carbon.stratos.common.constants.StratosConstants;
-import org.wso2.carbon.user.api.Tenant;
-import org.wso2.carbon.user.api.TenantManager;
-import org.wso2.carbon.utils.CarbonUtils;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Billing engine work on billing per a seller
- */
-public class BillingEngine {
-
- private static Log log = LogFactory.getLog(BillingEngine.class);
- private BillingTaskConfiguration billingTaskConfig;
- BillingScheduler billingScheduler;
- DataAccessObject dataAccessObject;
-
- public BillingEngine(BillingTaskConfiguration billingTaskConfig,
- DataAccessObject dataAccessObject) {
- this.billingTaskConfig = billingTaskConfig;
- billingScheduler = new BillingScheduler(this, billingTaskConfig);
- this.dataAccessObject = dataAccessObject;
- }
-
- public void scheduleBilling() throws BillingException {
- // the logic to schedule the billing
- SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
- billingScheduler.scheduleNextCycle(schedulerContext);
- }
-
- public void generateBill() throws BillingException {
- BillingEngineContext billingEngineContext = new BillingEngineContext();
- generateBill(billingEngineContext);
- }
-
- public void generateBill(SchedulerContext schedulerContext) throws BillingException {
- BillingEngineContext billingEngineContext = new BillingEngineContext();
- billingEngineContext.setSchedulerContext(schedulerContext);
- generateBill(billingEngineContext);
- }
-
- public void generateBill(BillingEngineContext billingEngineContext) throws BillingException {
-
- try {
- beginTransaction();
- if (billingEngineContext.getSchedulerContext() == null) {
- SchedulerContext schedulerContext = billingScheduler.createScheduleContext();
- billingEngineContext.setSchedulerContext(schedulerContext);
- }
-
- billingEngineContext.setTaskConfiguration(billingTaskConfig);
-
- // now iterator through all the handlers
- List<BillingHandler> handlers = billingTaskConfig.getBillingHandlers();
- for (BillingHandler handler : handlers) {
- handler.execute(billingEngineContext);
- }
- //commit transaction
- commitTransaction();
- }catch (Exception e){
- String msg = "Error occurred while generating the bill:" + e.getMessage();
- log.error(msg);
- //rollback transaction
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
-
- }
-
- public void beginTransaction() throws BillingException {
- dataAccessObject.beginTransaction();
- }
-
- public void commitTransaction() throws BillingException {
- dataAccessObject.commitTransaction();
- }
-
- public void rollbackTransaction() throws BillingException {
- dataAccessObject.rollbackTransaction();
- }
-
- public List<Item> getItemsWithName(String itemName) throws BillingException {
- List<Item> items;
- try {
- beginTransaction();
- items = dataAccessObject.getItemsWithName(itemName);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting item with name: " + itemName +
- " " + e.getMessage();
- log.error(msg);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return items;
- }
-
- public int addItem(Item item) throws BillingException {
- int itemId = 0;
- try {
- beginTransaction();
- itemId = dataAccessObject.addItem(item);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while adding item: " + item.getName() +
- " " + e.getMessage();
- log.error(msg);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return itemId;
- }
-
- public Item getItem(int itemId) throws BillingException {
- Item item;
- try {
- beginTransaction();
- item = dataAccessObject.getItem(itemId);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting item with id: " + itemId +
- " " + e.getMessage();
- log.error(msg);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return item;
- }
-
- public List<Customer> getCustomersWithName(String customerName) throws BillingException {
- TenantManager tenantManager = Util.getRealmService().getTenantManager();
- List<Customer> customers = new ArrayList<Customer>();
- try{
- int tenantId = tenantManager.getTenantId(customerName);
- Tenant tenant = tenantManager.getTenant(tenantId);
- if(tenant!=null){
- Customer customer = new Customer();
- customer.setId(tenant.getId());
- customer.setName(tenant.getDomain());
- customer.setStartedDate(tenant.getCreatedDate());
- customer.setEmail(tenant.getEmail());
- //customer.setAddress();
- customers.add(customer);
- }
- }catch(Exception e){
- String msg = "Failed to get customers for customers: " + customerName + ".";
- log.error(msg, e);
- throw new BillingException(msg, e);
- }
-
- return customers;
- }
-
- public int addSubscription(Subscription subscription) throws BillingException {
- int subscriptionId = 0;
- try {
- beginTransaction();
- subscriptionId =
- dataAccessObject.addSubscription(subscription,
- subscription.getSubscriptionPlan());
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while adding subscription: " + subscription.getSubscriptionPlan()+
- " for the customer " + subscription.getCustomer().getName() + " " + e.getMessage() ;
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return subscriptionId;
- }
-
- public int addPayment(Payment payment) throws BillingException {
- int paymentId = 0;
- try {
- beginTransaction();
- paymentId = dataAccessObject.addPayment(payment);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while adding payment record (transaction id): " + payment.getDescription() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return paymentId;
- }
-
- public int addRegistrationPayment(Payment payment, String usagePlan) throws BillingException {
- int paymentId = 0;
- try {
- beginTransaction();
- paymentId = dataAccessObject.addRegistrationPayment(payment, usagePlan);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while adding registration payment record (transaction id): " + payment.getDescription() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return paymentId;
- }
-
- public Invoice getLastInvoice(Customer customer) throws BillingException {
- Invoice invoice = null;
- try {
- beginTransaction();
- invoice = dataAccessObject.getLastInvoice(customer);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting last invoice for customer: " + customer.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return invoice;
- }
-
- public List<Invoice> getAllInvoices(Customer customer) throws BillingException {
- List<Invoice> invoices = null;
- try {
- beginTransaction();
- invoices = dataAccessObject.getAllInvoices(customer);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting all invoices for customer: " + customer.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return invoices;
- }
-
- public List<Subscription> getActiveSubscriptions(Customer customer) throws BillingException {
- List<Subscription> subscriptions;
- try {
- beginTransaction();
- subscriptions =
- dataAccessObject.getFilteredActiveSubscriptionsForCustomer(
- null, customer);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting active subscriptions for customer: " + customer.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return subscriptions;
- }
-
- public Subscription getActiveSubscriptionOfCustomer(int customerId) throws BillingException {
- Subscription subscription;
- try {
- beginTransaction();
- subscription =
- dataAccessObject.getActiveSubscriptionOfCustomer(customerId);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting active subscription for customer: " + customerId +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return subscription;
- }
-
- public List<Invoice> getInvoices(Customer customer) throws BillingException {
- List<Invoice> invoices;
- try {
- beginTransaction();
- invoices = dataAccessObject.getInvoices(customer);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting invoices for customer: " + customer.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return invoices;
- }
-
- public Invoice getInvoice(int invoiceId) throws BillingException {
- Invoice invoice = null;
- try {
- beginTransaction();
- invoice = dataAccessObject.getInvoice(invoiceId);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting invoice with id: " + invoiceId +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return invoice;
- }
-
- public List<Item> getBilledItems(Subscription subscription) throws BillingException {
- List<Item> billedItems;
- try {
- beginTransaction();
- billedItems = dataAccessObject.getBilledItems(subscription);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting billed items for subscription: " + subscription.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return billedItems;
- }
-
- public List<Subscription> getInvoiceSubscriptions(int invoiceId) throws BillingException {
- List<Subscription> subscriptions;
- try {
- beginTransaction();
- subscriptions = dataAccessObject.getInvoiceSubscriptions(invoiceId);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting invoice subscriptions for invoice id: " + invoiceId +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return subscriptions;
- }
-
- public Payment getLastPayment(Customer customer) throws BillingException {
- Payment payment;
- try {
- beginTransaction();
- payment = dataAccessObject.getLastPayment(customer);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while getting the last payment for customer: " + customer.getId() +
- " " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
- return payment;
- }
-
- public List<Customer> getAllCustomers() throws BillingException {
- return CustomerUtils.getAllCustomers();
- }
-
- public List<OutstandingBalanceInfoBean> getAllOutstandingBalanceInfoBeans(String tenantDomain)
- throws BillingException {
- if(tenantDomain==null || "".equals(tenantDomain)){
- return getAllOutstandingBalances(null);
- }else{
- List<Customer> customers = getCustomersWithName(tenantDomain);
- if(customers!=null && customers.size()>0){
- return getAllOutstandingBalances(customers.get(0));
- }else{
- return new ArrayList<OutstandingBalanceInfoBean>();
- }
- }
- }
-
- public List<OutstandingBalanceInfoBean> getAllOutstandingBalances(Customer preferredCustomer) throws BillingException{
- List<Customer> customers;// = getAllCustomers();
- List<OutstandingBalanceInfoBean> outstandingBalances = new ArrayList<OutstandingBalanceInfoBean>();
- if(preferredCustomer!=null){
- customers = new ArrayList<Customer>();
- customers.add(preferredCustomer);
- }else{
- customers = getAllCustomers();
- }
- for(Customer customer : customers){
- OutstandingBalanceInfoBean balanceBean = new OutstandingBalanceInfoBean();
- balanceBean.setCustomerName(customer.getName());
- Invoice invoice = getLastInvoice(customer);
- if(invoice!=null){
- balanceBean.setCarriedForward(invoice.getCarriedForward().toString());
- balanceBean.setLastInvoiceDate(invoice.getDate());
- }
- //setting the active usage plan
- Subscription subscription = getActiveSubscriptionOfCustomer(customer.getId());
- if(subscription!=null){
- balanceBean.setSubscription(subscription.getSubscriptionPlan());
- }else{
- balanceBean.setSubscription("Not Available");
- }
-
- Payment payment = getLastPayment(customer);
- if(payment!=null){
- balanceBean.setLastPaidAmount(payment.getAmount().toString());
- balanceBean.setLastPaymentDate(payment.getDate());
- }
- outstandingBalances.add(balanceBean);
- }
- return outstandingBalances;
- }
-
- public void sendPaymentReceivedEmail(String toAddress, String emailFile,
- Map<String,String> mailParameters) throws Exception {
- String emailTemplateFile = CarbonUtils.getCarbonConfigDirPath()+ File.separator
- + StratosConstants.EMAIL_CONFIG + File.separator + emailFile;
- EmailSenderConfiguration senderConfiguration =
- EmailSenderConfiguration.loadEmailSenderConfiguration(emailTemplateFile);
- EmailSender sender = new EmailSender(senderConfiguration);
- sender.sendEmail(toAddress, mailParameters);
- }
-
- public boolean addDiscount(Discount discount) throws Exception {
- boolean added = false;
- try {
- beginTransaction();
- added = dataAccessObject.addDiscount(discount);
- commitTransaction();
- } catch(Exception e){
- String msg = "Error occurred while adding the discount for tenant: " + discount.getTenantId()+
- ". " + e.getMessage();
- log.error(msg, e);
- rollbackTransaction();
- throw new BillingException(msg, e);
- }
-
- return added;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
deleted file mode 100644
index 8d97dc1..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingEngineContext.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
-import org.wso2.carbon.billing.core.dataobjects.Customer;
-import org.wso2.carbon.billing.core.dataobjects.Subscription;
-import org.wso2.carbon.billing.core.scheduler.SchedulerContext;
-
-import java.util.List;
-
-public class BillingEngineContext {
- List<Subscription> subscriptions;
- SchedulerContext schedulerContext;
- Customer customer;
- BillingTaskConfiguration taskConfiguration;
-
- public List<Subscription> getSubscriptions() {
- return subscriptions;
- }
-
- public void setSubscriptions(List<Subscription> subscriptions) {
- this.subscriptions = subscriptions;
- }
-
- public SchedulerContext getSchedulerContext() {
- return schedulerContext;
- }
-
- public void setSchedulerContext(SchedulerContext schedulerContext) {
- this.schedulerContext = schedulerContext;
- }
-
- public Customer getCustomer() {
- return customer;
- }
-
- public void setCustomer(Customer customer) {
- this.customer = customer;
- }
-
- public BillingTaskConfiguration getTaskConfiguration() {
- return taskConfiguration;
- }
-
- public void setTaskConfiguration(BillingTaskConfiguration taskConfiguration) {
- this.taskConfiguration = taskConfiguration;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
deleted file mode 100644
index 2aae5a4..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-@SuppressWarnings("serial")
-public class BillingException extends Exception {
- public BillingException(String msg, Exception e) {
- super(msg, e);
- }
-
- public BillingException(String msg) {
- super(msg);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
deleted file mode 100644
index 2e7e0fc..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingHandler.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-import java.util.Map;
-
-public interface BillingHandler {
- public void init(Map<String, String> handlerConfig) throws BillingException;
-
- /**
- * Performs the tasks needed to generate bill, sending bills, etc.
- *
- * @param handlerContext
- * @throws BillingException
- */
- public void execute(BillingEngineContext handlerContext) throws BillingException;
-}
http://git-wip-us.apache.org/repos/asf/incubator-stratos/blob/ee2ab783/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
----------------------------------------------------------------------
diff --git a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java b/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
deleted file mode 100644
index a523b60..0000000
--- a/components/stratos/billing/org.wso2.carbon.billing.core/2.1.0/src/main/java/org/wso2/carbon/billing/core/BillingManager.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wso2.carbon.billing.core;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.billing.core.conf.BillingConfiguration;
-import org.wso2.carbon.billing.core.conf.BillingTaskConfiguration;
-import org.wso2.carbon.billing.core.jdbc.DataAccessObject;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A class to handle multiple billing engines
- */
-public class BillingManager {
- private static final Log log = LogFactory.getLog(BillingManager.class);
- private static BillingManager billingManager;
- private BillingConfiguration billingConfiguration;
- private DataAccessObject dataAccessObject;
- private Map<String, BillingEngine> billingEngines = new HashMap<String, BillingEngine>();
-
- public static BillingManager getInstance() throws BillingException {
- if (billingManager == null) {
- String msg = "Billing Manager is not initialized.";
- log.error(msg);
- throw new BillingException(msg);
- }
- return billingManager;
- }
-
- public static void destroyInstance() {
- billingManager = null;
- }
-
- public BillingManager(BillingConfiguration billingConfiguration) throws BillingException {
- if (billingManager != null) {
- String msg = "Billing Manager should not be initialized twice";
- log.error(msg);
- throw new BillingException(msg);
- }
-
- this.billingConfiguration = billingConfiguration;
- this.dataAccessObject = new DataAccessObject(billingConfiguration.getDataSource());
- //Create billing engine corresponds to given billingTaskConfigurations
- Map<String, BillingTaskConfiguration> billingTaskConfigs =
- billingConfiguration.getBillingTaskConfigs();
- for (Map.Entry<String, BillingTaskConfiguration> entry : billingTaskConfigs.entrySet()) {
- String billingTaskName = entry.getKey();
- BillingTaskConfiguration billingTaskConfiguration = entry.getValue();
- BillingEngine billingEngine =
- new BillingEngine(billingTaskConfiguration, dataAccessObject);
- billingEngines.put(billingTaskName, billingEngine);
- }
- billingManager = this;
- }
-
- public BillingConfiguration getBillingConfiguration() {
- return billingConfiguration;
- }
-
- public DataAccessObject getDataAccessObject() {
- return dataAccessObject;
- }
-
- public BillingEngine getBillingEngine(String billingTaskName) {
- return billingEngines.get(billingTaskName);
- }
-}