killbill-aplcache
Changes
analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java 13(+7 -6)
invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java 22(+13 -9)
invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java 2(+1 -1)
invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java 1(+0 -1)
junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingEntitlementUserApi.java 33(+24 -9)
junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingApi.java 51(+28 -23)
junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java 2(+1 -1)
Details
diff --git a/account/src/main/java/com/ning/billing/account/api/user/DefaultAccountUserApi.java b/account/src/main/java/com/ning/billing/account/api/user/DefaultAccountUserApi.java
index 6f8d856..1e5a8a6 100644
--- a/account/src/main/java/com/ning/billing/account/api/user/DefaultAccountUserApi.java
+++ b/account/src/main/java/com/ning/billing/account/api/user/DefaultAccountUserApi.java
@@ -19,6 +19,8 @@ package com.ning.billing.account.api.user;
import java.util.List;
import java.util.UUID;
+import org.joda.time.DateTime;
+
import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.Account;
@@ -26,14 +28,12 @@ import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.account.api.DefaultAccount;
import com.ning.billing.account.api.MigrationAccountData;
-import com.ning.billing.account.api.DefaultMutableAccountData;
import com.ning.billing.account.dao.AccountDao;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallContextFactory;
import com.ning.billing.util.customfield.CustomField;
import com.ning.billing.util.entity.EntityPersistenceException;
import com.ning.billing.util.tag.Tag;
-import org.joda.time.DateTime;
public class DefaultAccountUserApi implements com.ning.billing.account.api.AccountUserApi {
private final CallContextFactory factory;
@@ -62,13 +62,21 @@ public class DefaultAccountUserApi implements com.ning.billing.account.api.Accou
}
@Override
- public Account getAccountByKey(final String key) {
- return dao.getAccountByKey(key);
+ public Account getAccountByKey(final String key) throws AccountApiException {
+ Account account = dao.getAccountByKey(key);
+ if(account == null) {
+ throw new AccountApiException(ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_KEY, key);
+ }
+ return account;
}
@Override
- public Account getAccountById(final UUID id) {
- return dao.getById(id.toString());
+ public Account getAccountById(final UUID id) throws AccountApiException {
+ Account account = dao.getById(id.toString());
+ if(account == null) {
+ throw new AccountApiException(ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID, id);
+ }
+ return account;
}
@Override
diff --git a/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java b/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java
index fb9f4d7..a0ad41d 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java
@@ -21,6 +21,7 @@ import com.google.inject.Inject;
import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountChangeEvent;
import com.ning.billing.account.api.AccountCreationEvent;
+import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.SubscriptionEventTransition;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.payment.api.PaymentErrorEvent;
@@ -37,7 +38,7 @@ public class AnalyticsListener {
}
@Subscribe
- public void handleSubscriptionTransitionChange(final SubscriptionEventTransition event) throws AccountApiException {
+ public void handleSubscriptionTransitionChange(final SubscriptionEventTransition event) throws AccountApiException, EntitlementUserApiException {
switch (event.getTransitionType()) {
// A susbcription enters either through migration or as newly created subscription
case MIGRATE_ENTITLEMENT:
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java
index 92c3bb0..15c4a94 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java
@@ -16,8 +16,18 @@
package com.ning.billing.analytics;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
+import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.account.api.ChangedField;
@@ -28,14 +38,6 @@ import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentAttempt;
import com.ning.billing.payment.api.PaymentInfoEvent;
import com.ning.billing.util.tag.Tag;
-import org.joda.time.DateTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
public class BusinessAccountRecorder {
private static final Logger log = LoggerFactory.getLogger(BusinessAccountRecorder.class);
@@ -54,12 +56,17 @@ public class BusinessAccountRecorder {
}
public void accountCreated(final AccountData data) {
- final Account account = accountApi.getAccountByKey(data.getExternalKey());
+ Account account;
+ try {
+ account = accountApi.getAccountByKey(data.getExternalKey());
final BusinessAccount bac = createBusinessAccountFromAccount(account);
log.info("ACCOUNT CREATION " + bac);
dao.createAccount(bac);
- }
+ } catch (AccountApiException e) {
+ log.warn("Error encountered creating BusinessAccount",e);
+ }
+ }
/**
* Notification handler for Account changes
@@ -82,13 +89,13 @@ public class BusinessAccountRecorder {
if (paymentAttempt == null) {
return;
}
-
- final Account account = accountApi.getAccountById(paymentAttempt.getAccountId());
- if (account == null) {
- return;
+ try {
+ final Account account = accountApi.getAccountById(paymentAttempt.getAccountId());
+ accountUpdated(account.getId());
+ } catch (AccountApiException e) {
+ log.warn("Error encountered creating BusinessAccount",e);
}
- accountUpdated(account.getId());
}
/**
@@ -97,23 +104,28 @@ public class BusinessAccountRecorder {
* @param accountId account id associated with the created invoice
*/
public void accountUpdated(final UUID accountId) {
- final Account account = accountApi.getAccountById(accountId);
+ try {
+ final Account account = accountApi.getAccountById(accountId);
- if (account == null) {
- log.warn("Couldn't find account {}", accountId);
- return;
- }
+ if (account == null) {
+ log.warn("Couldn't find account {}", accountId);
+ return;
+ }
- BusinessAccount bac = dao.getAccount(account.getExternalKey());
- if (bac == null) {
- bac = createBusinessAccountFromAccount(account);
- log.info("ACCOUNT CREATION " + bac);
- dao.createAccount(bac);
- } else {
- updateBusinessAccountFromAccount(account, bac);
- log.info("ACCOUNT UPDATE " + bac);
- dao.saveAccount(bac);
+ BusinessAccount bac = dao.getAccount(account.getExternalKey());
+ if (bac == null) {
+ bac = createBusinessAccountFromAccount(account);
+ log.info("ACCOUNT CREATION " + bac);
+ dao.createAccount(bac);
+ } else {
+ updateBusinessAccountFromAccount(account, bac);
+ log.info("ACCOUNT UPDATE " + bac);
+ dao.saveAccount(bac);
+ }
+ } catch (AccountApiException e) {
+ log.warn("Error encountered creating BusinessAccount",e);
}
+
}
private BusinessAccount createBusinessAccountFromAccount(final Account account) {
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java
index 82457ef..7ec958f 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java
@@ -23,6 +23,7 @@ import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.analytics.dao.BusinessSubscriptionTransitionDao;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
+import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.entitlement.api.user.SubscriptionEventTransition;
import org.joda.time.DateTime;
@@ -48,39 +49,39 @@ public class BusinessSubscriptionTransitionRecorder
this.accountApi = accountApi;
}
- public void subscriptionCreated(final SubscriptionEventTransition created) throws AccountApiException
+ public void subscriptionCreated(final SubscriptionEventTransition created) throws AccountApiException, EntitlementUserApiException
{
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionCreated(created.getNextPlan());
recordTransition(event, created);
}
- public void subscriptionRecreated(final SubscriptionEventTransition recreated) throws AccountApiException
+ public void subscriptionRecreated(final SubscriptionEventTransition recreated) throws AccountApiException, EntitlementUserApiException
{
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionRecreated(recreated.getNextPlan());
recordTransition(event, recreated);
}
- public void subscriptionCancelled(final SubscriptionEventTransition cancelled) throws AccountApiException
+ public void subscriptionCancelled(final SubscriptionEventTransition cancelled) throws AccountApiException, EntitlementUserApiException
{
// cancelled.getNextPlan() is null here - need to look at the previous one to create the correct event name
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionCancelled(cancelled.getPreviousPlan());
recordTransition(event, cancelled);
}
- public void subscriptionChanged(final SubscriptionEventTransition changed) throws AccountApiException
+ public void subscriptionChanged(final SubscriptionEventTransition changed) throws AccountApiException, EntitlementUserApiException
{
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionChanged(changed.getNextPlan());
recordTransition(event, changed);
}
- public void subscriptionPhaseChanged(final SubscriptionEventTransition phaseChanged) throws AccountApiException
+ public void subscriptionPhaseChanged(final SubscriptionEventTransition phaseChanged) throws AccountApiException, EntitlementUserApiException
{
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionPhaseChanged(phaseChanged.getNextPlan(), phaseChanged.getNextState());
recordTransition(event, phaseChanged);
}
- public void recordTransition(final BusinessSubscriptionEvent event, final SubscriptionEventTransition transition) throws AccountApiException
+ public void recordTransition(final BusinessSubscriptionEvent event, final SubscriptionEventTransition transition) throws AccountApiException, EntitlementUserApiException
{
Currency currency = null;
String transitionKey = null;
diff --git a/api/src/main/java/com/ning/billing/account/api/AccountUserApi.java b/api/src/main/java/com/ning/billing/account/api/AccountUserApi.java
index 98d6272..eabee0f 100644
--- a/api/src/main/java/com/ning/billing/account/api/AccountUserApi.java
+++ b/api/src/main/java/com/ning/billing/account/api/AccountUserApi.java
@@ -44,9 +44,9 @@ public interface AccountUserApi {
public void updateAccount(UUID accountId, AccountData accountData, CallContext context) throws AccountApiException;
- public Account getAccountByKey(String key);
+ public Account getAccountByKey(String key) throws AccountApiException;
- public Account getAccountById(UUID accountId);
+ public Account getAccountById(UUID accountId) throws AccountApiException;
public List<Account> getAccounts();
diff --git a/api/src/main/java/com/ning/billing/entitlement/api/user/EntitlementUserApi.java b/api/src/main/java/com/ning/billing/entitlement/api/user/EntitlementUserApi.java
index 66091e2..0e74f86 100644
--- a/api/src/main/java/com/ning/billing/entitlement/api/user/EntitlementUserApi.java
+++ b/api/src/main/java/com/ning/billing/entitlement/api/user/EntitlementUserApi.java
@@ -26,11 +26,11 @@ import com.ning.billing.catalog.api.PlanPhaseSpecifier;
public interface EntitlementUserApi {
- public SubscriptionBundle getBundleFromId(UUID id);
+ public SubscriptionBundle getBundleFromId(UUID id) throws EntitlementUserApiException;
- public Subscription getSubscriptionFromId(UUID id);
+ public Subscription getSubscriptionFromId(UUID id) throws EntitlementUserApiException;
- public SubscriptionBundle getBundleForKey(String bundleKey);
+ public SubscriptionBundle getBundleForKey(String bundleKey) throws EntitlementUserApiException;
public List<SubscriptionBundle> getBundlesForAccount(UUID accountId);
diff --git a/api/src/main/java/com/ning/billing/ErrorCode.java b/api/src/main/java/com/ning/billing/ErrorCode.java
index 234cb45..9680237 100644
--- a/api/src/main/java/com/ning/billing/ErrorCode.java
+++ b/api/src/main/java/com/ning/billing/ErrorCode.java
@@ -56,6 +56,8 @@ public enum ErrorCode {
ENT_GET_NO_BUNDLE_FOR_SUBSCRIPTION(1080, "Could not find a bundle for subscription %s"),
ENT_GET_INVALID_BUNDLE_ID(1081, "Could not find a bundle matching id %s"),
ENT_INVALID_SUBSCRIPTION_ID(1082, "Unknown subscription %s"),
+ ENT_GET_INVALID_BUNDLE_KEY(1083, "Could not find a bundle matching key %s"),
+
ENT_BUNDLE_IS_OVERDUE_BLOCKED(1090, "Changes to this bundle are blocked by overdue enforcement (%s : %s)"),
ENT_ACCOUNT_IS_OVERDUE_BLOCKED(1091, "Changes to this account are blocked by overdue enforcement (%s)"),
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegration.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegration.java
index a6a61b6..5766862 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegration.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegration.java
@@ -61,12 +61,14 @@ import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
+import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.entitlement.api.user.SubscriptionData;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.invoice.model.InvoicingConfiguration;
+import com.ning.billing.junction.plumbing.api.BlockingSubscription;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallOrigin;
@@ -139,7 +141,7 @@ public class TestIntegration {
public void setup() throws Exception{
setupMySQL();
-
+ cleanupData();
context = new DefaultCallContextFactory(clock).createCallContext("Integration Test", CallOrigin.TEST, UserType.TEST);
/**
@@ -168,9 +170,10 @@ public class TestIntegration {
log.warn("\n");
log.warn("RESET TEST FRAMEWORK\n\n");
+ cleanupData();
busHandler.reset();
clock.resetDeltaFromReality();
- cleanupData();
+
}
@AfterMethod(groups = "slow")
@@ -206,8 +209,9 @@ public class TestIntegration {
private void verifyTestResult(UUID accountId, UUID subscriptionId,
DateTime startDate, DateTime endDate,
BigDecimal amount, DateTime chargeThroughDate,
- int totalInvoiceItemCount) {
- SubscriptionData subscription = (SubscriptionData) entitlementUserApi.getSubscriptionFromId(subscriptionId);
+ int totalInvoiceItemCount) throws EntitlementUserApiException {
+ BlockingSubscription bSubscription = (BlockingSubscription) entitlementUserApi.getSubscriptionFromId(subscriptionId);
+ SubscriptionData subscription = (SubscriptionData) bSubscription.getDelegateSubscription();
List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(accountId);
List<InvoiceItem> invoiceItems = new ArrayList<InvoiceItem>();
@@ -264,9 +268,9 @@ public class TestIntegration {
testBasePlanComplete(startDate, 3, true);
}
- private void waitForDebug() throws Exception {
- Thread.sleep(600000);
- }
+// private void waitForDebug() throws Exception {
+// Thread.sleep(600000);
+// }
@Test(groups = {"slow", "stress"}, enabled = false)
public void stressTest() throws Exception {
@@ -312,8 +316,10 @@ public class TestIntegration {
//
busHandler.pushExpectedEvent(NextEvent.CREATE);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
- SubscriptionData subscription = (SubscriptionData) entitlementUserApi.createSubscription(bundle.getId(),
- new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context);
+
+ SubscriptionData subscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
+ new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
+
assertNotNull(subscription);
assertTrue(busHandler.isCompleted(DELAY));
@@ -335,7 +341,7 @@ public class TestIntegration {
clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
assertTrue(busHandler.isCompleted(DELAY));
- subscription = (SubscriptionData) entitlementUserApi.getSubscriptionFromId(subscription.getId());
+ subscription = subscriptionDataFromSubscription(entitlementUserApi.getSubscriptionFromId(subscription.getId()));
subscription.cancel(clock.getUTCNow(), false, context);
// MOVE AFTER CANCEL DATE AND EXPECT EVENT : NextEvent.CANCEL
@@ -357,6 +363,11 @@ public class TestIntegration {
}
+
+ private SubscriptionData subscriptionDataFromSubscription(Subscription sub) {
+ return (SubscriptionData)((BlockingSubscription)sub).getDelegateSubscription();
+ }
+
private void testBasePlanComplete(DateTime initialCreationDate, int billingDay,
boolean proRationExpected) throws Exception {
@@ -378,8 +389,9 @@ public class TestIntegration {
//
busHandler.pushExpectedEvent(NextEvent.CREATE);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
- SubscriptionData subscription = (SubscriptionData) entitlementUserApi.createSubscription(bundle.getId(),
- new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context);
+ SubscriptionData subscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
+ new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
+
assertNotNull(subscription);
assertTrue(busHandler.isCompleted(DELAY));
@@ -476,7 +488,7 @@ public class TestIntegration {
newTerm = BillingPeriod.MONTHLY;
newPlanSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
newProductName = "Pistol";
- subscription = (SubscriptionData) entitlementUserApi.getSubscriptionFromId(subscription.getId());
+ subscription = subscriptionDataFromSubscription(entitlementUserApi.getSubscriptionFromId(subscription.getId()));
subscription.changePlan(newProductName, newTerm, newPlanSetName, clock.getUTCNow(), context);
//
@@ -524,7 +536,7 @@ public class TestIntegration {
//
// FINALLY CANCEL SUBSCRIPTION EOT
//
- subscription = (SubscriptionData) entitlementUserApi.getSubscriptionFromId(subscription.getId());
+ subscription = subscriptionDataFromSubscription(entitlementUserApi.getSubscriptionFromId(subscription.getId()));
subscription.cancel(clock.getUTCNow(), false, context);
// MOVE AFTER CANCEL DATE AND EXPECT EVENT : NextEvent.CANCEL
@@ -540,7 +552,7 @@ public class TestIntegration {
clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS + 1000);
assertTrue(busHandler.isCompleted(DELAY));
- subscription = (SubscriptionData) entitlementUserApi.getSubscriptionFromId(subscription.getId());
+ subscription = subscriptionDataFromSubscription(entitlementUserApi.getSubscriptionFromId(subscription.getId()));
DateTime lastCtd = subscription.getChargedThroughDate();
assertNotNull(lastCtd);
log.info("Checking CTD: " + lastCtd.toString() + "; clock is " + clock.getUTCNow().toString());
@@ -551,46 +563,13 @@ public class TestIntegration {
log.info("TEST PASSED !");
}
- @Test(groups = "slow")
- public void testHappyPath() throws AccountApiException, EntitlementUserApiException {
- Account account = accountUserApi.createAccount(getAccountData(3), null, null, context);
- assertNotNull(account);
-
- SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), "whatever", context);
-
- String productName = "Shotgun";
- BillingPeriod term = BillingPeriod.MONTHLY;
- String planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
-
- busHandler.pushExpectedEvent(NextEvent.CREATE);
- busHandler.pushExpectedEvent(NextEvent.INVOICE);
- SubscriptionData subscription = (SubscriptionData) entitlementUserApi.createSubscription(bundle.getId(),
- new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context);
- assertNotNull(subscription);
-
- assertTrue(busHandler.isCompleted(DELAY));
-
- busHandler.pushExpectedEvent(NextEvent.CHANGE);
- busHandler.pushExpectedEvent(NextEvent.INVOICE);
- BillingPeriod newTerm = BillingPeriod.MONTHLY;
- String newPlanSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
- String newProductName = "Assault-Rifle";
- subscription.changePlan(newProductName, newTerm, newPlanSetName, clock.getUTCNow(), context);
-
- assertTrue(busHandler.isCompleted(DELAY));
-
- busHandler.pushExpectedEvent(NextEvent.PHASE);
- busHandler.pushExpectedEvent(NextEvent.INVOICE);
- clock.setDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
- assertTrue(busHandler.isCompleted(DELAY));
-
- }
@Test(groups = "slow")
public void testForMultipleRecurringPhases() throws AccountApiException, EntitlementUserApiException, InterruptedException {
- clock.setDeltaFromReality(new DateTime().getMillis() - clock.getUTCNow().getMillis());
+ DateTime initialCreationDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ clock.setDeltaFromReality(initialCreationDate.getMillis() - clock.getUTCNow().getMillis());
- Account account = accountUserApi.createAccount(getAccountData(15), null, null, context);
+ Account account = accountUserApi.createAccount(getAccountData(2), null, null, context);
UUID accountId = account.getId();
String productName = "Blowdart";
@@ -599,31 +578,53 @@ public class TestIntegration {
busHandler.pushExpectedEvent(NextEvent.CREATE);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(accountId, "testKey", context);
- SubscriptionData subscription = (SubscriptionData) entitlementUserApi.createSubscription(bundle.getId(),
+ subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
new PlanPhaseSpecifier(productName, ProductCategory.BASE,
- BillingPeriod.MONTHLY, planSetName, PhaseType.TRIAL), null, context);
+ BillingPeriod.MONTHLY, planSetName, PhaseType.TRIAL), null, context));
+
assertTrue(busHandler.isCompleted(DELAY));
List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(accountId);
assertNotNull(invoices);
assertTrue(invoices.size() == 1);
-
+
busHandler.pushExpectedEvent(NextEvent.PHASE);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
busHandler.pushExpectedEvent(NextEvent.PAYMENT);
- clock.addDeltaFromReality(6 * AT_LEAST_ONE_MONTH_MS);
- assertTrue(busHandler.isCompleted(DELAY));
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
+ assertTrue(busHandler.isCompleted(DELAY));
invoices = invoiceUserApi.getInvoicesByAccount(accountId);
assertNotNull(invoices);
assertEquals(invoices.size(),2);
-
- busHandler.pushExpectedEvent(NextEvent.PHASE);
+
+ for (int i = 0; i < 5; i++) {
+ log.info("============== loop number " + i +"=======================");
+ busHandler.pushExpectedEvent(NextEvent.INVOICE);
+ busHandler.pushExpectedEvent(NextEvent.PAYMENT);
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
+ assertTrue(busHandler.isCompleted(DELAY));
+ }
+
busHandler.pushExpectedEvent(NextEvent.INVOICE);
busHandler.pushExpectedEvent(NextEvent.PAYMENT);
- clock.addDeltaFromReality(6 * AT_LEAST_ONE_MONTH_MS);
- assertTrue(busHandler.isCompleted(DELAY));
+ busHandler.pushExpectedEvent(NextEvent.PHASE);
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceUserApi.getInvoicesByAccount(accountId);
+ assertNotNull(invoices);
+ assertEquals(invoices.size(),8);
+
+ for (int i = 0; i <= 5; i++) {
+ log.info("============== second loop number " + i +"=======================");
+ busHandler.pushExpectedEvent(NextEvent.INVOICE);
+ busHandler.pushExpectedEvent(NextEvent.PAYMENT);
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
+ assertTrue(busHandler.isCompleted(DELAY));
+ }
+
invoices = invoiceUserApi.getInvoicesByAccount(accountId);
assertNotNull(invoices);
- assertEquals(invoices.size(),3);
+ assertEquals(invoices.size(),14);
}
protected AccountData getAccountData(final int billingDay) {
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiDemos.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiDemos.java
index b21764d..a206aaa 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiDemos.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiDemos.java
@@ -170,23 +170,27 @@ public class TestUserApiDemos extends TestApiBase {
System.out.println("");
System.out.println("******\t STEP " + stepMsg + " **************");
-
- SubscriptionData subscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(subscriptionId);
+ try {
+ SubscriptionData subscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(subscriptionId);
- Plan currentPlan = subscription.getCurrentPlan();
- PlanPhase currentPhase = subscription.getCurrentPhase();
- String priceList = subscription.getCurrentPriceList().getName();
- System.out.println("");
- System.out.println("\t CURRENT TIME = " + clock.getUTCNow());
- System.out.println("");
- System.out.println("\t CURRENT STATE = " + subscription.getState());
- System.out.println("\t CURRENT PRODUCT = " + ((currentPlan == null) ? "NONE" : currentPlan.getProduct().getName()));
- System.out.println("\t CURRENT TERM = " + ((currentPlan == null) ? "NONE" : currentPlan.getBillingPeriod().toString()));
- System.out.println("\t CURRENT PHASE = " + ((currentPhase == null) ? "NONE" : currentPhase.getPhaseType()));
- System.out.println("\t CURRENT PRICE LIST = " + ((priceList == null) ? "NONE" : priceList));
- System.out.println("\t CURRENT \'SLUG\' = " + ((currentPhase == null) ? "NONE" : currentPhase.getName()));
+ Plan currentPlan = subscription.getCurrentPlan();
+ PlanPhase currentPhase = subscription.getCurrentPhase();
+ String priceList = subscription.getCurrentPriceList().getName();
+
+ System.out.println("");
+ System.out.println("\t CURRENT TIME = " + clock.getUTCNow());
+ System.out.println("");
+ System.out.println("\t CURRENT STATE = " + subscription.getState());
+ System.out.println("\t CURRENT PRODUCT = " + ((currentPlan == null) ? "NONE" : currentPlan.getProduct().getName()));
+ System.out.println("\t CURRENT TERM = " + ((currentPlan == null) ? "NONE" : currentPlan.getBillingPeriod().toString()));
+ System.out.println("\t CURRENT PHASE = " + ((currentPhase == null) ? "NONE" : currentPhase.getPhaseType()));
+ System.out.println("\t CURRENT PRICE LIST = " + ((priceList == null) ? "NONE" : priceList));
+ System.out.println("\t CURRENT \'SLUG\' = " + ((currentPhase == null) ? "NONE" : currentPhase.getName()));
+ } catch (EntitlementUserApiException e) {
+ System.out.println("No subscription found for id:" + subscriptionId );
+ }
System.out.println("");
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java b/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java
index 870e7c5..4cea068 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java
@@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.Account;
+import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.entitlement.api.billing.BillingEvent;
@@ -138,43 +139,43 @@ public class InvoiceDispatcher {
}
}
private Invoice processAccountWithLock(final UUID accountId, final DateTime targetDate,
- final boolean dryRun, final CallContext context) throws InvoiceApiException {
-
- Account account = accountUserApi.getAccountById(accountId);
- if (account == null) {
- log.error("Failed handling entitlement change.",
- new InvoiceApiException(ErrorCode.INVOICE_ACCOUNT_ID_INVALID, accountId.toString()));
- return null;
- }
-
- SortedSet<BillingEvent> events = billingApi.getBillingEventsForAccountAndUpdateAccountBCD(accountId);
- BillingEventSet billingEvents = new BillingEventSet(events);
+ final boolean dryRun, final CallContext context) throws InvoiceApiException {
+ try {
+ Account account = accountUserApi.getAccountById(accountId);
+ SortedSet<BillingEvent> events = billingApi.getBillingEventsForAccountAndUpdateAccountBCD(accountId);
+ BillingEventSet billingEvents = new BillingEventSet(events);
- Currency targetCurrency = account.getCurrency();
+ Currency targetCurrency = account.getCurrency();
- List<Invoice> invoices = invoiceDao.getInvoicesByAccount(accountId);
- Invoice invoice = generator.generateInvoice(accountId, billingEvents, invoices, targetDate, targetCurrency);
+ List<Invoice> invoices = invoiceDao.getInvoicesByAccount(accountId);
+ Invoice invoice = generator.generateInvoice(accountId, billingEvents, invoices, targetDate, targetCurrency);
- if (invoice == null) {
- log.info("Generated null invoice.");
- outputDebugData(events, invoices);
- if (!dryRun) {
- postEmptyInvoiceEvent(accountId, context.getUserToken());
- }
- } else {
- log.info("Generated invoice {} with {} items.", invoice.getId().toString(), invoice.getNumberOfItems());
- if (VERBOSE_OUTPUT) {
- log.info("New items");
- for (InvoiceItem item : invoice.getInvoiceItems()) {
- log.info(item.toString());
+ if (invoice == null) {
+ log.info("Generated null invoice.");
+ outputDebugData(events, invoices);
+ if (!dryRun) {
+ postEmptyInvoiceEvent(accountId, context.getUserToken());
+ }
+ } else {
+ log.info("Generated invoice {} with {} items.", invoice.getId().toString(), invoice.getNumberOfItems());
+ if (VERBOSE_OUTPUT) {
+ log.info("New items");
+ for (InvoiceItem item : invoice.getInvoiceItems()) {
+ log.info(item.toString());
+ }
+ }
+ outputDebugData(events, invoices);
+ if (!dryRun) {
+ invoiceDao.create(invoice, context);
}
}
- outputDebugData(events, invoices);
- if (!dryRun) {
- invoiceDao.create(invoice, context);
- }
+ return invoice;
+ } catch(AccountApiException e) {
+ log.error("Failed handling entitlement change.",e);
+ return null;
+
}
- return invoice;
+
}
private void outputDebugData(Collection<BillingEvent> events, Collection<Invoice> invoices) {
diff --git a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
index 2f6ea8b..28d15a8 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java
@@ -26,10 +26,10 @@ import com.google.inject.Inject;
import com.ning.billing.config.InvoiceConfig;
import com.ning.billing.config.NotificationConfig;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
+import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.invoice.InvoiceListener;
import com.ning.billing.invoice.api.DefaultInvoiceService;
-
import com.ning.billing.util.notificationq.NotificationQueue;
import com.ning.billing.util.notificationq.NotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueAlreadyExists;
@@ -66,15 +66,19 @@ public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier
new NotificationQueueHandler() {
@Override
public void handleReadyNotification(String notificationKey, DateTime eventDate) {
- try {
- UUID key = UUID.fromString(notificationKey);
- Subscription subscription = entitlementUserApi.getSubscriptionFromId(key);
- if (subscription == null) {
- log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")" );
- } else {
- processEvent(key , eventDate);
+ try {
+ UUID key = UUID.fromString(notificationKey);
+ try {
+ Subscription subscription = entitlementUserApi.getSubscriptionFromId(key);
+ if (subscription == null) {
+ log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")" );
+ } else {
+ processEvent(key , eventDate);
+ }
+ } catch (EntitlementUserApiException e) {
+ log.warn("Next Billing Date Notification Queue handled spurious notification (key: " + key + ")", e );
}
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
return;
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/api/migration/MockModuleNoEntitlement.java b/invoice/src/test/java/com/ning/billing/invoice/api/migration/MockModuleNoEntitlement.java
index 28077d2..0486238 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/api/migration/MockModuleNoEntitlement.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/api/migration/MockModuleNoEntitlement.java
@@ -17,7 +17,6 @@
package com.ning.billing.invoice.api.migration;
import com.ning.billing.entitlement.api.billing.ChargeThruApi;
-import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.invoice.MockModule;
import com.ning.billing.invoice.glue.InvoiceModule;
import com.ning.billing.invoice.notification.NextBillingDateNotifier;
@@ -34,7 +33,7 @@ public class MockModuleNoEntitlement extends MockModule {
((ZombieControl)entitlementApi).addResult("setChargedThroughDateFromTransaction", BrainDeadProxyFactory.ZOMBIE_VOID);
((ZombieControl)entitlementApi).addResult("getBillingEventsForAccountAndUpdateAccountBCD", BrainDeadProxyFactory.ZOMBIE_VOID);
//bind(BillingApi.class).toInstance(entitlementApi);
- bind(EntitlementUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class));
+// bind(EntitlementUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class));
ChargeThruApi cta = BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class);
bind(ChargeThruApi.class).toInstance(cta);
((ZombieControl)cta).addResult("setChargedThroughDateFromTransaction", BrainDeadProxyFactory.ZOMBIE_VOID);
diff --git a/invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java b/invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java
index 354b28a..047c5d6 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java
@@ -69,7 +69,7 @@ import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
import com.ning.billing.util.globallocker.GlobalLocker;
-@Guice(modules = {MockModuleNoEntitlement.class})
+@Guice(modules = {MockModuleNoEntitlement.class, })
public class TestDefaultInvoiceMigrationApi {
Logger log = LoggerFactory.getLogger(TestDefaultInvoiceMigrationApi.class);
diff --git a/invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java b/invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java
index c82994c..d1ff615 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java
@@ -142,7 +142,6 @@ public class TestNextBillingDateNotifier {
bind(InvoiceGenerator.class).to(DefaultInvoiceGenerator.class).asEagerSingleton();
bind(InvoiceDao.class).to(DefaultInvoiceDao.class);
bind(NextBillingDatePoster.class).to(DefaultNextBillingDatePoster.class).asEagerSingleton();
- bind(EntitlementUserApi.class).to(DefaultEntitlementUserApi.class).asEagerSingleton();
bind(ChargeThruApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class));
install(new MockJunctionModule());
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java b/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java
index 72a1db0..7b53850 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java
@@ -56,6 +56,7 @@ import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.plumbing.billing.DefaultBillingEvent;
import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
+import com.ning.billing.mock.glue.MockJunctionModule;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.bus.DefaultBusService;
import com.ning.billing.util.callcontext.CallContext;
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/AccountResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/AccountResource.java
index 49203f5..bd7a22b 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/AccountResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/AccountResource.java
@@ -33,8 +33,8 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -79,12 +79,16 @@ public class AccountResource implements BaseJaxrsResource {
@Path("/{accountId:" + UUID_PATTERN + "}")
@Produces(APPLICATION_JSON)
public Response getAccount(@PathParam("accountId") String accountId) {
- Account account = accountApi.getAccountById(UUID.fromString(accountId));
- if (account == null) {
- return Response.status(Status.NO_CONTENT).build();
+ try {
+ Account account = accountApi.getAccountById(UUID.fromString(accountId));
+
+ AccountJson json = new AccountJson(account);
+ return Response.status(Status.OK).entity(json).build();
+ } catch (AccountApiException e) {
+ log.warn("Failed to find account.", e);
+ return Response.status(Status.NO_CONTENT).build();
}
- AccountJson json = new AccountJson(account);
- return Response.status(Status.OK).entity(json).build();
+
}
@GET
@@ -92,34 +96,42 @@ public class AccountResource implements BaseJaxrsResource {
@Produces(APPLICATION_JSON)
public Response getAccountBundles(@PathParam("accountId") String accountId) {
- UUID uuid = UUID.fromString(accountId);
- Account account = accountApi.getAccountById(uuid);
- if (account == null) {
- return Response.status(Status.NO_CONTENT).build();
- }
- List<SubscriptionBundle> bundles = entitlementApi.getBundlesForAccount(uuid);
- Collection<BundleJson> result = Collections2.transform(bundles, new Function<SubscriptionBundle, BundleJson>() {
- @Override
- public BundleJson apply(SubscriptionBundle input) {
- return new BundleJson(input);
- }
- });
- return Response.status(Status.OK).entity(result).build();
+ try {
+ UUID uuid = UUID.fromString(accountId);
+ accountApi.getAccountById(uuid);
+
+ List<SubscriptionBundle> bundles = entitlementApi.getBundlesForAccount(uuid);
+ Collection<BundleJson> result = Collections2.transform(bundles, new Function<SubscriptionBundle, BundleJson>() {
+ @Override
+ public BundleJson apply(SubscriptionBundle input) {
+ return new BundleJson(input);
+ }
+ });
+ return Response.status(Status.OK).entity(result).build();
+ } catch (AccountApiException e) {
+ log.warn("Failed to find account.", e);
+ return Response.status(Status.NO_CONTENT).build();
+ }
}
@GET
@Produces(APPLICATION_JSON)
public Response getAccountByKey(@QueryParam(QUERY_EXTERNAL_KEY) String externalKey) {
- Account account = null;
- if (externalKey != null) {
- account = accountApi.getAccountByKey(externalKey);
- }
- if (account == null) {
+ try {
+ Account account = null;
+ if (externalKey != null) {
+ account = accountApi.getAccountByKey(externalKey);
+ }
+ if (account == null) {
+ return Response.status(Status.NO_CONTENT).build();
+ }
+ AccountJson json = new AccountJson(account);
+ return Response.status(Status.OK).entity(json).build();
+ } catch (AccountApiException e) {
+ log.warn("Failed to find account.", e);
return Response.status(Status.NO_CONTENT).build();
}
- AccountJson json = new AccountJson(account);
- return Response.status(Status.OK).entity(json).build();
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/BundleResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/BundleResource.java
index d6a94ab..3b6665e 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/BundleResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/BundleResource.java
@@ -38,6 +38,7 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.inject.Inject;
+import com.ning.billing.ErrorCode;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
@@ -50,73 +51,93 @@ import com.ning.billing.jaxrs.util.JaxrsUriBuilder;
@Path(BaseJaxrsResource.BUNDLES_PATH)
public class BundleResource implements BaseJaxrsResource {
- private static final Logger log = LoggerFactory.getLogger(BundleResource.class);
+ private static final Logger log = LoggerFactory.getLogger(BundleResource.class);
- private final EntitlementUserApi entitlementApi;
- private final Context context;
+ private final EntitlementUserApi entitlementApi;
+ private final Context context;
private final JaxrsUriBuilder uriBuilder;
@Inject
- public BundleResource(final JaxrsUriBuilder uriBuilder, final EntitlementUserApi entitlementApi, final Context context) {
- this.uriBuilder = uriBuilder;
- this.entitlementApi = entitlementApi;
- this.context = context;
- }
-
- @GET
- @Path("/{bundleId:" + UUID_PATTERN + "}")
- @Produces(APPLICATION_JSON)
- public Response getBundle(@PathParam("bundleId") final String bundleId) {
- SubscriptionBundle bundle = entitlementApi.getBundleFromId(UUID.fromString(bundleId));
- if (bundle == null) {
- return Response.status(Status.NO_CONTENT).build();
- }
- BundleJson json = new BundleJson(bundle);
- return Response.status(Status.OK).entity(json).build();
- }
-
- @GET
- @Produces(APPLICATION_JSON)
- public Response getBundleByKey(@QueryParam(QUERY_EXTERNAL_KEY) final String externalKey) {
- SubscriptionBundle bundle = entitlementApi.getBundleForKey(externalKey);
- if (bundle == null) {
- return Response.status(Status.NO_CONTENT).build();
- }
- BundleJson json = new BundleJson(bundle);
- return Response.status(Status.OK).entity(json).build();
- }
-
- @POST
- @Consumes(APPLICATION_JSON)
- @Produces(APPLICATION_JSON)
- public Response createBundle(final BundleJson json) {
- try {
- UUID accountId = UUID.fromString(json.getAccountId());
- final SubscriptionBundle bundle = entitlementApi.createBundleForAccount(accountId, json.getExternalKey(), context.createContext());
+ public BundleResource(final JaxrsUriBuilder uriBuilder, final EntitlementUserApi entitlementApi, final Context context) {
+ this.uriBuilder = uriBuilder;
+ this.entitlementApi = entitlementApi;
+ this.context = context;
+ }
+
+ @GET
+ @Path("/{bundleId:" + UUID_PATTERN + "}")
+ @Produces(APPLICATION_JSON)
+ public Response getBundle(@PathParam("bundleId") final String bundleId) throws EntitlementUserApiException {
+ try {
+ SubscriptionBundle bundle = entitlementApi.getBundleFromId(UUID.fromString(bundleId));
+ BundleJson json = new BundleJson(bundle);
+ return Response.status(Status.OK).entity(json).build();
+ } catch (EntitlementUserApiException e) {
+ if (e.getCode() == ErrorCode.ENT_GET_INVALID_BUNDLE_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ throw e;
+ }
+
+ }
+ }
+
+ @GET
+ @Produces(APPLICATION_JSON)
+ public Response getBundleByKey(@QueryParam(QUERY_EXTERNAL_KEY) final String externalKey) throws EntitlementUserApiException {
+ try {
+ SubscriptionBundle bundle = entitlementApi.getBundleForKey(externalKey);
+ BundleJson json = new BundleJson(bundle);
+ return Response.status(Status.OK).entity(json).build();
+ } catch (EntitlementUserApiException e) {
+ if (e.getCode() == ErrorCode.ENT_GET_INVALID_BUNDLE_KEY.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ throw e;
+ }
+
+ }
+ }
+
+ @POST
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ public Response createBundle(final BundleJson json) {
+ try {
+ UUID accountId = UUID.fromString(json.getAccountId());
+ final SubscriptionBundle bundle = entitlementApi.createBundleForAccount(accountId, json.getExternalKey(), context.createContext());
return uriBuilder.buildResponse(BundleResource.class, "getBundle", bundle.getId());
- } catch (EntitlementUserApiException e) {
- log.info(String.format("Failed to create bundle %s", json), e);
- return Response.status(Status.BAD_REQUEST).build();
- }
- }
-
- @GET
- @Path("/{bundleId:" + UUID_PATTERN + "}/" + SUBSCRIPTIONS)
- @Produces(APPLICATION_JSON)
- public Response getBundleSubscriptions(@PathParam("bundleId") final String bundleId) {
-
- UUID uuid = UUID.fromString(bundleId);
- SubscriptionBundle bundle = entitlementApi.getBundleFromId(uuid);
- if (bundle == null) {
- return Response.status(Status.NO_CONTENT).build();
- }
- List<Subscription> bundles = entitlementApi.getSubscriptionsForBundle(uuid);
- Collection<SubscriptionJson> result = Collections2.transform(bundles, new Function<Subscription, SubscriptionJson>() {
- @Override
- public SubscriptionJson apply(Subscription input) {
- return new SubscriptionJson(input, null, null, null);
- }
- });
- return Response.status(Status.OK).entity(result).build();
- }
+ } catch (EntitlementUserApiException e) {
+ log.info(String.format("Failed to create bundle %s", json), e);
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ }
+
+ @GET
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + SUBSCRIPTIONS)
+ @Produces(APPLICATION_JSON)
+ public Response getBundleSubscriptions(@PathParam("bundleId") final String bundleId) throws EntitlementUserApiException {
+ try {
+ UUID uuid = UUID.fromString(bundleId);
+ SubscriptionBundle bundle = entitlementApi.getBundleFromId(uuid);
+ if (bundle == null) {
+ return Response.status(Status.NO_CONTENT).build();
+ }
+ List<Subscription> bundles = entitlementApi.getSubscriptionsForBundle(uuid);
+ Collection<SubscriptionJson> result = Collections2.transform(bundles, new Function<Subscription, SubscriptionJson>() {
+ @Override
+ public SubscriptionJson apply(Subscription input) {
+ return new SubscriptionJson(input, null, null, null);
+ }
+ });
+ return Response.status(Status.OK).entity(result).build();
+ } catch (EntitlementUserApiException e) {
+ if (e.getCode() == ErrorCode.ENT_GET_INVALID_BUNDLE_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ throw e;
+ }
+
+ }
+ }
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/SubscriptionResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/SubscriptionResource.java
index 8c5c5bd..8a3b350 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/SubscriptionResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/SubscriptionResource.java
@@ -22,7 +22,6 @@ import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
-import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
@@ -43,6 +42,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
+import com.ning.billing.ErrorCode;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.ProductCategory;
@@ -86,16 +86,22 @@ public class SubscriptionResource implements BaseJaxrsResource{
@GET
@Path("/{subscriptionId:" + UUID_PATTERN + "}")
@Produces(APPLICATION_JSON)
- public Response getSubscription(@PathParam("subscriptionId") final String subscriptionId) {
+ public Response getSubscription(@PathParam("subscriptionId") final String subscriptionId) throws EntitlementUserApiException {
+ try {
+ UUID uuid = UUID.fromString(subscriptionId);
+ Subscription subscription = entitlementApi.getSubscriptionFromId(uuid);
+
+ SubscriptionJson json = new SubscriptionJson(subscription, null, null, null);
+ return Response.status(Status.OK).entity(json).build();
+ } catch (EntitlementUserApiException e) {
+ if (e.getCode() == ErrorCode.ENT_INVALID_SUBSCRIPTION_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ throw e;
+ }
- UUID uuid = UUID.fromString(subscriptionId);
- Subscription subscription = entitlementApi.getSubscriptionFromId(uuid);
- if (subscription == null) {
- return Response.status(Status.NO_CONTENT).build();
}
- SubscriptionJson json = new SubscriptionJson(subscription, null, null, null);
- return Response.status(Status.OK).entity(json).build();
}
@POST
@@ -141,11 +147,11 @@ public class SubscriptionResource implements BaseJaxrsResource{
final @QueryParam(QUERY_REQUESTED_DT) String requestedDate,
final @QueryParam(QUERY_CALL_COMPLETION) @DefaultValue("false") Boolean callCompletion,
final @QueryParam(QUERY_CALL_TIMEOUT) @DefaultValue("3") long timeoutSec) {
-
+
SubscriptionCallCompletionCallback<Response> callback = new SubscriptionCallCompletionCallback<Response>() {
private boolean isImmediateOp = true;
-
+
@Override
public Response doOperation(CallContext ctx)
throws EntitlementUserApiException, InterruptedException,
@@ -168,13 +174,22 @@ public class SubscriptionResource implements BaseJaxrsResource{
if (operationResponse.getStatus() != Status.OK.getStatusCode()) {
return operationResponse;
}
+ try {
return getSubscription(subscriptionId);
+ } catch (EntitlementUserApiException e) {
+ if (e.getCode() == ErrorCode.ENT_GET_INVALID_BUNDLE_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.INTERNAL_SERVER_ERROR).build();
+ }
+
+ }
}
};
SubscriptionCallCompletion<Response> callCompletionCreation = new SubscriptionCallCompletion<Response>();
return callCompletionCreation.withSynchronization(callback, timeoutSec, callCompletion);
}
-
+
@PUT
@Path("/{subscriptionId:" + UUID_PATTERN + "}/uncancel")
@Produces(APPLICATION_JSON)
@@ -200,11 +215,11 @@ public class SubscriptionResource implements BaseJaxrsResource{
final @QueryParam(QUERY_REQUESTED_DT) String requestedDate,
final @QueryParam(QUERY_CALL_COMPLETION) @DefaultValue("false") Boolean callCompletion,
final @QueryParam(QUERY_CALL_TIMEOUT) @DefaultValue("3") long timeoutSec) {
-
+
SubscriptionCallCompletionCallback<Response> callback = new SubscriptionCallCompletionCallback<Response>() {
private boolean isImmediateOp = true;
-
+
@Override
public Response doOperation(CallContext ctx)
throws EntitlementUserApiException, InterruptedException,
@@ -230,7 +245,7 @@ public class SubscriptionResource implements BaseJaxrsResource{
SubscriptionCallCompletion<Response> callCompletionCreation = new SubscriptionCallCompletion<Response>();
return callCompletionCreation.withSynchronization(callback, timeoutSec, callCompletion);
}
-
+
private final static class CompletionUserRequestSubscription extends CompletionUserRequestBase {
public CompletionUserRequestSubscription(final UUID userToken) {
@@ -264,7 +279,7 @@ public class SubscriptionResource implements BaseJaxrsResource{
notifyForCompletion();
}
}
-
+
private interface SubscriptionCallCompletionCallback<T> {
public T doOperation(final CallContext ctx) throws EntitlementUserApiException, InterruptedException, TimeoutException;
public boolean isImmOperation();
@@ -272,7 +287,7 @@ public class SubscriptionResource implements BaseJaxrsResource{
}
private class SubscriptionCallCompletion<T> {
-
+
public Response withSynchronization(final SubscriptionCallCompletionCallback<T> callback, final long timeoutSec, final boolean callCompletion) {
CallContext ctx = context.createContext();
diff --git a/junction/src/main/java/com/ning/billing/junction/api/blocking/DefaultBlockingApi.java b/junction/src/main/java/com/ning/billing/junction/api/blocking/DefaultBlockingApi.java
index 27abad0..62878ad 100644
--- a/junction/src/main/java/com/ning/billing/junction/api/blocking/DefaultBlockingApi.java
+++ b/junction/src/main/java/com/ning/billing/junction/api/blocking/DefaultBlockingApi.java
@@ -24,6 +24,7 @@ import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.junction.dao.BlockingStateDao;
import com.ning.billing.util.clock.Clock;
diff --git a/junction/src/main/java/com/ning/billing/junction/block/DefaultBlockingChecker.java b/junction/src/main/java/com/ning/billing/junction/block/DefaultBlockingChecker.java
index 838a457..26e97cd 100644
--- a/junction/src/main/java/com/ning/billing/junction/block/DefaultBlockingChecker.java
+++ b/junction/src/main/java/com/ning/billing/junction/block/DefaultBlockingChecker.java
@@ -22,6 +22,7 @@ import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.Account;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
+import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.junction.api.Blockable;
@@ -30,7 +31,7 @@ import com.ning.billing.junction.api.BlockingState;
import com.ning.billing.junction.dao.BlockingStateDao;
public class DefaultBlockingChecker implements BlockingChecker {
-
+
private static class BlockingAggregator {
private boolean blockChange = false;
private boolean blockEntitlement= false;
@@ -42,14 +43,14 @@ public class DefaultBlockingChecker implements BlockingChecker {
blockEntitlement = blockEntitlement || state.isBlockEntitlement();
blockBilling = blockBilling || state.isBlockBilling();
}
-
+
public void or(BlockingAggregator state) {
if (state == null) { return; }
blockChange = blockChange || state.isBlockChange();
blockEntitlement = blockEntitlement || state.isBlockEntitlement();
blockBilling = blockBilling || state.isBlockBilling();
}
-
+
public boolean isBlockChange() {
return blockChange;
}
@@ -59,7 +60,7 @@ public class DefaultBlockingChecker implements BlockingChecker {
public boolean isBlockBilling() {
return blockBilling;
}
-
+
}
private static final Object TYPE_SUBSCRIPTION = "Subscription";
@@ -72,19 +73,19 @@ public class DefaultBlockingChecker implements BlockingChecker {
private final EntitlementUserApi entitlementApi;
private final BlockingStateDao dao;
-
+
@Inject
public DefaultBlockingChecker(EntitlementUserApi entitlementApi, BlockingStateDao dao) {
this.entitlementApi = entitlementApi;
this.dao = dao;
}
- public BlockingAggregator getBlockedStateSubscriptionId(UUID subscriptionId) {
- Subscription subscription = entitlementApi.getSubscriptionFromId(subscriptionId);
- return getBlockedStateSubscription(subscription);
+ public BlockingAggregator getBlockedStateSubscriptionId(UUID subscriptionId) throws EntitlementUserApiException {
+ Subscription subscription = entitlementApi.getSubscriptionFromId(subscriptionId);
+ return getBlockedStateSubscription(subscription);
}
-
- public BlockingAggregator getBlockedStateSubscription(Subscription subscription) {
+
+ public BlockingAggregator getBlockedStateSubscription(Subscription subscription) throws EntitlementUserApiException {
BlockingAggregator result = new BlockingAggregator();
if(subscription != null) {
BlockingState subscriptionState = subscription.getBlockingState();
@@ -98,11 +99,11 @@ public class DefaultBlockingChecker implements BlockingChecker {
return result;
}
- public BlockingAggregator getBlockedStateBundleId(UUID bundleId) {
+ public BlockingAggregator getBlockedStateBundleId(UUID bundleId) throws EntitlementUserApiException {
SubscriptionBundle bundle = entitlementApi.getBundleFromId(bundleId);
return getBlockedStateBundle(bundle);
- }
-
+ }
+
public BlockingAggregator getBlockedStateBundle(SubscriptionBundle bundle) {
BlockingAggregator result = getBlockedStateAccountId(bundle.getAccountId());
BlockingState bundleState = bundle.getBlockingState();
@@ -129,71 +130,97 @@ public class DefaultBlockingChecker implements BlockingChecker {
}
@Override
public void checkBlockedChange(Blockable blockable) throws BlockingApiException {
- if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_SUBSCRIPTION, blockable.getId().toString());
- } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_BUNDLE, blockable.getId().toString());
- } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_ACCOUNT, blockable.getId().toString());
+ try {
+ if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_SUBSCRIPTION, blockable.getId().toString());
+ } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_BUNDLE, blockable.getId().toString());
+ } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_ACCOUNT, blockable.getId().toString());
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
@Override
public void checkBlockedEntitlement(Blockable blockable) throws BlockingApiException {
- if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_SUBSCRIPTION, blockable.getId().toString());
- } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_BUNDLE, blockable.getId().toString());
- } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_ACCOUNT, blockable.getId().toString());
+ try {
+ if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_SUBSCRIPTION, blockable.getId().toString());
+ } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_BUNDLE, blockable.getId().toString());
+ } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_ACCOUNT, blockable.getId().toString());
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
@Override
public void checkBlockedBilling(Blockable blockable) throws BlockingApiException {
- if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_SUBSCRIPTION, blockable.getId().toString());
- } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_BUNDLE, blockable.getId().toString());
- } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_ACCOUNT, blockable.getId().toString());
+ try {
+ if(blockable instanceof Subscription && getBlockedStateSubscription((Subscription) blockable).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_SUBSCRIPTION, blockable.getId().toString());
+ } else if(blockable instanceof SubscriptionBundle && getBlockedStateBundle((SubscriptionBundle) blockable).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_BUNDLE, blockable.getId().toString());
+ } else if(blockable instanceof Account && getBlockedStateAccount((Account) blockable).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_ACCOUNT, blockable.getId().toString());
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
+
@Override
public void checkBlockedChange(UUID blockableId, Blockable.Type type) throws BlockingApiException {
- if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_SUBSCRIPTION, blockableId.toString());
- } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_BUNDLE, blockableId.toString());
- } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockChange()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_ACCOUNT, blockableId.toString());
+ try {
+ if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_SUBSCRIPTION, blockableId.toString());
+ } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_BUNDLE, blockableId.toString());
+ } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockChange()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_CHANGE, TYPE_ACCOUNT, blockableId.toString());
+
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
@Override
public void checkBlockedEntitlement(UUID blockableId, Blockable.Type type) throws BlockingApiException {
- if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_SUBSCRIPTION, blockableId.toString());
- } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_BUNDLE, blockableId.toString());
- } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockEntitlement()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_ACCOUNT, blockableId.toString());
+ try {
+ if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_SUBSCRIPTION, blockableId.toString());
+ } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_BUNDLE, blockableId.toString());
+ } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockEntitlement()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_ENTITLEMENT, TYPE_ACCOUNT, blockableId.toString());
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
@Override
public void checkBlockedBilling(UUID blockableId, Blockable.Type type) throws BlockingApiException {
- if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_SUBSCRIPTION, blockableId.toString());
- } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_BUNDLE, blockableId.toString());
- } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockBilling()) {
- throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_ACCOUNT, blockableId.toString());
+ try {
+ if(type == Blockable.Type.SUBSCRIPTION && getBlockedStateSubscriptionId(blockableId).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_SUBSCRIPTION, blockableId.toString());
+ } else if(type == Blockable.Type.SUBSCRIPTION_BUNDLE && getBlockedStateBundleId(blockableId).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_BUNDLE, blockableId.toString());
+ } else if(type == Blockable.Type.ACCOUNT && getBlockedStateAccountId(blockableId).isBlockBilling()) {
+ throw new BlockingApiException(ErrorCode.BLOCK_BLOCKED_ACTION,ACTION_BILLING, TYPE_ACCOUNT, blockableId.toString());
+ }
+ } catch (EntitlementUserApiException e) {
+ throw new BlockingApiException(e, ErrorCode.values()[e.getCode()]);
}
}
-
+
}
diff --git a/junction/src/main/java/com/ning/billing/junction/dao/BlockingStateSqlDao.java b/junction/src/main/java/com/ning/billing/junction/dao/BlockingStateSqlDao.java
index 22e3d07..4345f6d 100644
--- a/junction/src/main/java/com/ning/billing/junction/dao/BlockingStateSqlDao.java
+++ b/junction/src/main/java/com/ning/billing/junction/dao/BlockingStateSqlDao.java
@@ -39,7 +39,7 @@ import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingApiException;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.overdue.OverdueState;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.dao.BinderBase;
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccount.java b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccount.java
index b438d62..7f23f84 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccount.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccount.java
@@ -37,7 +37,7 @@ public class BlockingAccount implements Account {
private BlockingState blockingState = null;
private BlockingApi blockingApi;
- public BlockingAccount(Account account, BlockingApi blockingApi) {
+ public BlockingAccount( Account account, BlockingApi blockingApi) {
this.account = account;
this.blockingApi = blockingApi;
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccountUserApi.java b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccountUserApi.java
index 6e67325..38af49f 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccountUserApi.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingAccountUserApi.java
@@ -69,12 +69,12 @@ public class BlockingAccountUserApi implements AccountUserApi {
}
@Override
- public Account getAccountByKey(String key) {
+ public Account getAccountByKey(String key) throws AccountApiException {
return new BlockingAccount(userApi.getAccountByKey(key), blockingApi);
}
@Override
- public Account getAccountById(UUID accountId) {
+ public Account getAccountById(UUID accountId) throws AccountApiException {
return userApi.getAccountById(accountId);
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingEntitlementUserApi.java b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingEntitlementUserApi.java
index 14eba4b..3d340da 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingEntitlementUserApi.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingEntitlementUserApi.java
@@ -23,6 +23,7 @@ import java.util.UUID;
import org.joda.time.DateTime;
import com.google.inject.Inject;
+import com.ning.billing.ErrorCode;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
@@ -47,16 +48,30 @@ public class BlockingEntitlementUserApi implements EntitlementUserApi {
this.checker = checker;
}
- public SubscriptionBundle getBundleFromId(UUID id) {
- return new BlockingSubscriptionBundle(entitlementUserApi.getBundleFromId(id), blockingApi);
+ public SubscriptionBundle getBundleFromId(UUID id) throws EntitlementUserApiException {
+ SubscriptionBundle bundle = entitlementUserApi.getBundleFromId(id);
+ if(bundle == null) {
+ throw new EntitlementUserApiException(ErrorCode.ENT_GET_INVALID_BUNDLE_ID, id);
+ }
+ return new BlockingSubscriptionBundle(bundle, blockingApi);
}
- public Subscription getSubscriptionFromId(UUID id) {
- return new BlockingSubscription(entitlementUserApi.getSubscriptionFromId(id), blockingApi, checker);
+ public Subscription getSubscriptionFromId(UUID id) throws EntitlementUserApiException {
+ Subscription subscription = entitlementUserApi.getSubscriptionFromId(id);
+ if(subscription == null) {
+ throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_SUBSCRIPTION_ID, id);
+ }
+ return new BlockingSubscription(subscription, blockingApi, checker);
}
- public SubscriptionBundle getBundleForKey(String bundleKey) {
- return new BlockingSubscriptionBundle(entitlementUserApi.getBundleForKey(bundleKey), blockingApi);
+
+ public SubscriptionBundle getBundleForKey(String bundleKey) throws EntitlementUserApiException {
+ SubscriptionBundle bundle = entitlementUserApi.getBundleForKey(bundleKey);
+ if(bundle == null) {
+ throw new EntitlementUserApiException(ErrorCode.ENT_GET_INVALID_BUNDLE_KEY, bundleKey);
+ }
+
+ return new BlockingSubscriptionBundle(bundle, blockingApi);
}
public List<SubscriptionBundle> getBundlesForAccount(UUID accountId) {
@@ -93,8 +108,8 @@ public class BlockingEntitlementUserApi implements EntitlementUserApi {
public SubscriptionBundle createBundleForAccount(UUID accountId, String bundleKey, CallContext context)
throws EntitlementUserApiException {
try {
- checker.checkBlockedChange(accountId, Blockable.Type.ACCOUNT);
- return new BlockingSubscriptionBundle(entitlementUserApi.createBundleForAccount(accountId, bundleKey, context), blockingApi);
+ checker.checkBlockedChange(accountId, Blockable.Type.ACCOUNT);
+ return new BlockingSubscriptionBundle(entitlementUserApi.createBundleForAccount(accountId, bundleKey, context), blockingApi);
}catch (BlockingApiException e) {
throw new EntitlementUserApiException(e, e.getCode(), e.getMessage());
}
@@ -104,7 +119,7 @@ public class BlockingEntitlementUserApi implements EntitlementUserApi {
CallContext context) throws EntitlementUserApiException {
try {
checker.checkBlockedChange(bundleId, Blockable.Type.SUBSCRIPTION_BUNDLE);
- return new BlockingSubscription(createSubscription(bundleId, spec, requestedDate, context), blockingApi, checker);
+ return new BlockingSubscription(entitlementUserApi.createSubscription(bundleId, spec, requestedDate, context), blockingApi, checker);
}catch (BlockingApiException e) {
throw new EntitlementUserApiException(e, e.getCode(), e.getMessage());
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscription.java b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscription.java
index 32705f6..bae03ec 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscription.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscription.java
@@ -214,5 +214,10 @@ public class BlockingSubscription implements Subscription {
}
return blockingState;
}
+
+ public Subscription getDelegateSubscription() {
+ return subscription;
+ }
+
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BlockingCalculator.java b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BlockingCalculator.java
index ca993b9..ff38df9 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BlockingCalculator.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BlockingCalculator.java
@@ -39,7 +39,7 @@ import com.ning.billing.entitlement.api.user.SubscriptionEventTransition.Subscri
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
public class BlockingCalculator {
private final BlockingApi blockingApi;
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingApi.java b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingApi.java
index 46f18d0..d9ddb2b 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingApi.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingApi.java
@@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
+import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.account.api.MutableAccountData;
import com.ning.billing.catalog.api.CatalogApiException;
@@ -66,39 +67,43 @@ public class DefaultBillingApi implements BillingApi {
@Override
public SortedSet<BillingEvent> getBillingEventsForAccountAndUpdateAccountBCD(final UUID accountId) {
- Account account = accountApi.getAccountById(accountId);
CallContext context = factory.createCallContext(API_USER_NAME, CallOrigin.INTERNAL, UserType.SYSTEM);
List<SubscriptionBundle> bundles = entitlementUserApi.getBundlesForAccount(accountId);
SortedSet<BillingEvent> result = new TreeSet<BillingEvent>();
- for (final SubscriptionBundle bundle: bundles) {
- List<Subscription> subscriptions = entitlementUserApi.getSubscriptionsForBundle(bundle.getId());
-
- for (final Subscription subscription: subscriptions) {
- for (final SubscriptionEventTransition transition : subscription.getBillingTransitions()) {
- try {
- int bcd = bcdCalculator.calculateBcd(bundle, subscription, transition, account);
-
- if(account.getBillCycleDay() == 0) {
- MutableAccountData modifiedData = account.toMutableAccountData();
- modifiedData.setBillCycleDay(bcd);
- accountApi.updateAccount(account.getExternalKey(), modifiedData, context);
- }
+ try {
+ Account account = accountApi.getAccountById(accountId);
+ for (final SubscriptionBundle bundle: bundles) {
+ List<Subscription> subscriptions = entitlementUserApi.getSubscriptionsForBundle(bundle.getId());
+
+ for (final Subscription subscription: subscriptions) {
+ for (final SubscriptionEventTransition transition : subscription.getBillingTransitions()) {
+ try {
+ int bcd = bcdCalculator.calculateBcd(bundle, subscription, transition, account);
+
+ if(account.getBillCycleDay() == 0) {
+ MutableAccountData modifiedData = account.toMutableAccountData();
+ modifiedData.setBillCycleDay(bcd);
+ accountApi.updateAccount(account.getExternalKey(), modifiedData, context);
+ }
- BillingEvent event = new DefaultBillingEvent(account, transition, subscription, bcd, account.getCurrency());
- result.add(event);
- } catch (CatalogApiException e) {
- log.error("Failing to identify catalog components while creating BillingEvent from transition: " +
- transition.getId().toString(), e);
- } catch (Exception e) {
- log.warn("Failed while getting BillingEvent", e);
+ BillingEvent event = new DefaultBillingEvent(account, transition, subscription, bcd, account.getCurrency());
+ result.add(event);
+ } catch (CatalogApiException e) {
+ log.error("Failing to identify catalog components while creating BillingEvent from transition: " +
+ transition.getId().toString(), e);
+ } catch (Exception e) {
+ log.warn("Failed while getting BillingEvent", e);
+ }
}
}
}
+ }catch (AccountApiException e) {
+ log.warn("Failed while getting BillingEvent", e);
}
-
+
blockCalculator.insertBlockingEvents(result);
-
+
return result;
}
diff --git a/junction/src/test/java/com/ning/billing/junction/api/blocking/TestBlockingApi.java b/junction/src/test/java/com/ning/billing/junction/api/blocking/TestBlockingApi.java
index e26d4a5..1d814b8 100644
--- a/junction/src/test/java/com/ning/billing/junction/api/blocking/TestBlockingApi.java
+++ b/junction/src/test/java/com/ning/billing/junction/api/blocking/TestBlockingApi.java
@@ -39,6 +39,7 @@ import com.ning.billing.junction.MockModule;
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.junction.dao.TestBlockingDao;
import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
diff --git a/junction/src/test/java/com/ning/billing/junction/blocking/TestBlockingChecker.java b/junction/src/test/java/com/ning/billing/junction/blocking/TestBlockingChecker.java
index c9d6a4e..22869b7 100644
--- a/junction/src/test/java/com/ning/billing/junction/blocking/TestBlockingChecker.java
+++ b/junction/src/test/java/com/ning/billing/junction/blocking/TestBlockingChecker.java
@@ -35,7 +35,7 @@ import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApiException;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.junction.block.BlockingChecker;
import com.ning.billing.junction.block.DefaultBlockingChecker;
import com.ning.billing.junction.dao.BlockingStateDao;
diff --git a/junction/src/test/java/com/ning/billing/junction/dao/TestBlockingDao.java b/junction/src/test/java/com/ning/billing/junction/dao/TestBlockingDao.java
index 6652fc4..3fc73ec 100644
--- a/junction/src/test/java/com/ning/billing/junction/dao/TestBlockingDao.java
+++ b/junction/src/test/java/com/ning/billing/junction/dao/TestBlockingDao.java
@@ -35,7 +35,7 @@ import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.junction.MockModule;
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockEntitlementModule;
diff --git a/junction/src/test/java/com/ning/billing/junction/MockModule.java b/junction/src/test/java/com/ning/billing/junction/MockModule.java
index 3054f1f..5651c8b 100644
--- a/junction/src/test/java/com/ning/billing/junction/MockModule.java
+++ b/junction/src/test/java/com/ning/billing/junction/MockModule.java
@@ -24,10 +24,13 @@ import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.junction.glue.JunctionModule;
+import com.ning.billing.mock.glue.MockDbHelperModule;
import com.ning.billing.util.callcontext.CallContextFactory;
import com.ning.billing.util.callcontext.DefaultCallContextFactory;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
+import com.ning.billing.util.clock.MockClockModule;
+import com.ning.billing.util.glue.CallContextModule;
public class MockModule extends JunctionModule {
@@ -36,21 +39,10 @@ public class MockModule extends JunctionModule {
@Override
protected void configure() {
super.configure();
- bind(Clock.class).to(ClockMock.class).asEagerSingleton();
- bind(ClockMock.class).asEagerSingleton();
- bind(CallContextFactory.class).to(DefaultCallContextFactory.class).asEagerSingleton();
-
- final MysqlTestingHelper helper = new MysqlTestingHelper();
- bind(MysqlTestingHelper.class).toInstance(helper);
- if (helper.isUsingLocalInstance()) {
- bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
- final DbiConfig config = new ConfigurationObjectFactory(System.getProperties()).build(DbiConfig.class);
- bind(DbiConfig.class).toInstance(config);
- } else {
- final IDBI dbi = helper.getDBI();
- bind(IDBI.class).toInstance(dbi);
- }
+ install(new MockClockModule());
+ install(new MockDbHelperModule());
+ install(new CallContextModule());
install(new CatalogModule());
}
diff --git a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java
index de9a18c..874ba13 100644
--- a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java
+++ b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java
@@ -52,7 +52,7 @@ import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.junction.dao.BlockingStateDao;
import com.ning.billing.junction.plumbing.billing.BlockingCalculator.DisabledDuration;
import com.ning.billing.mock.BrainDeadProxyFactory;
diff --git a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultEntitlementBillingApi.java b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultEntitlementBillingApi.java
index 044fe43..d43af31 100644
--- a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultEntitlementBillingApi.java
+++ b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultEntitlementBillingApi.java
@@ -65,10 +65,10 @@ import com.ning.billing.entitlement.events.EntitlementEvent.EventType;
import com.ning.billing.entitlement.events.user.ApiEventType;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.Blockable;
+import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
import com.ning.billing.lifecycle.KillbillService.ServiceException;
import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
diff --git a/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java b/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java
index 68c5be2..82ad93c 100644
--- a/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java
+++ b/overdue/src/main/java/com/ning/billing/overdue/applicator/OverdueStateApplicator.java
@@ -23,7 +23,8 @@ import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.BlockingApi;
-import com.ning.billing.junction.api.blocking.DefaultBlockingState;
+import com.ning.billing.junction.api.DefaultBlockingState;
+
import com.ning.billing.overdue.OverdueService;
import com.ning.billing.overdue.OverdueState;
import com.ning.billing.overdue.config.api.OverdueError;
diff --git a/overdue/src/test/java/com/ning/billing/overdue/notification/TestOverdueCheckNotifier.java b/overdue/src/test/java/com/ning/billing/overdue/notification/TestOverdueCheckNotifier.java
index 8d89999..3086274 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/notification/TestOverdueCheckNotifier.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/notification/TestOverdueCheckNotifier.java
@@ -135,7 +135,6 @@ public class TestOverdueCheckNotifier {
bind(CustomFieldDao.class).to(AuditedCustomFieldDao.class).asEagerSingleton();
bind(GlobalLocker.class).to(MySqlGlobalLocker.class).asEagerSingleton();
bind(ChargeThruApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class));
- bind(EntitlementUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class));
install(new MockJunctionModule());
}
});
diff --git a/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentApi.java b/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentApi.java
index 0d9c19a..229fb5a 100644
--- a/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentApi.java
+++ b/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentApi.java
@@ -30,6 +30,7 @@ import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
+import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.config.PaymentConfig;
import com.ning.billing.invoice.api.Invoice;
@@ -54,11 +55,11 @@ public class DefaultPaymentApi implements PaymentApi {
@Inject
public DefaultPaymentApi(PaymentProviderPluginRegistry pluginRegistry,
- AccountUserApi accountUserApi,
- InvoicePaymentApi invoicePaymentApi,
- RetryService retryService,
- PaymentDao paymentDao,
- PaymentConfig config) {
+ AccountUserApi accountUserApi,
+ InvoicePaymentApi invoicePaymentApi,
+ RetryService retryService,
+ PaymentDao paymentDao,
+ PaymentConfig config) {
this.pluginRegistry = pluginRegistry;
this.accountUserApi = accountUserApi;
this.invoicePaymentApi = invoicePaymentApi;
@@ -77,9 +78,12 @@ public class DefaultPaymentApi implements PaymentApi {
String paymentProviderName = null;
if (accountKey != null) {
- final Account account = accountUserApi.getAccountByKey(accountKey);
- if (account != null) {
+ Account account;
+ try {
+ account = accountUserApi.getAccountByKey(accountKey);
return getPaymentProviderPlugin(account);
+ } catch (AccountApiException e) {
+ log.error("Error getting payment provider plugin.", e);
}
}
@@ -134,37 +138,57 @@ public class DefaultPaymentApi implements PaymentApi {
@Override
public List<Either<PaymentErrorEvent, PaymentInfoEvent>> createPayment(String accountKey, List<String> invoiceIds, CallContext context) {
- final Account account = accountUserApi.getAccountByKey(accountKey);
- return createPayment(account, invoiceIds, context);
+ try {
+ final Account account = accountUserApi.getAccountByKey(accountKey);
+ return createPayment(account, invoiceIds, context);
+ } catch (AccountApiException e) {
+ log.error("Error getting payment provider plugin.", e);
+ List<Either<PaymentErrorEvent, PaymentInfoEvent>> result = new ArrayList<Either<PaymentErrorEvent, PaymentInfoEvent>>();
+ result.add(new Either.Left<PaymentErrorEvent, PaymentInfoEvent>((PaymentErrorEvent) new DefaultPaymentError("createPaymentError", e.getMessage(),
+ null,
+ null,
+ context.getUserToken())));
+ return result;
+ }
+
}
@Override
public Either<PaymentErrorEvent, PaymentInfoEvent> createPaymentForPaymentAttempt(UUID paymentAttemptId, CallContext context) {
-
+
PaymentAttempt paymentAttempt = paymentDao.getPaymentAttemptById(paymentAttemptId);
if (paymentAttempt != null) {
- Invoice invoice = invoicePaymentApi.getInvoice(paymentAttempt.getInvoiceId());
- Account account = accountUserApi.getAccountById(paymentAttempt.getAccountId());
-
- if (invoice != null && account != null) {
- if (invoice.getBalance().compareTo(BigDecimal.ZERO) <= 0 ) {
- // TODO: send a notification that invoice was ignored?
- log.info("Received invoice for payment with outstanding amount of 0 {} ", invoice);
- return Either.left((PaymentErrorEvent) new DefaultPaymentError("invoice_balance_0",
- "Invoice balance was 0 or less",
- paymentAttempt.getAccountId(),
- paymentAttempt.getInvoiceId(),
- context.getUserToken()));
- }
- else {
- PaymentAttempt newPaymentAttempt = new PaymentAttempt.Builder(paymentAttempt)
- .setRetryCount(paymentAttempt.getRetryCount() + 1)
- .setPaymentAttemptId(UUID.randomUUID())
- .build();
-
- paymentDao.createPaymentAttempt(newPaymentAttempt, context);
- return processPayment(getPaymentProviderPlugin(account), account, invoice, newPaymentAttempt, context);
+ try {
+ Invoice invoice = invoicePaymentApi.getInvoice(paymentAttempt.getInvoiceId());
+ Account account = accountUserApi.getAccountById(paymentAttempt.getAccountId());
+
+ if (invoice != null && account != null) {
+ if (invoice.getBalance().compareTo(BigDecimal.ZERO) <= 0 ) {
+ // TODO: send a notification that invoice was ignored?
+ log.info("Received invoice for payment with outstanding amount of 0 {} ", invoice);
+ return Either.left((PaymentErrorEvent) new DefaultPaymentError("invoice_balance_0",
+ "Invoice balance was 0 or less",
+ paymentAttempt.getAccountId(),
+ paymentAttempt.getInvoiceId(),
+ context.getUserToken()));
+ }
+ else {
+ PaymentAttempt newPaymentAttempt = new PaymentAttempt.Builder(paymentAttempt)
+ .setRetryCount(paymentAttempt.getRetryCount() + 1)
+ .setPaymentAttemptId(UUID.randomUUID())
+ .build();
+
+ paymentDao.createPaymentAttempt(newPaymentAttempt, context);
+ return processPayment(getPaymentProviderPlugin(account), account, invoice, newPaymentAttempt, context);
+ }
}
+ } catch (AccountApiException e) {
+ log.error("Error creating payment attempt.", e);
+ return new Either.Left<PaymentErrorEvent, PaymentInfoEvent>((PaymentErrorEvent) new DefaultPaymentError("createPaymentError", e.getMessage(),
+ null,
+ null,
+ context.getUserToken()));
+
}
}
return Either.left((PaymentErrorEvent) new DefaultPaymentError("retry_payment_error",
@@ -187,13 +211,13 @@ public class DefaultPaymentApi implements PaymentApi {
log.debug("Received invoice for payment with balance of 0 {} ", invoice);
}
else if (invoice.isMigrationInvoice()) {
- log.info("Received invoice for payment that is a migration invoice - don't know how to handle those yet: {}", invoice);
- Either<PaymentErrorEvent, PaymentInfoEvent> result = Either.left((PaymentErrorEvent) new DefaultPaymentError("migration invoice",
+ log.info("Received invoice for payment that is a migration invoice - don't know how to handle those yet: {}", invoice);
+ Either<PaymentErrorEvent, PaymentInfoEvent> result = Either.left((PaymentErrorEvent) new DefaultPaymentError("migration invoice",
"Invoice balance was a migration invoice",
account.getId(),
UUID.fromString(invoiceId),
context.getUserToken()));
- processedPaymentsOrErrors.add(result);
+ processedPaymentsOrErrors.add(result);
}
else {
PaymentAttempt paymentAttempt = paymentDao.createPaymentAttempt(invoice, context);
@@ -206,7 +230,7 @@ public class DefaultPaymentApi implements PaymentApi {
}
private Either<PaymentErrorEvent, PaymentInfoEvent> processPayment(PaymentProviderPlugin plugin, Account account, Invoice invoice,
- PaymentAttempt paymentAttempt, CallContext context) {
+ PaymentAttempt paymentAttempt, CallContext context) {
Either<PaymentErrorEvent, PaymentInfoEvent> paymentOrError = plugin.processInvoice(account, invoice);
PaymentInfoEvent paymentInfo = null;
@@ -245,12 +269,12 @@ public class DefaultPaymentApi implements PaymentApi {
}
invoicePaymentApi.notifyOfPaymentAttempt(new DefaultInvoicePayment(paymentAttempt.getPaymentAttemptId(),
- invoice.getId(),
- paymentAttempt.getPaymentAttemptDate(),
- paymentInfo == null || paymentInfo.getStatus().equalsIgnoreCase("Error") ? null : paymentInfo.getAmount(),
-// paymentInfo.getRefundAmount(), TODO
- paymentInfo == null || paymentInfo.getStatus().equalsIgnoreCase("Error") ? null : invoice.getCurrency()),
- context);
+ invoice.getId(),
+ paymentAttempt.getPaymentAttemptDate(),
+ paymentInfo == null || paymentInfo.getStatus().equalsIgnoreCase("Error") ? null : paymentInfo.getAmount(),
+ // paymentInfo.getRefundAmount(), TODO
+ paymentInfo == null || paymentInfo.getStatus().equalsIgnoreCase("Error") ? null : invoice.getCurrency()),
+ context);
return paymentOrError;
}
@@ -294,9 +318,18 @@ public class DefaultPaymentApi implements PaymentApi {
@Override
public Either<PaymentErrorEvent, Void> updatePaymentProviderAccountContact(String externalKey, CallContext context) {
- Account account = accountUserApi.getAccountByKey(externalKey);
- final PaymentProviderPlugin plugin = getPaymentProviderPlugin(account);
- return plugin.updatePaymentProviderAccountExistingContact(account);
+ try {
+ Account account = accountUserApi.getAccountByKey(externalKey);
+ final PaymentProviderPlugin plugin = getPaymentProviderPlugin(account);
+ return plugin.updatePaymentProviderAccountExistingContact(account);
+ } catch (AccountApiException e) {
+ log.error("Error updating payment provider account contact.", e);
+ return new Either.Left<PaymentErrorEvent, Void>((PaymentErrorEvent) new DefaultPaymentError("updatePaymentProviderAccountContactError", e.getMessage(),
+ null,
+ null,
+ context.getUserToken()));
+
+ }
}
@Override
@@ -306,8 +339,8 @@ public class DefaultPaymentApi implements PaymentApi {
@Override
public List<Either<PaymentErrorEvent, PaymentInfoEvent>> createRefund(Account account,
- List<String> invoiceIds,
- CallContext context) {
+ List<String> invoiceIds,
+ CallContext context) {
final PaymentProviderPlugin plugin = getPaymentProviderPlugin(account);
return plugin.processRefund(account);
}
diff --git a/payment/src/main/java/com/ning/billing/payment/RequestProcessor.java b/payment/src/main/java/com/ning/billing/payment/RequestProcessor.java
index 45afaa7..a1ccd55 100644
--- a/payment/src/main/java/com/ning/billing/payment/RequestProcessor.java
+++ b/payment/src/main/java/com/ning/billing/payment/RequestProcessor.java
@@ -19,17 +19,13 @@ package com.ning.billing.payment;
import java.util.Arrays;
import java.util.List;
-import com.ning.billing.util.callcontext.CallContext;
-import com.ning.billing.util.callcontext.CallOrigin;
-import com.ning.billing.util.callcontext.DefaultCallContext;
-import com.ning.billing.util.callcontext.UserType;
-import com.ning.billing.util.clock.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
+import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.payment.api.Either;
@@ -39,6 +35,11 @@ import com.ning.billing.payment.api.PaymentInfoEvent;
import com.ning.billing.payment.provider.PaymentProviderPluginRegistry;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.Bus.EventBusException;
+import com.ning.billing.util.callcontext.CallContext;
+import com.ning.billing.util.callcontext.CallOrigin;
+import com.ning.billing.util.callcontext.DefaultCallContext;
+import com.ning.billing.util.callcontext.UserType;
+import com.ning.billing.util.clock.Clock;
public class RequestProcessor {
public static final String PAYMENT_PROVIDER_KEY = "paymentProvider";
@@ -79,6 +80,9 @@ public class RequestProcessor {
}
}
}
+ catch(AccountApiException e) {
+ log.warn("could not process invoice payment", e);
+ }
catch (EventBusException ex) {
throw new RuntimeException(ex);
}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockClockModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockClockModule.java
new file mode 100644
index 0000000..82605ae
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockClockModule.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2010-2011 Ning, Inc.
+ *
+ * Ning 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 com.ning.billing.mock.glue;
+
+import com.google.inject.AbstractModule;
+import com.ning.billing.util.clock.Clock;
+import com.ning.billing.util.clock.ClockMock;
+
+public class MockClockModule extends AbstractModule {
+
+ @Override
+ protected void configure() {
+ bind(Clock.class).to(ClockMock.class).asEagerSingleton();
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockDbHelperModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockDbHelperModule.java
new file mode 100644
index 0000000..0487e0d
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockDbHelperModule.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2010-2011 Ning, Inc.
+ *
+ * Ning 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 com.ning.billing.mock.glue;
+
+import org.skife.config.ConfigurationObjectFactory;
+import org.skife.jdbi.v2.IDBI;
+
+import com.google.inject.AbstractModule;
+import com.ning.billing.dbi.DBIProvider;
+import com.ning.billing.dbi.DbiConfig;
+import com.ning.billing.dbi.MysqlTestingHelper;
+
+public class MockDbHelperModule extends AbstractModule {
+
+
+ @Override
+ protected void configure() {
+ installMysqlTestingHelper();
+ }
+
+ protected void installMysqlTestingHelper() {
+
+ final MysqlTestingHelper helper = new MysqlTestingHelper();
+ bind(MysqlTestingHelper.class).toInstance(helper);
+ if (helper.isUsingLocalInstance()) {
+ bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
+ final DbiConfig config = new ConfigurationObjectFactory(System.getProperties()).build(DbiConfig.class);
+ bind(DbiConfig.class).toInstance(config);
+ } else {
+ final IDBI dbi = helper.getDBI();
+ bind(IDBI.class).toInstance(dbi);
+ }
+
+ }
+
+}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockJunctionModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockJunctionModule.java
index f39659f..d21806d 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockJunctionModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockJunctionModule.java
@@ -34,6 +34,7 @@ public class MockJunctionModule extends AbstractModule {
installBlockingApi();
installAccountUserApi();
installBillingApi();
+ installEntitlementUserApi();
}
protected void installBillingApi() {
diff --git a/util/src/test/java/com/ning/billing/util/clock/ClockMock.java b/util/src/test/java/com/ning/billing/util/clock/ClockMock.java
index 8787cd1..9e51a80 100644
--- a/util/src/test/java/com/ning/billing/util/clock/ClockMock.java
+++ b/util/src/test/java/com/ning/billing/util/clock/ClockMock.java
@@ -153,4 +153,10 @@ public class ClockMock extends DefaultClock {
return truncateMs(input.plus(deltaFromRealityMs));
}
+ @Override
+ public String toString() {
+ return getUTCNow().toString();
+ }
+
+
}
diff --git a/util/src/test/java/com/ning/billing/util/clock/MockClockModule.java b/util/src/test/java/com/ning/billing/util/clock/MockClockModule.java
index 89de280..a8f0605 100644
--- a/util/src/test/java/com/ning/billing/util/clock/MockClockModule.java
+++ b/util/src/test/java/com/ning/billing/util/clock/MockClockModule.java
@@ -23,7 +23,8 @@ public class MockClockModule extends AbstractModule {
@Override
protected void configure() {
- bind(Clock.class).to(ClockMock.class).asEagerSingleton();
+ bind(Clock.class).to(ClockMock.class).asEagerSingleton();
+ bind(ClockMock.class).asEagerSingleton();
}
}