killbill-aplcache
Changes
account/pom.xml 2(+1 -1)
analytics/pom.xml 3(+1 -2)
analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java 243(+169 -74)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionBinder.java 27(+3 -24)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldMapper.java 8(+7 -1)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.java 7(+4 -3)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionMapper.java 61(+30 -31)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.java 11(+9 -2)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagMapper.java 7(+6 -1)
analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.java 7(+4 -3)
analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransition.java 90(+68 -22)
analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionField.java 43(+34 -9)
analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionTag.java 36(+30 -6)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.sql.stg 19(+11 -8)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountSqlDao.sql.stg 33(+28 -5)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.sql.stg 19(+11 -8)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.sql.stg 24(+2 -22)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.sql.stg 73(+18 -55)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.sql.stg 38(+36 -2)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.sql.stg 20(+15 -5)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.sql.stg 22(+14 -8)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.sql.stg 71(+57 -14)
analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.sql.stg 22(+14 -8)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountFieldSqlDao.java 34(+19 -15)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountTagSqlDao.java 34(+19 -15)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceItemSqlDao.java 27(+9 -18)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentFieldSqlDao.java 4(+2 -2)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentSqlDao.java 77(+32 -45)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentTagSqlDao.java 4(+2 -2)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessOverdueStatusSqlDao.java 26(+14 -12)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionFieldSqlDao.java 36(+21 -15)
analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionTagSqlDao.java 36(+21 -15)
analytics/src/test/java/com/ning/billing/analytics/MockBusinessSubscriptionTransitionSqlDao.java 51(+50 -1)
analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoicePayment.java 34(+11 -23)
analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionEvent.java 5(+2 -3)
analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransition.java 45(+30 -15)
analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionField.java 10(+9 -1)
analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionTag.java 14(+12 -2)
analytics/src/test/java/com/ning/billing/analytics/TestBusinessSubscriptionTransitionRecorder.java 61(+28 -33)
api/pom.xml 2(+1 -1)
beatrix/pom.xml 2(+1 -1)
beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java 14(+7 -7)
beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java 294(+294 -0)
catalog/pom.xml 7(+6 -1)
entitlement/pom.xml 7(+6 -1)
entitlement/src/main/java/com/ning/billing/entitlement/api/migration/DefaultEntitlementMigrationApi.java 44(+19 -25)
entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/DefaultEntitlementTimelineApi.java 57(+18 -39)
entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/RepairSubscriptionFactory.java 6(+3 -3)
entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/SubscriptionDataRepair.java 34(+14 -20)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEffectiveSubscriptionEvent.java 55(+55 -0)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEntitlementUserApi.java 31(+13 -18)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultRequestedSubscriptionEvent.java 61(+61 -0)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionApiService.java 120(+52 -68)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionEvent.java 238(+78 -160)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionFactory.java 21(+13 -8)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundleData.java 72(+58 -14)
entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionTransitionData.java 141(+119 -22)
entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/AuditedEntitlementDao.java 255(+143 -112)
entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/RepairEntitlementDao.java 57(+27 -30)
entitlement/src/main/resources/com/ning/billing/entitlement/engine/dao/BundleSqlDao.sql.stg 5(+2 -3)
entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationMemory.java 10(+4 -6)
entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestApiBaseRepair.java 13(+3 -10)
entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithAO.java 45(+7 -38)
entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithError.java 61(+11 -50)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelMemory.java 10(+4 -6)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlan.java 40(+1 -39)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanMemory.java 15(+6 -9)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanSql.java 16(+7 -9)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateMemory.java 13(+5 -8)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateMemory.java 2(+0 -2)
entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateSql.java 5(+2 -3)
entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoMemory.java 41(+15 -26)
entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoSql.java 53(+4 -49)
entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuiteWithEmbeddedDB.java 22(+22 -0)
invoice/pom.xml 2(+1 -1)
invoice/src/main/java/com/ning/billing/invoice/api/invoice/DefaultInvoicePaymentApi.java 44(+21 -23)
invoice/src/main/java/com/ning/billing/invoice/api/migration/DefaultInvoiceMigrationApi.java 21(+19 -2)
invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDateNotifier.java 46(+21 -25)
invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDatePoster.java 19(+15 -4)
invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceFormatter.java 53(+40 -13)
invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java 32(+21 -11)
invoice/src/main/java/com/ning/billing/invoice/template/translator/DefaultInvoiceTranslator.java 2(+1 -1)
invoice/src/main/resources/com/ning/billing/invoice/dao/FixedPriceInvoiceItemSqlDao.sql.stg 82(+0 -82)
invoice/src/test/java/com/ning/billing/invoice/api/migration/MockModuleNoEntitlement.java 27(+4 -23)
invoice/src/test/java/com/ning/billing/invoice/api/migration/TestDefaultInvoiceMigrationApi.java 83(+33 -50)
invoice/src/test/java/com/ning/billing/invoice/generator/TestDefaultInvoiceGenerator.java 128(+84 -44)
invoice/src/test/java/com/ning/billing/invoice/generator/TestDefaultInvoiceGeneratorUnit.java 332(+332 -0)
invoice/src/test/java/com/ning/billing/invoice/notification/TestNextBillingDateNotifier.java 53(+15 -38)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/GenericProRationTests.java 1(+0 -1)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/TestDoubleProRation.java 21(+10 -11)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/TestLeadingProRation.java 23(+11 -12)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/TestTrailingProRation.java 15(+7 -8)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/GenericProRationTestBase.java 31(+15 -16)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/GenericProRationTests.java 1(+0 -1)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/TestDoubleProRation.java 21(+10 -11)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/TestLeadingProRation.java 23(+11 -12)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/TestProRation.java 39(+19 -20)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/TestTrailingProRation.java 15(+7 -8)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/ProRationInAdvanceTestBase.java 1(+0 -1)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/GenericProRationTests.java 1(+0 -1)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/TestDoubleProRation.java 21(+10 -11)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/TestLeadingProRation.java 23(+11 -12)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/TestProRation.java 39(+19 -20)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/TestTrailingProRation.java 15(+7 -8)
invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/TestValidationProRation.java 16(+8 -8)
invoice/src/test/resources/com/ning/billing/util/template/translation/InvoiceTranslation_en_US.properties 13(+6 -7)
jaxrs/pom.xml 2(+1 -1)
junction/pom.xml 2(+1 -1)
junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscriptionBundle.java 48(+42 -6)
junction/src/main/java/com/ning/billing/junction/plumbing/billing/BillCycleDayCalculator.java 4(+2 -2)
junction/src/test/java/com/ning/billing/junction/plumbing/billing/MockSubscription.java 119(+0 -119)
junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBillingApi.java 239(+102 -137)
junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBlockingCalculator.java 69(+25 -44)
junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultBillingEvent.java 22(+9 -13)
overdue/pom.xml 12(+11 -1)
overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckNotifier.java 64(+32 -32)
overdue/src/test/java/com/ning/billing/overdue/applicator/OverdueListenerTesterModule.java 21(+7 -14)
overdue/src/test/java/com/ning/billing/overdue/applicator/TestOverdueStateApplicator.java 46(+37 -9)
overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculator.java 32(+13 -19)
overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculatorBundle.java 96(+46 -50)
overdue/src/test/java/com/ning/billing/overdue/notification/TestOverdueCheckNotifier.java 52(+15 -37)
payment/pom.xml 7(+6 -1)
payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentProviderPlugin.java 12(+9 -3)
pom.xml 2(+1 -1)
server/pom.xml 2(+1 -1)
util/pom.xml 2(+1 -1)
util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueueService.java 4(+2 -2)
util/src/main/java/com/ning/billing/util/template/translation/DefaultCatalogTranslator.java 2(+1 -1)
util/src/main/resources/com/ning/billing/util/notificationq/dao/NotificationSqlDao.sql.stg 32(+32 -0)
util/src/main/resources/com/ning/billing/util/template/translation/CatalogTranslation_en_US.properties 2(+0 -2)
util/src/main/resources/com/ning/billing/util/template/translation/CatalogTranslation_fr_CA.properties 1(+0 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagCreationEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionCreationEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionDeletionEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDeletionEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionCreationEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionDeletionEvent.java 3(+2 -1)
util/src/test/java/com/ning/billing/util/template/translation/TestDefaultTranslatorBase.java 51(+51 -0)
Details
account/pom.xml 2(+1 -1)
diff --git a/account/pom.xml b/account/pom.xml
index 1bf852c..441e961 100644
--- a/account/pom.xml
+++ b/account/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-account</artifactId>
diff --git a/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java b/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java
index c2273de..b540d4a 100644
--- a/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java
+++ b/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java
@@ -41,9 +41,9 @@ public class DefaultAccount extends EntityBase implements Account {
private final String externalKey;
private final String email;
private final String name;
- private final int firstNameLength;
+ private final Integer firstNameLength;
private final Currency currency;
- private final int billCycleDay;
+ private final Integer billCycleDay;
private final UUID paymentMethodId;
private final DateTimeZone timeZone;
private final String locale;
@@ -55,8 +55,8 @@ public class DefaultAccount extends EntityBase implements Account {
private final String country;
private final String postalCode;
private final String phone;
- private final boolean isMigrated;
- private final boolean isNotifiedForInvoices;
+ private final Boolean isMigrated;
+ private final Boolean isNotifiedForInvoices;
public DefaultAccount(final AccountData data) {
this(UUID.randomUUID(), data);
@@ -81,13 +81,13 @@ public class DefaultAccount extends EntityBase implements Account {
* This call is used for testing and update from an existing account
*/
public DefaultAccount(final UUID id, final String externalKey, final String email,
- final String name, final int firstNameLength,
- final Currency currency, final int billCycleDay, final UUID paymentMethodId,
+ final String name, final Integer firstNameLength,
+ final Currency currency, final Integer billCycleDay, final UUID paymentMethodId,
final DateTimeZone timeZone, final String locale,
final String address1, final String address2, final String companyName,
final String city, final String stateOrProvince, final String country,
final String postalCode, final String phone,
- final boolean isMigrated, final boolean isNotifiedForInvoices) {
+ final Boolean isMigrated, final Boolean isNotifiedForInvoices) {
super(id);
this.externalKey = externalKey;
this.email = email;
diff --git a/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java b/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java
index 8e162f7..9e7faf8 100644
--- a/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java
+++ b/account/src/main/java/com/ning/billing/account/dao/AuditedAccountDao.java
@@ -140,11 +140,11 @@ public class AuditedAccountDao implements AccountDao {
transactional.update(account, context);
final Long recordId = accountSqlDao.getRecordId(accountId.toString());
- final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.INSERT);
+ final EntityHistory<Account> history = new EntityHistory<Account>(accountId, recordId, account, ChangeType.UPDATE);
accountSqlDao.insertHistoryFromTransaction(history, context);
final Long historyRecordId = accountSqlDao.getHistoryRecordId(recordId);
- final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.INSERT);
+ final EntityAudit audit = new EntityAudit(TableName.ACCOUNT_HISTORY, historyRecordId, ChangeType.UPDATE);
accountSqlDao.insertAuditFromTransaction(audit, context);
final AccountChangeEvent changeEvent = new DefaultAccountChangeEvent(accountId, context.getUserToken(), currentAccount, account);
diff --git a/account/src/test/java/com/ning/billing/account/AccountTestSuite.java b/account/src/test/java/com/ning/billing/account/AccountTestSuite.java
new file mode 100644
index 0000000..aa2eb9e
--- /dev/null
+++ b/account/src/test/java/com/ning/billing/account/AccountTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.account;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class AccountTestSuite extends KillbillTestSuite {
+}
diff --git a/account/src/test/java/com/ning/billing/account/AccountTestSuiteWithEmbeddedDB.java b/account/src/test/java/com/ning/billing/account/AccountTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..24fb47f
--- /dev/null
+++ b/account/src/test/java/com/ning/billing/account/AccountTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.account;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class AccountTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/account/src/test/java/com/ning/billing/account/api/user/TestDefaultAccountUserApi.java b/account/src/test/java/com/ning/billing/account/api/user/TestDefaultAccountUserApi.java
index 5d4657b..6de32f6 100644
--- a/account/src/test/java/com/ning/billing/account/api/user/TestDefaultAccountUserApi.java
+++ b/account/src/test/java/com/ning/billing/account/api/user/TestDefaultAccountUserApi.java
@@ -24,6 +24,7 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.ning.billing.account.AccountTestSuite;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.account.api.DefaultAccount;
@@ -37,7 +38,7 @@ import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallContextFactory;
-public class TestDefaultAccountUserApi {
+public class TestDefaultAccountUserApi extends AccountTestSuite {
private final CallContextFactory factory = Mockito.mock(CallContextFactory.class);
private final CallContext callContext = Mockito.mock(CallContext.class);
diff --git a/account/src/test/java/com/ning/billing/account/api/user/TestEventJson.java b/account/src/test/java/com/ning/billing/account/api/user/TestEventJson.java
index 8853ad6..a15d101 100644
--- a/account/src/test/java/com/ning/billing/account/api/user/TestEventJson.java
+++ b/account/src/test/java/com/ning/billing/account/api/user/TestEventJson.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.account.api.user;
import java.util.ArrayList;
@@ -22,18 +23,18 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.account.AccountTestSuite;
import com.ning.billing.account.api.AccountChangeEvent;
import com.ning.billing.account.api.ChangedField;
import com.ning.billing.account.api.DefaultChangedField;
import com.ning.billing.account.api.user.DefaultAccountCreationEvent.DefaultAccountData;
import com.ning.billing.util.jackson.ObjectMapper;
-public class TestEventJson {
+public class TestEventJson extends AccountTestSuite {
private final ObjectMapper mapper = new ObjectMapper();
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testDefaultAccountChangeEvent() throws Exception {
-
final List<ChangedField> changes = new ArrayList<ChangedField>();
changes.add(new DefaultChangedField("fieldXX", "valueX", "valueXXX"));
changes.add(new DefaultChangedField("fieldYY", "valueY", "valueYYY"));
@@ -46,17 +47,15 @@ public class TestEventJson {
Assert.assertTrue(obj.equals(e));
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testAccountCreationEvent() throws Exception {
-
final DefaultAccountData data = new DefaultAccountData("dsfdsf", "bobo", 3, "bobo@yahoo.com", 12, "USD", UUID.randomUUID(),
- "UTC", "US", "21 avenue", "", "Gling", "San Franciso", "CA", "94110", "USA", "4126789887", false, false);
+ "UTC", "US", "21 avenue", "", "Gling", "San Franciso", "CA", "94110", "USA", "4126789887", false, false);
final DefaultAccountCreationEvent e = new DefaultAccountCreationEvent(data, UUID.randomUUID(), UUID.randomUUID());
final String json = mapper.writeValueAsString(e);
final Class<?> claz = Class.forName(DefaultAccountCreationEvent.class.getName());
final Object obj = mapper.readValue(json, claz);
Assert.assertTrue(obj.equals(e));
-
}
}
diff --git a/account/src/test/java/com/ning/billing/account/dao/AccountDaoTestBase.java b/account/src/test/java/com/ning/billing/account/dao/AccountDaoTestBase.java
index 0635c4e..463afe7 100644
--- a/account/src/test/java/com/ning/billing/account/dao/AccountDaoTestBase.java
+++ b/account/src/test/java/com/ning/billing/account/dao/AccountDaoTestBase.java
@@ -18,15 +18,10 @@ package com.ning.billing.account.dao;
import java.io.IOException;
-import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
-import org.skife.jdbi.v2.TransactionCallback;
-import org.skife.jdbi.v2.TransactionStatus;
-import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.account.AccountTestSuiteWithEmbeddedDB;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.bus.DefaultBusService;
@@ -37,14 +32,11 @@ import com.ning.billing.util.callcontext.DefaultCallContextFactory;
import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
-import com.ning.billing.util.io.IOUtils;
import com.ning.billing.util.tag.api.user.TagEventBuilder;
import static org.testng.Assert.fail;
-public abstract class AccountDaoTestBase {
- private final MysqlTestingHelper helper = new MysqlTestingHelper();
-
+public abstract class AccountDaoTestBase extends AccountTestSuiteWithEmbeddedDB {
protected final TagEventBuilder tagEventBuilder = new TagEventBuilder();
protected AccountDao accountDao;
@@ -53,17 +45,9 @@ public abstract class AccountDaoTestBase {
protected Bus bus;
protected CallContext context;
- @BeforeClass(alwaysRun = true)
+ @BeforeClass(groups = "slow")
protected void setup() throws IOException {
- // Health check test to make sure MySQL is setup properly
try {
- final String accountDdl = IOUtils.toString(AccountSqlDao.class.getResourceAsStream("/com/ning/billing/account/ddl.sql"));
- final String utilDdl = IOUtils.toString(AccountSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(accountDdl);
- helper.initDb(utilDdl);
-
dbi = helper.getDBI();
bus = new InMemoryBus();
@@ -71,9 +55,11 @@ public abstract class AccountDaoTestBase {
((DefaultBusService) busService).startBus();
accountDao = new AuditedAccountDao(dbi, bus);
+ // Health check test to make sure MySQL is setup properly
accountDao.test();
accountEmailDao = new AuditedAccountEmailDao(dbi);
+ // Health check test to make sure MySQL is setup properly
accountEmailDao.test();
final Clock clock = new ClockMock();
@@ -82,27 +68,4 @@ public abstract class AccountDaoTestBase {
fail(t.toString());
}
}
-
- @AfterClass(alwaysRun = true)
- public void stopMysql() {
- helper.stopMysql();
- }
-
- @BeforeMethod(alwaysRun = true)
- public void cleanupData() {
- dbi.inTransaction(new TransactionCallback<Void>() {
- @Override
- public Void inTransaction(final Handle h, final TransactionStatus status) throws Exception {
- h.execute("truncate table accounts");
- h.execute("truncate table notifications");
- h.execute("truncate table bus_events");
- h.execute("truncate table claimed_bus_events");
- h.execute("truncate table claimed_notifications");
- h.execute("truncate table tag_definitions");
- h.execute("truncate table tags");
- h.execute("truncate table custom_fields");
- return null;
- }
- });
- }
}
diff --git a/account/src/test/java/com/ning/billing/account/dao/TestAccountDao.java b/account/src/test/java/com/ning/billing/account/dao/TestAccountDao.java
index b3105c3..5d457e2 100644
--- a/account/src/test/java/com/ning/billing/account/dao/TestAccountDao.java
+++ b/account/src/test/java/com/ning/billing/account/dao/TestAccountDao.java
@@ -126,7 +126,6 @@ public class TestAccountDao extends AccountDaoTestBase {
assertEquals(account.getExternalKey(), key);
assertEquals(account.getName(), name);
assertEquals(account.getFirstNameLength(), firstNameLength);
-
}
@Test
@@ -359,9 +358,9 @@ public class TestAccountDao extends AccountDaoTestBase {
final String buggyKey = "extKey1338";
final DefaultAccount updatedAccountData = new DefaultAccount(accountId, buggyKey, "myemail1337@glam.com",
- "John Smith", 4, Currency.USD, 15, null,
- null, null, null, null, null, null, null, null, null, null,
- false, false);
+ "John Smith", 4, Currency.USD, 15, null,
+ null, null, null, null, null, null, null, null, null, null,
+ false, false);
accountDao.update(updatedAccountData, context);
Assert.assertNull(accountDao.getAccountByKey(buggyKey));
}
diff --git a/account/src/test/java/com/ning/billing/account/glue/AccountModuleWithMocks.java b/account/src/test/java/com/ning/billing/account/glue/AccountModuleWithMocks.java
index f806309..b224a46 100644
--- a/account/src/test/java/com/ning/billing/account/glue/AccountModuleWithMocks.java
+++ b/account/src/test/java/com/ning/billing/account/glue/AccountModuleWithMocks.java
@@ -16,10 +16,11 @@
package com.ning.billing.account.glue;
+import org.mockito.Mockito;
+
import com.ning.billing.account.dao.AccountDao;
import com.ning.billing.account.dao.AccountEmailDao;
import com.ning.billing.account.dao.MockAccountDao;
-import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.util.glue.CallContextModule;
@@ -27,7 +28,7 @@ public class AccountModuleWithMocks extends AccountModule {
@Override
protected void installAccountDao() {
bind(MockAccountDao.class).asEagerSingleton();
- final AccountEmailDao accountEmailDao = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountEmailDao.class);
+ final AccountEmailDao accountEmailDao = Mockito.mock(AccountEmailDao.class);
bind(AccountEmailDao.class).toInstance(accountEmailDao);
bind(AccountDao.class).to(MockAccountDao.class);
}
analytics/pom.xml 3(+1 -2)
diff --git a/analytics/pom.xml b/analytics/pom.xml
index ecd27bf..e493b1f 100644
--- a/analytics/pom.xml
+++ b/analytics/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-analytics</artifactId>
@@ -117,7 +117,6 @@
<dependency>
<groupId>com.ning.billing</groupId>
<artifactId>killbill-util</artifactId>
- <scope>test</scope>
</dependency>
<dependency>
<groupId>com.ning.billing</groupId>
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 eb41bce..a5ad78f 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/AnalyticsListener.java
@@ -22,10 +22,12 @@ 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.timeline.RepairEntitlementEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
-import com.ning.billing.invoice.api.EmptyInvoiceEvent;
+import com.ning.billing.entitlement.api.user.RequestedSubscriptionEvent;
+import com.ning.billing.invoice.api.NullInvoiceEvent;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
+import com.ning.billing.overdue.OverdueChangeEvent;
import com.ning.billing.payment.api.PaymentErrorEvent;
import com.ning.billing.payment.api.PaymentInfoEvent;
import com.ning.billing.util.tag.api.ControlTagCreationEvent;
@@ -41,46 +43,41 @@ public class AnalyticsListener {
private final BusinessSubscriptionTransitionRecorder bstRecorder;
private final BusinessAccountRecorder bacRecorder;
private final BusinessInvoiceRecorder invoiceRecorder;
+ private final BusinessOverdueStatusRecorder bosRecorder;
+ private final BusinessInvoicePaymentRecorder bipRecorder;
private final BusinessTagRecorder tagRecorder;
@Inject
public AnalyticsListener(final BusinessSubscriptionTransitionRecorder bstRecorder,
final BusinessAccountRecorder bacRecorder,
final BusinessInvoiceRecorder invoiceRecorder,
+ final BusinessOverdueStatusRecorder bosRecorder,
+ final BusinessInvoicePaymentRecorder bipRecorder,
final BusinessTagRecorder tagRecorder) {
this.bstRecorder = bstRecorder;
this.bacRecorder = bacRecorder;
this.invoiceRecorder = invoiceRecorder;
+ this.bosRecorder = bosRecorder;
+ this.bipRecorder = bipRecorder;
this.tagRecorder = tagRecorder;
}
@Subscribe
- public void handleSubscriptionTransitionChange(final SubscriptionEvent event) throws AccountApiException, EntitlementUserApiException {
- switch (event.getTransitionType()) {
- // A subscription enters either through migration or as newly created subscription
- case MIGRATE_ENTITLEMENT:
- case CREATE:
- bstRecorder.subscriptionCreated(event);
- break;
- case RE_CREATE:
- bstRecorder.subscriptionRecreated(event);
- break;
- case MIGRATE_BILLING:
- break;
- case CANCEL:
- bstRecorder.subscriptionCancelled(event);
- break;
- case CHANGE:
- bstRecorder.subscriptionChanged(event);
- break;
- case UNCANCEL:
- break;
- case PHASE:
- bstRecorder.subscriptionPhaseChanged(event);
- break;
- default:
- throw new RuntimeException("Unexpected event type " + event.getTransitionType());
- }
+ public void handleEffectiveSubscriptionTransitionChange(final EffectiveSubscriptionEvent eventEffective) throws AccountApiException, EntitlementUserApiException {
+ // The event is used as a trigger to rebuild all transitions for this bundle
+ bstRecorder.rebuildTransitionsForBundle(eventEffective.getBundleId());
+ }
+
+ @Subscribe
+ public void handleRequestedSubscriptionTransitionChange(final RequestedSubscriptionEvent eventRequested) throws AccountApiException, EntitlementUserApiException {
+ // The event is used as a trigger to rebuild all transitions for this bundle
+ bstRecorder.rebuildTransitionsForBundle(eventRequested.getBundleId());
+ }
+
+ @Subscribe
+ public void handleRepairEntitlement(final RepairEntitlementEvent event) {
+ // In case of repair, just rebuild all transitions
+ bstRecorder.rebuildTransitionsForBundle(event.getBundleId());
}
@Subscribe
@@ -99,22 +96,34 @@ public class AnalyticsListener {
@Subscribe
public void handleInvoiceCreation(final InvoiceCreationEvent event) {
- invoiceRecorder.invoiceCreated(event.getInvoiceId());
+ // The event is used as a trigger to rebuild all invoices and invoice items for this account
+ invoiceRecorder.rebuildInvoicesForAccount(event.getAccountId());
}
@Subscribe
- public void handleNullInvoice(final EmptyInvoiceEvent event) {
+ public void handleNullInvoice(final NullInvoiceEvent event) {
// Ignored for now
}
@Subscribe
public void handlePaymentInfo(final PaymentInfoEvent paymentInfo) {
- bacRecorder.accountUpdated(paymentInfo);
+ bipRecorder.invoicePaymentPosted(paymentInfo.getAccountId(),
+ paymentInfo.getPaymentId(),
+ paymentInfo.getExtPaymentRefId(),
+ paymentInfo.getStatus().toString());
}
@Subscribe
public void handlePaymentError(final PaymentErrorEvent paymentError) {
- // TODO - we can't tie the error back to an account yet
+ bipRecorder.invoicePaymentPosted(paymentError.getAccountId(),
+ paymentError.getPaymentId(),
+ null,
+ paymentError.getMessage());
+ }
+
+ @Subscribe
+ public void handleOverdueChange(final OverdueChangeEvent changeEvent) {
+ bosRecorder.overdueStatusChanged(changeEvent.getOverdueObjectType(), changeEvent.getOverdueObjectId());
}
@Subscribe
@@ -156,9 +165,4 @@ public class AnalyticsListener {
public void handleUserTagDefinitionDeletion(final UserTagDefinitionDeletionEvent event) {
// Ignored for now
}
-
- @Subscribe
- public void handleRepairEntitlement(final RepairEntitlementEvent event) {
- // Ignored for now
- }
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/api/user/DefaultAnalyticsUserApi.java b/analytics/src/main/java/com/ning/billing/analytics/api/user/DefaultAnalyticsUserApi.java
index 424e1c2..4d90894 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/api/user/DefaultAnalyticsUserApi.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/api/user/DefaultAnalyticsUserApi.java
@@ -25,6 +25,8 @@ import com.ning.billing.analytics.model.BusinessAccount;
import com.ning.billing.analytics.model.BusinessAccountTag;
import com.ning.billing.analytics.model.BusinessInvoice;
import com.ning.billing.analytics.model.BusinessInvoiceItem;
+import com.ning.billing.analytics.model.BusinessInvoicePayment;
+import com.ning.billing.analytics.model.BusinessOverdueStatus;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
// Note: not exposed in api yet
@@ -52,7 +54,15 @@ public class DefaultAnalyticsUserApi {
return analyticsDao.getTagsForAccount(accountKey);
}
+ public List<BusinessOverdueStatus> getOverdueStatusesForBundle(final String externalKey) {
+ return analyticsDao.getOverdueStatusesForBundleByKey(externalKey);
+ }
+
public List<BusinessInvoiceItem> getInvoiceItemsForInvoice(final UUID invoiceId) {
return analyticsDao.getInvoiceItemsForInvoice(invoiceId.toString());
}
+
+ public List<BusinessInvoicePayment> getInvoicePaymentsForAccount(final String accountKey) {
+ return analyticsDao.getInvoicePaymentsForAccountByKey(accountKey);
+ }
}
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 998fd7e..7ecd1b3 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessAccountRecorder.java
@@ -36,7 +36,6 @@ import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.payment.api.Payment;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentApiException;
-import com.ning.billing.payment.api.PaymentInfoEvent;
public class BusinessAccountRecorder {
private static final Logger log = LoggerFactory.getLogger(BusinessAccountRecorder.class);
@@ -59,7 +58,7 @@ public class BusinessAccountRecorder {
final Account account;
try {
account = accountApi.getAccountByKey(data.getExternalKey());
- final BusinessAccount bac = new BusinessAccount();
+ final BusinessAccount bac = new BusinessAccount(account.getId());
updateBusinessAccountFromAccount(account, bac);
log.info("ACCOUNT CREATION " + bac);
@@ -70,41 +69,33 @@ public class BusinessAccountRecorder {
}
/**
- * Notification handler for Payment creations
- *
- * @param paymentInfo payment object (from the payment plugin)
- */
- public void accountUpdated(final PaymentInfoEvent paymentInfo) {
- try {
- final Account account = accountApi.getAccountById(paymentInfo.getAccountId());
- accountUpdated(account.getId());
- } catch (AccountApiException e) {
- log.warn("Error encountered creating BusinessAccount", e);
- }
- }
-
- /**
* Notification handler for Invoice creations
*
* @param accountId account id associated with the created invoice
*/
public void accountUpdated(final UUID accountId) {
+ final Account account;
try {
- final Account account = accountApi.getAccountById(accountId);
-
- BusinessAccount bac = sqlDao.getAccount(account.getExternalKey());
- if (bac == null) {
- bac = new BusinessAccount();
- updateBusinessAccountFromAccount(account, bac);
- log.info("ACCOUNT CREATION " + bac);
- sqlDao.createAccount(bac);
- } else {
- updateBusinessAccountFromAccount(account, bac);
- log.info("ACCOUNT UPDATE " + bac);
- sqlDao.saveAccount(bac);
- }
+ account = accountApi.getAccountById(accountId);
} catch (AccountApiException e) {
log.warn("Error encountered creating BusinessAccount", e);
+ return;
+ }
+
+ updateAccountInTransaction(account, sqlDao);
+ }
+
+ public void updateAccountInTransaction(final Account account, final BusinessAccountSqlDao transactional) {
+ BusinessAccount bac = transactional.getAccount(account.getId().toString());
+ if (bac == null) {
+ bac = new BusinessAccount(account.getId());
+ updateBusinessAccountFromAccount(account, bac);
+ log.info("ACCOUNT CREATION " + bac);
+ transactional.createAccount(bac);
+ } else {
+ updateBusinessAccountFromAccount(account, bac);
+ log.info("ACCOUNT UPDATE " + bac);
+ transactional.saveAccount(bac);
}
}
@@ -142,7 +133,7 @@ public class BusinessAccountRecorder {
if (lastPaymentDate == null || cur.getEffectiveDate().isAfter(lastPaymentDate)) {
lastPaymentDate = cur.getEffectiveDate();
lastPaymentStatus = cur.getPaymentStatus().toString();
- // STEPH talk to Pierre
+ // TODO STEPH talk to Pierre
paymentMethod = null;
creditCardType = null;
billingAddressCountry = null;
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoicePaymentRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoicePaymentRecorder.java
new file mode 100644
index 0000000..1d7c3d0
--- /dev/null
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoicePaymentRecorder.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2010-2012 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.analytics;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import java.util.UUID;
+
+import org.skife.jdbi.v2.Transaction;
+import org.skife.jdbi.v2.TransactionStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+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.analytics.dao.BusinessAccountSqlDao;
+import com.ning.billing.analytics.dao.BusinessInvoicePaymentSqlDao;
+import com.ning.billing.analytics.dao.BusinessInvoiceSqlDao;
+import com.ning.billing.analytics.model.BusinessInvoicePayment;
+import com.ning.billing.invoice.api.InvoicePayment;
+import com.ning.billing.invoice.api.InvoicePaymentApi;
+import com.ning.billing.payment.api.Payment;
+import com.ning.billing.payment.api.PaymentApi;
+import com.ning.billing.payment.api.PaymentApiException;
+import com.ning.billing.payment.api.PaymentMethod;
+import com.ning.billing.payment.api.PaymentMethodPlugin;
+import com.ning.billing.util.clock.Clock;
+
+public class BusinessInvoicePaymentRecorder {
+ private static final Logger log = LoggerFactory.getLogger(BusinessInvoicePaymentRecorder.class);
+
+ private final BusinessInvoicePaymentSqlDao invoicePaymentSqlDao;
+ private final AccountUserApi accountApi;
+ private final InvoicePaymentApi invoicePaymentApi;
+ private final PaymentApi paymentApi;
+ private final Clock clock;
+ private final BusinessInvoiceRecorder invoiceRecorder;
+ private final BusinessAccountRecorder accountRecorder;
+
+ @Inject
+ public BusinessInvoicePaymentRecorder(final BusinessInvoicePaymentSqlDao invoicePaymentSqlDao, final AccountUserApi accountApi,
+ final InvoicePaymentApi invoicePaymentApi, final PaymentApi paymentApi, final Clock clock,
+ final BusinessInvoiceRecorder invoiceRecorder, final BusinessAccountRecorder accountRecorder) {
+ this.invoicePaymentSqlDao = invoicePaymentSqlDao;
+ this.accountApi = accountApi;
+ this.invoicePaymentApi = invoicePaymentApi;
+ this.paymentApi = paymentApi;
+ this.clock = clock;
+ this.invoiceRecorder = invoiceRecorder;
+ this.accountRecorder = accountRecorder;
+ }
+
+ public void invoicePaymentPosted(final UUID accountId, final UUID paymentId, @Nullable final String extPaymentRefId, final String message) {
+ final Account account;
+ try {
+ account = accountApi.getAccountById(accountId);
+ } catch (AccountApiException e) {
+ log.warn("Ignoring payment {}: account {} does not exist", paymentId, accountId);
+ return;
+ }
+
+ final Payment payment;
+ try {
+ payment = paymentApi.getPayment(paymentId);
+ } catch (PaymentApiException e) {
+ log.warn("Ignoring payment {}: payment does not exist", paymentId);
+ return;
+ }
+
+ final InvoicePayment invoicePayment = invoicePaymentApi.getInvoicePayment(paymentId);
+
+ final PaymentMethod paymentMethod;
+ try {
+ paymentMethod = paymentApi.getPaymentMethod(account, payment.getPaymentMethodId(), true);
+ } catch (PaymentApiException e) {
+ log.warn("Ignoring payment {}: payment method {} does not exist", paymentId, payment.getPaymentMethodId());
+ return;
+ }
+
+ createPayment(account, invoicePayment, payment, paymentMethod, extPaymentRefId, message);
+ }
+
+ private void createPayment(final Account account, @Nullable final InvoicePayment invoicePayment, final Payment payment,
+ final PaymentMethod paymentMethod, final String extPaymentRefId, final String message) {
+ final PaymentMethodPlugin pluginDetail = paymentMethod.getPluginDetail();
+ // TODO - make it generic
+ final String cardCountry = pluginDetail != null ? pluginDetail.getValueString("country") : null;
+ final String cardType = pluginDetail != null ? pluginDetail.getValueString("cardType") : null;
+ // TODO support CreditCard, DebitCard, WireTransfer, BankTransfer, Check, ACH, Cash, Paypal
+ final String paymentMethodString = cardType != null ? "CreditCard" : "Other";
+
+ invoicePaymentSqlDao.inTransaction(new Transaction<Void, BusinessInvoicePaymentSqlDao>() {
+ @Override
+ public Void inTransaction(final BusinessInvoicePaymentSqlDao transactional, final TransactionStatus status) throws Exception {
+ // Delete the existing payment if it exists - this is to make the call idempotent
+ transactional.deleteInvoicePayment(payment.getId().toString());
+
+ // invoicePayment may be null on payment failures
+ final String invoicePaymentType;
+ final UUID linkedInvoicePaymentId;
+ if (invoicePayment != null) {
+ invoicePaymentType = invoicePayment.getType().toString();
+ linkedInvoicePaymentId = invoicePayment.getLinkedInvoicePaymentId();
+ } else {
+ invoicePaymentType = null;
+ linkedInvoicePaymentId = null;
+ }
+
+ // Create the bip record
+ final BusinessInvoicePayment businessInvoicePayment = new BusinessInvoicePayment(
+ account.getExternalKey(),
+ payment.getAmount(),
+ extPaymentRefId,
+ cardCountry,
+ cardType,
+ clock.getUTCNow(),
+ payment.getCurrency(),
+ payment.getEffectiveDate(),
+ payment.getInvoiceId(),
+ message,
+ payment.getId(),
+ paymentMethodString,
+ "Electronic",
+ paymentMethod.getPluginName(),
+ payment.getPaymentStatus().toString(),
+ payment.getAmount(),
+ clock.getUTCNow(),
+ invoicePaymentType,
+ linkedInvoicePaymentId);
+ transactional.createInvoicePayment(businessInvoicePayment);
+
+ // Update bin to get the latest invoice(s) balance(s)
+ final BusinessInvoiceSqlDao invoiceSqlDao = transactional.become(BusinessInvoiceSqlDao.class);
+ invoiceRecorder.rebuildInvoicesForAccountInTransaction(account.getId(), invoiceSqlDao);
+
+ // Update bac to get the latest account balance, total invoice balance, etc.
+ final BusinessAccountSqlDao accountSqlDao = transactional.become(BusinessAccountSqlDao.class);
+ accountRecorder.updateAccountInTransaction(account, accountSqlDao);
+
+ log.info("Added payment {}", businessInvoicePayment);
+ return null;
+ }
+ });
+ }
+}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoiceRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoiceRecorder.java
index 21693f3..30baa4a 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoiceRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessInvoiceRecorder.java
@@ -21,13 +21,18 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import org.skife.jdbi.v2.Transaction;
+import org.skife.jdbi.v2.TransactionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.analytics.dao.AnalyticsDao;
+import com.ning.billing.analytics.dao.BusinessAccountSqlDao;
+import com.ning.billing.analytics.dao.BusinessInvoiceItemSqlDao;
+import com.ning.billing.analytics.dao.BusinessInvoiceSqlDao;
+import com.ning.billing.analytics.model.BusinessAccount;
import com.ning.billing.analytics.model.BusinessInvoice;
import com.ning.billing.analytics.model.BusinessInvoiceItem;
import com.ning.billing.catalog.api.Plan;
@@ -39,46 +44,77 @@ import com.ning.billing.entitlement.api.user.SubscriptionBundle;
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.util.clock.Clock;
public class BusinessInvoiceRecorder {
private static final Logger log = LoggerFactory.getLogger(BusinessInvoiceRecorder.class);
- private final AnalyticsDao analyticsDao;
private final AccountUserApi accountApi;
private final EntitlementUserApi entitlementApi;
private final InvoiceUserApi invoiceApi;
+ private final BusinessInvoiceSqlDao sqlDao;
+ private final Clock clock;
@Inject
- public BusinessInvoiceRecorder(final AnalyticsDao analyticsDao,
- final AccountUserApi accountApi,
+ public BusinessInvoiceRecorder(final AccountUserApi accountApi,
final EntitlementUserApi entitlementApi,
- final InvoiceUserApi invoiceApi) {
- this.analyticsDao = analyticsDao;
+ final InvoiceUserApi invoiceApi,
+ final BusinessInvoiceSqlDao sqlDao,
+ final Clock clock) {
this.accountApi = accountApi;
this.entitlementApi = entitlementApi;
this.invoiceApi = invoiceApi;
+ this.sqlDao = sqlDao;
+ this.clock = clock;
}
- public void invoiceCreated(final UUID invoiceId) {
- // Lookup the invoice object
- final Invoice invoice = invoiceApi.getInvoice(invoiceId);
- if (invoice == null) {
- log.warn("Ignoring invoice creation for invoice id {} (invoice does not exist)", invoiceId.toString());
- return;
- }
+ public void rebuildInvoicesForAccount(final UUID accountId) {
+ sqlDao.inTransaction(new Transaction<Void, BusinessInvoiceSqlDao>() {
+ @Override
+ public Void inTransaction(final BusinessInvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
+ rebuildInvoicesForAccountInTransaction(accountId, transactional);
+ return null;
+ }
+ });
+ }
+ public void rebuildInvoicesForAccountInTransaction(final UUID accountId, final BusinessInvoiceSqlDao transactional) {
// Lookup the associated account
final String accountKey;
try {
- final Account account = accountApi.getAccountById(invoice.getAccountId());
+ final Account account = accountApi.getAccountById(accountId);
accountKey = account.getExternalKey();
} catch (AccountApiException e) {
- log.warn("Ignoring invoice creation for invoice id {} and account id {} (account does not exist)",
- invoice.getId().toString(),
- invoice.getAccountId().toString());
+ log.warn("Ignoring invoice update for account id {} (account does not exist)", accountId);
return;
}
+ log.info("Started rebuilding transitions for account id {}", accountId);
+ deleteInvoicesAndInvoiceItemsForAccountInTransaction(transactional, accountId);
+
+ for (final Invoice invoice : invoiceApi.getInvoicesByAccount(accountId)) {
+ createInvoiceInTransaction(transactional, accountKey, invoice);
+ }
+
+ log.info("Finished rebuilding transitions for account id {}", accountId);
+ }
+
+ private void deleteInvoicesAndInvoiceItemsForAccountInTransaction(final BusinessInvoiceSqlDao transactional, final UUID accountId) {
+ // We don't use on cascade delete here as we don't want the database layer to be generic - hence we have
+ // to delete the invoice items manually.
+ final List<BusinessInvoice> invoicesToDelete = transactional.getInvoicesForAccount(accountId.toString());
+ final BusinessInvoiceItemSqlDao invoiceItemSqlDao = transactional.become(BusinessInvoiceItemSqlDao.class);
+ for (final BusinessInvoice businessInvoice : invoicesToDelete) {
+ final List<BusinessInvoiceItem> invoiceItemsForInvoice = invoiceItemSqlDao.getInvoiceItemsForInvoice(businessInvoice.getInvoiceId().toString());
+ for (final BusinessInvoiceItem invoiceItemToDelete : invoiceItemsForInvoice) {
+ invoiceItemSqlDao.deleteInvoiceItem(invoiceItemToDelete.getItemId().toString());
+ }
+ }
+
+ transactional.deleteInvoicesForAccount(accountId.toString());
+ }
+
+ private void createInvoiceInTransaction(final BusinessInvoiceSqlDao transactional, final String accountKey, final Invoice invoice) {
// Create the invoice
final BusinessInvoice businessInvoice = new BusinessInvoice(accountKey, invoice);
@@ -91,8 +127,33 @@ public class BusinessInvoiceRecorder {
}
}
- // Update the Analytics tables
- analyticsDao.createInvoice(accountKey, businessInvoice, businessInvoiceItems);
+ createInvoiceInTransaction(transactional, invoice.getAccountId(), businessInvoice, businessInvoiceItems);
+ }
+
+ private void createInvoiceInTransaction(final BusinessInvoiceSqlDao transactional, final UUID accountId,
+ final BusinessInvoice invoice, final Iterable<BusinessInvoiceItem> invoiceItems) {
+ // Create the invoice
+ log.info("Adding invoice {}", invoice);
+ transactional.createInvoice(invoice);
+
+ // Add associated invoice items
+ final BusinessInvoiceItemSqlDao invoiceItemSqlDao = transactional.become(BusinessInvoiceItemSqlDao.class);
+ for (final BusinessInvoiceItem invoiceItem : invoiceItems) {
+ log.info("Adding invoice item {}", invoiceItem);
+ invoiceItemSqlDao.createInvoiceItem(invoiceItem);
+ }
+
+ // Update BAC
+ final BusinessAccountSqlDao accountSqlDao = transactional.become(BusinessAccountSqlDao.class);
+ final BusinessAccount account = accountSqlDao.getAccount(accountId.toString());
+ if (account == null) {
+ throw new IllegalStateException("Account does not exist for id " + accountId);
+ }
+ account.setBalance(account.getBalance().add(invoice.getBalance()));
+ account.setLastInvoiceDate(invoice.getInvoiceDate());
+ account.setTotalInvoiceBalance(account.getTotalInvoiceBalance().add(invoice.getBalance()));
+ account.setUpdatedDt(clock.getUTCNow());
+ accountSqlDao.saveAccount(account);
}
private BusinessInvoiceItem createBusinessInvoiceItem(final InvoiceItem invoiceItem) {
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessOverdueStatusRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessOverdueStatusRecorder.java
new file mode 100644
index 0000000..8ec98d4
--- /dev/null
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessOverdueStatusRecorder.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2010-2012 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.analytics;
+
+import javax.inject.Inject;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+import org.skife.jdbi.v2.Transaction;
+import org.skife.jdbi.v2.TransactionStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+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.analytics.dao.BusinessOverdueStatusSqlDao;
+import com.ning.billing.analytics.model.BusinessOverdueStatus;
+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.junction.api.Blockable;
+import com.ning.billing.junction.api.BlockingApi;
+import com.ning.billing.junction.api.BlockingState;
+
+public class BusinessOverdueStatusRecorder {
+ private static final Logger log = LoggerFactory.getLogger(BusinessOverdueStatusRecorder.class);
+
+ private final BusinessOverdueStatusSqlDao overdueStatusSqlDao;
+ private final AccountUserApi accountApi;
+ private final EntitlementUserApi entitlementApi;
+ private final BlockingApi blockingApi;
+
+ @Inject
+ public BusinessOverdueStatusRecorder(final BusinessOverdueStatusSqlDao overdueStatusSqlDao, final AccountUserApi accountApi,
+ final EntitlementUserApi entitlementApi, final BlockingApi blockingApi) {
+ this.overdueStatusSqlDao = overdueStatusSqlDao;
+ this.accountApi = accountApi;
+ this.entitlementApi = entitlementApi;
+ this.blockingApi = blockingApi;
+ }
+
+ public void overdueStatusChanged(final Blockable.Type objectType, final UUID objectId) {
+ if (Blockable.Type.SUBSCRIPTION_BUNDLE.equals(objectType)) {
+ overdueStatusChangedForBundle(objectId);
+ } else {
+ log.info("Ignoring overdue status change for object id {} (type {})", objectId.toString(), objectType.toString());
+ }
+ }
+
+ private void overdueStatusChangedForBundle(final UUID bundleId) {
+ final SubscriptionBundle bundle;
+ try {
+ bundle = entitlementApi.getBundleFromId(bundleId);
+ } catch (EntitlementUserApiException e) {
+ log.warn("Ignoring update for bundle {}: bundle does not exist", bundleId);
+ return;
+ }
+
+ final Account account;
+ try {
+ account = accountApi.getAccountById(bundle.getAccountId());
+ } catch (AccountApiException e) {
+ log.warn("Ignoring update for bundle {}: account {} does not exist", bundleId, bundle.getAccountId());
+ return;
+ }
+
+ final String accountKey = account.getExternalKey();
+ final String externalKey = bundle.getKey();
+
+ overdueStatusSqlDao.inTransaction(new Transaction<Void, BusinessOverdueStatusSqlDao>() {
+ @Override
+ public Void inTransaction(final BusinessOverdueStatusSqlDao transactional, final TransactionStatus status) throws Exception {
+ log.info("Started rebuilding overdue statuses for bundle id {}", bundleId);
+ transactional.deleteOverdueStatusesForBundle(bundleId.toString());
+
+ final SortedSet<BlockingState> blockingHistory = blockingApi.getBlockingHistory(bundleId);
+ if (blockingHistory != null && blockingHistory.size() > 0) {
+ final List<BlockingState> overdueStates = ImmutableList.<BlockingState>copyOf(blockingHistory);
+ final List<BlockingState> overdueStatesReversed = Lists.reverse(overdueStates);
+
+ DateTime previousStartDate = null;
+ for (final BlockingState state : overdueStatesReversed) {
+ final BusinessOverdueStatus overdueStatus = new BusinessOverdueStatus(accountKey, bundleId, previousStartDate,
+ externalKey, state.getTimestamp(), state.getStateName());
+ log.info("Adding overdue state {}", overdueStatus);
+ overdueStatusSqlDao.createOverdueStatus(overdueStatus);
+
+ previousStartDate = state.getTimestamp();
+ }
+ }
+
+ log.info("Finished rebuilding overdue statuses for bundle id {}", bundleId);
+ return null;
+ }
+ });
+ }
+}
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 04e3547..83f701d 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscriptionTransitionRecorder.java
@@ -16,9 +16,12 @@
package com.ning.billing.analytics;
+import java.util.ArrayList;
import java.util.List;
+import java.util.UUID;
-import org.joda.time.DateTime;
+import org.skife.jdbi.v2.Transaction;
+import org.skife.jdbi.v2.TransactionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,10 +35,14 @@ import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.entitlement.api.SubscriptionTransitionType;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.SubscriptionEvent;
+import com.ning.billing.util.clock.Clock;
public class BusinessSubscriptionTransitionRecorder {
private static final Logger log = LoggerFactory.getLogger(BusinessSubscriptionTransitionRecorder.class);
@@ -44,109 +51,197 @@ public class BusinessSubscriptionTransitionRecorder {
private final EntitlementUserApi entitlementApi;
private final AccountUserApi accountApi;
private final CatalogService catalogService;
+ private final Clock clock;
@Inject
- public BusinessSubscriptionTransitionRecorder(final BusinessSubscriptionTransitionSqlDao sqlDao, final CatalogService catalogService, final EntitlementUserApi entitlementApi, final AccountUserApi accountApi) {
+ public BusinessSubscriptionTransitionRecorder(final BusinessSubscriptionTransitionSqlDao sqlDao,
+ final CatalogService catalogService,
+ final EntitlementUserApi entitlementApi,
+ final AccountUserApi accountApi,
+ final Clock clock) {
this.sqlDao = sqlDao;
this.catalogService = catalogService;
this.entitlementApi = entitlementApi;
this.accountApi = accountApi;
+ this.clock = clock;
}
+ public void rebuildTransitionsForBundle(final UUID bundleId) {
+ final SubscriptionBundle bundle;
+ try {
+ bundle = entitlementApi.getBundleFromId(bundleId);
+ } catch (EntitlementUserApiException e) {
+ log.warn("Ignoring update for bundle {}: bundle does not exist", bundleId);
+ return;
+ }
+
+ final Account account;
+ try {
+ account = accountApi.getAccountById(bundle.getAccountId());
+ } catch (AccountApiException e) {
+ log.warn("Ignoring update for bundle {}: account {} does not exist", bundleId, bundle.getAccountId());
+ return;
+ }
- public void subscriptionCreated(final SubscriptionEvent created) throws AccountApiException, EntitlementUserApiException {
- final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionCreated(created.getNextPlan(), catalogService.getFullCatalog(), created.getEffectiveTransitionTime(), created.getSubscriptionStartDate());
- recordTransition(event, created);
+ final List<Subscription> subscriptions = entitlementApi.getSubscriptionsForBundle(bundleId);
+
+ final Currency currency = account.getCurrency();
+
+ sqlDao.inTransaction(new Transaction<Void, BusinessSubscriptionTransitionSqlDao>() {
+ @Override
+ public Void inTransaction(final BusinessSubscriptionTransitionSqlDao transactional, final TransactionStatus status) throws Exception {
+ log.info("Started rebuilding transitions for bundle id {}", bundleId);
+ transactional.deleteTransitionsForBundle(bundleId.toString());
+
+ final ArrayList<BusinessSubscriptionTransition> transitions = new ArrayList<BusinessSubscriptionTransition>();
+ for (final Subscription subscription : subscriptions) {
+ for (final EffectiveSubscriptionEvent event : subscription.getAllTransitions()) {
+ final BusinessSubscriptionEvent businessEvent = getBusinessSubscriptionFromEvent(event);
+ if (businessEvent == null) {
+ continue;
+ }
+
+ final BusinessSubscription prevSubscription = createPreviousBusinessSubscription(event, businessEvent, transitions, currency);
+ final BusinessSubscription nextSubscription = createNextBusinessSubscription(event, businessEvent, currency);
+ final BusinessSubscriptionTransition transition = new BusinessSubscriptionTransition(
+ event.getTotalOrdering(),
+ bundleId,
+ bundle.getKey(),
+ bundle.getAccountId(),
+ account.getExternalKey(),
+ subscription.getId(),
+ event.getRequestedTransitionTime(),
+ businessEvent,
+ prevSubscription,
+ nextSubscription
+ );
+
+ transactional.createTransition(transition);
+ transitions.add(transition);
+ log.info("Adding transition {}", transition);
+
+ // We need to manually add the system cancel event
+ if (SubscriptionTransitionType.CANCEL.equals(event.getTransitionType()) &&
+ clock.getUTCNow().isAfter(event.getEffectiveTransitionTime())) {
+ final BusinessSubscriptionTransition systemCancelTransition = new BusinessSubscriptionTransition(
+ event.getTotalOrdering(),
+ bundleId,
+ bundle.getKey(),
+ bundle.getAccountId(),
+ account.getExternalKey(),
+ subscription.getId(),
+ event.getRequestedTransitionTime(),
+ new BusinessSubscriptionEvent(BusinessSubscriptionEvent.EventType.SYSTEM_CANCEL, businessEvent.getCategory()),
+ prevSubscription,
+ nextSubscription
+ );
+ transactional.createTransition(systemCancelTransition);
+ transitions.add(systemCancelTransition);
+ log.info("Adding transition {}", systemCancelTransition);
+ }
+ }
+ }
+
+ log.info("Finished rebuilding transitions for bundle id {}", bundleId);
+ return null;
+ }
+ });
}
+ private BusinessSubscriptionEvent getBusinessSubscriptionFromEvent(final SubscriptionEvent event) throws AccountApiException, EntitlementUserApiException {
+ switch (event.getTransitionType()) {
+ // A subscription enters either through migration or as newly created subscription
+ case MIGRATE_ENTITLEMENT:
+ case CREATE:
+ return subscriptionCreated(event);
+ case RE_CREATE:
+ return subscriptionRecreated(event);
+ case CANCEL:
+ return subscriptionCancelled(event);
+ case CHANGE:
+ return subscriptionChanged(event);
+ case PHASE:
+ return subscriptionPhaseChanged(event);
+ // TODO - should we really ignore these?
+ case MIGRATE_BILLING:
+ case UNCANCEL:
+ return null;
+ default:
+ log.warn("Unexpected event type " + event.getTransitionType());
+ return null;
+ }
+ }
- public void subscriptionRecreated(final SubscriptionEvent recreated) throws AccountApiException, EntitlementUserApiException {
- final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionRecreated(recreated.getNextPlan(), catalogService.getFullCatalog(), recreated.getEffectiveTransitionTime(), recreated.getSubscriptionStartDate());
- recordTransition(event, recreated);
+ private BusinessSubscriptionEvent subscriptionCreated(final SubscriptionEvent created) throws AccountApiException, EntitlementUserApiException {
+ return BusinessSubscriptionEvent.subscriptionCreated(created.getNextPlan(), catalogService.getFullCatalog(), created.getEffectiveTransitionTime(), created.getSubscriptionStartDate());
}
+ private BusinessSubscriptionEvent subscriptionRecreated(final SubscriptionEvent recreated) throws AccountApiException, EntitlementUserApiException {
+ return BusinessSubscriptionEvent.subscriptionRecreated(recreated.getNextPlan(), catalogService.getFullCatalog(), recreated.getEffectiveTransitionTime(), recreated.getSubscriptionStartDate());
+ }
- public void subscriptionCancelled(final SubscriptionEvent cancelled) throws AccountApiException, EntitlementUserApiException {
+ private BusinessSubscriptionEvent subscriptionCancelled(final SubscriptionEvent 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(), catalogService.getFullCatalog(), cancelled.getEffectiveTransitionTime(), cancelled.getSubscriptionStartDate());
- recordTransition(event, cancelled);
+ return BusinessSubscriptionEvent.subscriptionCancelled(cancelled.getPreviousPlan(), catalogService.getFullCatalog(), cancelled.getEffectiveTransitionTime(), cancelled.getSubscriptionStartDate());
}
+ private BusinessSubscriptionEvent subscriptionChanged(final SubscriptionEvent changed) throws AccountApiException, EntitlementUserApiException {
+ return BusinessSubscriptionEvent.subscriptionChanged(changed.getNextPlan(), catalogService.getFullCatalog(), changed.getEffectiveTransitionTime(), changed.getSubscriptionStartDate());
+ }
- public void subscriptionChanged(final SubscriptionEvent changed) throws AccountApiException, EntitlementUserApiException {
- final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionChanged(changed.getNextPlan(), catalogService.getFullCatalog(), changed.getEffectiveTransitionTime(), changed.getSubscriptionStartDate());
- recordTransition(event, changed);
+ private BusinessSubscriptionEvent subscriptionPhaseChanged(final SubscriptionEvent phaseChanged) throws AccountApiException, EntitlementUserApiException {
+ return BusinessSubscriptionEvent.subscriptionPhaseChanged(phaseChanged.getNextPlan(), phaseChanged.getNextState(), catalogService.getFullCatalog(), phaseChanged.getEffectiveTransitionTime(), phaseChanged.getSubscriptionStartDate());
}
- public void subscriptionPhaseChanged(final SubscriptionEvent phaseChanged) throws AccountApiException, EntitlementUserApiException {
- final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionPhaseChanged(phaseChanged.getNextPlan(), phaseChanged.getNextState(), catalogService.getFullCatalog(), phaseChanged.getEffectiveTransitionTime(), phaseChanged.getSubscriptionStartDate());
- recordTransition(event, phaseChanged);
+ private BusinessSubscription createNextBusinessSubscription(final EffectiveSubscriptionEvent event, final BusinessSubscriptionEvent businessEvent, final Currency currency) {
+ final BusinessSubscription nextSubscription;
+ if (BusinessSubscriptionEvent.EventType.CANCEL.equals(businessEvent.getEventType()) ||
+ BusinessSubscriptionEvent.EventType.SYSTEM_CANCEL.equals(businessEvent.getEventType())) {
+ nextSubscription = null;
+ } else {
+ nextSubscription = new BusinessSubscription(event.getNextPriceList(), event.getNextPlan(), event.getNextPhase(),
+ currency, event.getEffectiveTransitionTime(), event.getNextState(),
+ catalogService.getFullCatalog());
+ }
+
+ return nextSubscription;
}
- void recordTransition(final BusinessSubscriptionEvent event, final SubscriptionEvent transition)
- throws AccountApiException, EntitlementUserApiException {
- Currency currency = null;
- String externalKey = null;
- String accountKey = null;
-
- // Retrieve key and currency via the bundle
- final SubscriptionBundle bundle = entitlementApi.getBundleFromId(transition.getBundleId());
- if (bundle != null) {
- externalKey = bundle.getKey();
-
- final Account account = accountApi.getAccountById(bundle.getAccountId());
- if (account != null) {
- accountKey = account.getExternalKey();
- currency = account.getCurrency();
- }
+ private BusinessSubscription createPreviousBusinessSubscription(final EffectiveSubscriptionEvent event,
+ final BusinessSubscriptionEvent businessEvent,
+ final ArrayList<BusinessSubscriptionTransition> transitions,
+ final Currency currency) {
+ if (BusinessSubscriptionEvent.EventType.ADD.equals(businessEvent.getEventType()) ||
+ BusinessSubscriptionEvent.EventType.RE_ADD.equals(businessEvent.getEventType())) {
+ return null;
}
- // The ISubscriptionTransition interface gives us all the prev/next information we need but the start date
- // of the previous plan. We need to retrieve it from our own transitions table
- DateTime previousEffectiveTransitionTime = null;
- // For creation events, the prev subscription will always be null
- if (event.getEventType() != BusinessSubscriptionEvent.EventType.ADD) {
- final List<BusinessSubscriptionTransition> transitions = sqlDao.getTransitions(externalKey);
- if (transitions != null && transitions.size() > 0) {
- final BusinessSubscriptionTransition lastTransition = transitions.get(transitions.size() - 1);
- if (lastTransition != null && lastTransition.getNextSubscription() != null) {
- previousEffectiveTransitionTime = lastTransition.getNextSubscription().getStartDate();
- }
+ final BusinessSubscriptionTransition prevTransition = getPreviousBusinessSubscriptionTransitionForEvent(event, transitions);
+ return new BusinessSubscription(event.getPreviousPriceList(), event.getPreviousPlan(), event.getPreviousPhase(),
+ currency, prevTransition.getNextSubscription().getStartDate(), event.getPreviousState(),
+ catalogService.getFullCatalog());
+ }
+
+ private BusinessSubscriptionTransition getPreviousBusinessSubscriptionTransitionForEvent(final EffectiveSubscriptionEvent event,
+ final ArrayList<BusinessSubscriptionTransition> transitions) {
+ BusinessSubscriptionTransition transition = null;
+ for (final BusinessSubscriptionTransition candidate : transitions) {
+ final BusinessSubscription nextSubscription = candidate.getNextSubscription();
+ if (nextSubscription == null || !nextSubscription.getStartDate().isBefore(event.getEffectiveTransitionTime())) {
+ continue;
}
- }
- // TODO Support currency changes
- final BusinessSubscription prevSubscription;
- if (previousEffectiveTransitionTime == null) {
- prevSubscription = null;
- } else {
- prevSubscription = new BusinessSubscription(transition.getPreviousPriceList(), transition.getPreviousPlan(), transition.getPreviousPhase(), currency, previousEffectiveTransitionTime, transition.getPreviousState(), transition.getSubscriptionId(), transition.getBundleId(), catalogService.getFullCatalog());
+ if (candidate.getSubscriptionId().equals(event.getSubscriptionId())) {
+ transition = candidate;
+ }
}
- final BusinessSubscription nextSubscription;
- // next plan is null for CANCEL events
- if (transition.getNextPlan() == null) {
- nextSubscription = null;
- } else {
- nextSubscription = new BusinessSubscription(transition.getNextPriceList(), transition.getNextPlan(), transition.getNextPhase(), currency, transition.getEffectiveTransitionTime(), transition.getNextState(), transition.getSubscriptionId(), transition.getBundleId(), catalogService.getFullCatalog());
+ if (transition == null) {
+ log.error("Unable to retrieve the previous transition - THIS SHOULD NEVER HAPPEN");
+ // Fall back to the latest one?
+ transition = transitions.get(transitions.size() - 1);
}
- record(transition.getTotalOrdering(), externalKey, accountKey, transition.getRequestedTransitionTime(), event, prevSubscription, nextSubscription);
- }
-
- // Public for internal reasons
- public void record(final Long totalOrdering, final String externalKey, final String accountKey, final DateTime requestedDateTime, final BusinessSubscriptionEvent event, final BusinessSubscription prevSubscription, final BusinessSubscription nextSubscription) {
- final BusinessSubscriptionTransition transition = new BusinessSubscriptionTransition(
- totalOrdering,
- externalKey,
- accountKey,
- requestedDateTime,
- event,
- prevSubscription,
- nextSubscription
- );
-
- log.info(transition.getEvent() + " " + transition);
- sqlDao.createTransition(transition);
+ return transition;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessTagRecorder.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessTagRecorder.java
index 8aa4343..7708f15 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/BusinessTagRecorder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessTagRecorder.java
@@ -87,61 +87,50 @@ public class BusinessTagRecorder {
}
}
- private void tagAddedForAccount(final UUID objectId, final String name) {
+ private void tagAddedForAccount(final UUID accountId, final String name) {
final Account account;
try {
- account = accountApi.getAccountById(objectId);
+ account = accountApi.getAccountById(accountId);
} catch (AccountApiException e) {
- log.warn("Ignoring tag addition of {} for account id {} (account does not exist)", name, objectId.toString());
+ log.warn("Ignoring tag addition of {} for account id {} (account does not exist)", name, accountId.toString());
return;
}
final String accountKey = account.getExternalKey();
- accountTagSqlDao.addTag(accountKey, name);
+ accountTagSqlDao.addTag(accountId.toString(), accountKey, name);
}
- private void tagRemovedForAccount(final UUID objectId, final String name) {
- final Account account;
- try {
- account = accountApi.getAccountById(objectId);
- } catch (AccountApiException e) {
- log.warn("Ignoring tag removal of {} for account id {} (account does not exist)", name, objectId.toString());
- return;
- }
-
- final String accountKey = account.getExternalKey();
- accountTagSqlDao.removeTag(accountKey, name);
+ private void tagRemovedForAccount(final UUID accountId, final String name) {
+ accountTagSqlDao.removeTag(accountId.toString(), name);
}
- private void tagAddedForBundle(final UUID objectId, final String name) {
+ private void tagAddedForBundle(final UUID bundleId, final String name) {
final SubscriptionBundle bundle;
try {
- bundle = entitlementUserApi.getBundleFromId(objectId);
+ bundle = entitlementUserApi.getBundleFromId(bundleId);
} catch (EntitlementUserApiException e) {
- log.warn("Ignoring tag addition of {} for bundle id {} (bundle does not exist)", name, objectId.toString());
+ log.warn("Ignoring tag addition of {} for bundle id {} (bundle does not exist)", name, bundleId.toString());
+ return;
+ }
+
+ final Account account;
+ try {
+ account = accountApi.getAccountById(bundle.getAccountId());
+ } catch (AccountApiException e) {
+ log.warn("Ignoring tag addition of {} for bundle id {} and account id {} (account does not exist)", new Object[]{name, bundleId.toString(), bundle.getAccountId()});
return;
}
/*
* Note: we store tags associated to bundles, not to subscriptions.
- * Subscriptions are in the core of killbill and not exposed in Analytics to avoid a hard dependency
- * (i.e. dashboards should not rely on killbill ids).
*/
+ final String accountKey = account.getExternalKey();
final String externalKey = bundle.getKey();
- subscriptionTransitionTagSqlDao.addTag(externalKey, name);
+ subscriptionTransitionTagSqlDao.addTag(accountKey, bundleId.toString(), externalKey, name);
}
- private void tagRemovedForBundle(final UUID objectId, final String name) {
- final SubscriptionBundle bundle;
- try {
- bundle = entitlementUserApi.getBundleFromId(objectId);
- } catch (EntitlementUserApiException e) {
- log.warn("Ignoring tag removal of {} for bundle id {} (bundle does not exist)", name, objectId.toString());
- return;
- }
-
- final String externalKey = bundle.getKey();
- subscriptionTransitionTagSqlDao.removeTag(externalKey, name);
+ private void tagRemovedForBundle(final UUID bundleId, final String name) {
+ subscriptionTransitionTagSqlDao.removeTag(bundleId.toString(), name);
}
private void tagAddedForInvoice(final UUID objectId, final String name) {
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/AnalyticsDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/AnalyticsDao.java
index 8dcc6c8..0e349fc 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/AnalyticsDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/AnalyticsDao.java
@@ -22,6 +22,8 @@ import com.ning.billing.analytics.model.BusinessAccount;
import com.ning.billing.analytics.model.BusinessAccountTag;
import com.ning.billing.analytics.model.BusinessInvoice;
import com.ning.billing.analytics.model.BusinessInvoiceItem;
+import com.ning.billing.analytics.model.BusinessInvoicePayment;
+import com.ning.billing.analytics.model.BusinessOverdueStatus;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
public interface AnalyticsDao {
@@ -35,5 +37,7 @@ public interface AnalyticsDao {
List<BusinessInvoiceItem> getInvoiceItemsForInvoice(final String invoiceId);
- void createInvoice(final String accountKey, final BusinessInvoice invoice, final Iterable<BusinessInvoiceItem> invoiceItems);
+ List<BusinessOverdueStatus> getOverdueStatusesForBundleByKey(final String externalKey);
+
+ List<BusinessInvoicePayment> getInvoicePaymentsForAccountByKey(final String accountKey);
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountBinder.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountBinder.java
index 223068e..3ba6ea5 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountBinder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountBinder.java
@@ -49,6 +49,7 @@ public @interface BusinessAccountBinder {
}
q.bind("updated_date", dateTimeNow.getMillis());
+ q.bind("account_id", account.getAccountId().toString());
q.bind("account_key", account.getKey());
q.bind("balance", account.getRoundedBalance());
q.bind("name", account.getName());
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldMapper.java
index 7cb7260..411af1a 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldMapper.java
@@ -18,6 +18,7 @@ package com.ning.billing.analytics.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
@@ -27,6 +28,10 @@ import com.ning.billing.analytics.model.BusinessAccountField;
public class BusinessAccountFieldMapper implements ResultSetMapper<BusinessAccountField> {
@Override
public BusinessAccountField map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
- return new BusinessAccountField(r.getString(1), r.getString(2), r.getString(3));
+ final UUID accountId = UUID.fromString(r.getString(1));
+ final String accountKey = r.getString(2);
+ final String name = r.getString(3);
+ final String value = r.getString(4);
+ return new BusinessAccountField(accountId, accountKey, name, value);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.java
index d982772..4aed48a 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.java
@@ -30,13 +30,14 @@ import com.ning.billing.analytics.model.BusinessAccountField;
@RegisterMapper(BusinessAccountFieldMapper.class)
public interface BusinessAccountFieldSqlDao {
@SqlQuery
- List<BusinessAccountField> getFieldsForAccount(@Bind("account_key") final String accountKey);
+ List<BusinessAccountField> getFieldsForAccountByKey(@Bind("account_key") final String accountKey);
@SqlUpdate
- int addField(@Bind("account_key") final String accountKey, @Bind("name") final String name, @Bind("value") final String value);
+ int addField(@Bind("account_id") final String accountId, @Bind("account_key") final String accountKey,
+ @Bind("name") final String name, @Bind("value") final String value);
@SqlUpdate
- int removeField(@Bind("account_key") final String accountKey, @Bind("name") final String name);
+ int removeField(@Bind("account_id") final String accountId, @Bind("name") final String name);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountMapper.java
index bf4da3d..7bced4f 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountMapper.java
@@ -19,6 +19,7 @@ package com.ning.billing.analytics.dao;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -31,18 +32,19 @@ public class BusinessAccountMapper implements ResultSetMapper<BusinessAccount> {
@Override
public BusinessAccount map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
final BusinessAccount account = new BusinessAccount(
- r.getString(1),
- r.getString(5),
- BigDecimal.valueOf(r.getDouble(4)),
- r.getLong(6) == 0 ? null : new DateTime(r.getLong(6), DateTimeZone.UTC),
- BigDecimal.valueOf(r.getDouble(7)),
- r.getString(8),
+ UUID.fromString(r.getString(1)),
+ r.getString(2),
+ r.getString(6),
+ BigDecimal.valueOf(r.getDouble(5)),
+ r.getLong(7) == 0 ? null : new DateTime(r.getLong(7), DateTimeZone.UTC),
+ BigDecimal.valueOf(r.getDouble(8)),
r.getString(9),
r.getString(10),
- r.getString(11)
+ r.getString(11),
+ r.getString(12)
);
- account.setCreatedDt(new DateTime(r.getLong(2), DateTimeZone.UTC));
- account.setUpdatedDt(new DateTime(r.getLong(3), DateTimeZone.UTC));
+ account.setCreatedDt(new DateTime(r.getLong(3), DateTimeZone.UTC));
+ account.setUpdatedDt(new DateTime(r.getLong(4), DateTimeZone.UTC));
return account;
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountSqlDao.java
index 605e604..8ceb0ad 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountSqlDao.java
@@ -30,7 +30,10 @@ import com.ning.billing.analytics.model.BusinessAccount;
@RegisterMapper(BusinessAccountMapper.class)
public interface BusinessAccountSqlDao extends Transactional<BusinessAccountSqlDao>, Transmogrifier {
@SqlQuery
- BusinessAccount getAccount(@Bind("account_key") final String key);
+ BusinessAccount getAccount(@Bind("account_id") final String accountId);
+
+ @SqlQuery
+ BusinessAccount getAccountByKey(@Bind("account_key") String accountKey);
@SqlUpdate
int createAccount(@BusinessAccountBinder final BusinessAccount account);
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagMapper.java
index ddad81d..e8897d7 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagMapper.java
@@ -18,6 +18,7 @@ package com.ning.billing.analytics.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
@@ -27,6 +28,9 @@ import com.ning.billing.analytics.model.BusinessAccountTag;
public class BusinessAccountTagMapper implements ResultSetMapper<BusinessAccountTag> {
@Override
public BusinessAccountTag map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
- return new BusinessAccountTag(r.getString(1), r.getString(2));
+ final UUID accountId = UUID.fromString(r.getString(1));
+ final String accountKey = r.getString(2);
+ final String name = r.getString(3);
+ return new BusinessAccountTag(accountId, accountKey, name);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.java
index 0aac244..77cb020 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.java
@@ -30,13 +30,13 @@ import com.ning.billing.analytics.model.BusinessAccountTag;
@RegisterMapper(BusinessAccountTagMapper.class)
public interface BusinessAccountTagSqlDao {
@SqlQuery
- List<BusinessAccountTag> getTagsForAccount(@Bind("account_key") final String accountKey);
+ List<BusinessAccountTag> getTagsForAccountByKey(@Bind("account_key") final String accountKey);
@SqlUpdate
- int addTag(@Bind("account_key") final String accountKey, @Bind("name") final String name);
+ int addTag(@Bind("account_id") final String accountId, @Bind("account_key") final String accountKey, @Bind("name") final String name);
@SqlUpdate
- int removeTag(@Bind("account_key") final String accountKey, @Bind("name") final String name);
+ int removeTag(@Bind("account_id") final String accountId, @Bind("name") final String name);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceBinder.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceBinder.java
index 412f323..fa8358b 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceBinder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceBinder.java
@@ -43,6 +43,12 @@ public @interface BusinessInvoiceBinder {
public void bind(final SQLStatement q, final BusinessInvoiceBinder bind, final BusinessInvoice invoice) {
q.bind("invoice_id", invoice.getInvoiceId().toString());
+ if (invoice.getInvoiceNumber() != null) {
+ q.bind("invoice_number", invoice.getInvoiceNumber());
+ } else {
+ q.bindNull("invoice_number", Types.BIGINT);
+ }
+
final DateTime dateTimeNow = new DateTime(DateTimeZone.UTC);
if (invoice.getCreatedDate() != null) {
q.bind("created_date", invoice.getCreatedDate().getMillis());
@@ -56,6 +62,7 @@ public @interface BusinessInvoiceBinder {
q.bind("updated_date", dateTimeNow.getMillis());
}
+ q.bind("account_id", invoice.getAccountId().toString());
q.bind("account_key", invoice.getAccountKey());
if (invoice.getInvoiceDate() != null) {
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.java
index dd18e3a..f94293a 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.java
@@ -38,15 +38,12 @@ public interface BusinessInvoiceItemSqlDao extends Transactional<BusinessInvoice
List<BusinessInvoiceItem> getInvoiceItemsForInvoice(@Bind("invoice_id") final String invoiceId);
@SqlQuery
- List<BusinessInvoiceItem> getInvoiceItemsForBundle(@Bind("external_key") final String externalKey);
+ List<BusinessInvoiceItem> getInvoiceItemsForBundleByKey(@Bind("external_key") final String externalKey);
@SqlUpdate
int createInvoiceItem(@BusinessInvoiceItemBinder final BusinessInvoiceItem invoiceItem);
@SqlUpdate
- int updateInvoiceItem(@BusinessInvoiceItemBinder final BusinessInvoiceItem invoiceItem);
-
- @SqlUpdate
int deleteInvoiceItem(@Bind("item_id") final String itemId);
@SqlUpdate
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceMapper.java
index 93d727a..e6df819 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceMapper.java
@@ -33,18 +33,20 @@ public class BusinessInvoiceMapper implements ResultSetMapper<BusinessInvoice> {
@Override
public BusinessInvoice map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
final UUID invoiceId = UUID.fromString(r.getString(1));
- final DateTime createdDate = new DateTime(r.getLong(2), DateTimeZone.UTC);
- final DateTime updatedDate = new DateTime(r.getLong(3), DateTimeZone.UTC);
- final String accountKey = r.getString(4);
- final DateTime invoiceDate = new DateTime(r.getLong(5), DateTimeZone.UTC);
- final DateTime targetDate = new DateTime(r.getLong(6), DateTimeZone.UTC);
- final Currency currency = Currency.valueOf(r.getString(7));
- final BigDecimal balance = BigDecimal.valueOf(r.getDouble(8));
- final BigDecimal amountPaid = BigDecimal.valueOf(r.getDouble(9));
- final BigDecimal amountCharged = BigDecimal.valueOf(r.getDouble(10));
- final BigDecimal amountCredited = BigDecimal.valueOf(r.getDouble(11));
+ final Integer invoiceNumber = r.getInt(2);
+ final DateTime createdDate = new DateTime(r.getLong(3), DateTimeZone.UTC);
+ final DateTime updatedDate = new DateTime(r.getLong(4), DateTimeZone.UTC);
+ final UUID accountId = UUID.fromString(r.getString(5));
+ final String accountKey = r.getString(6);
+ final DateTime invoiceDate = new DateTime(r.getLong(7), DateTimeZone.UTC);
+ final DateTime targetDate = new DateTime(r.getLong(8), DateTimeZone.UTC);
+ final Currency currency = Currency.valueOf(r.getString(9));
+ final BigDecimal balance = BigDecimal.valueOf(r.getDouble(10));
+ final BigDecimal amountPaid = BigDecimal.valueOf(r.getDouble(11));
+ final BigDecimal amountCharged = BigDecimal.valueOf(r.getDouble(12));
+ final BigDecimal amountCredited = BigDecimal.valueOf(r.getDouble(13));
- return new BusinessInvoice(accountKey, amountCharged, amountCredited, amountPaid, balance, createdDate, currency,
- invoiceDate, invoiceId, targetDate, updatedDate);
+ return new BusinessInvoice(accountId, accountKey, amountCharged, amountCredited, amountPaid, balance, createdDate, currency,
+ invoiceDate, invoiceId, invoiceNumber, targetDate, updatedDate);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentBinder.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentBinder.java
index 8c01e8f..c55111c 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentBinder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentBinder.java
@@ -22,6 +22,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -56,7 +57,7 @@ public @interface BusinessInvoicePaymentBinder {
q.bind("updated_date", dateTimeNow.getMillis());
}
- q.bind("attempt_id", invoicePayment.getAttemptId().toString());
+ q.bind("ext_payment_ref_id", invoicePayment.getExtPaymentRefId());
q.bind("account_key", invoicePayment.getAccountKey());
q.bind("invoice_id", invoicePayment.getInvoiceId().toString());
@@ -76,6 +77,14 @@ public @interface BusinessInvoicePaymentBinder {
q.bind("payment_method", invoicePayment.getPaymentMethod());
q.bind("card_type", invoicePayment.getCardType());
q.bind("card_country", invoicePayment.getCardCountry());
+ q.bind("invoice_payment_type", invoicePayment.getInvoicePaymentType());
+
+ final UUID linkedInvoicePaymentId = invoicePayment.getLinkedInvoicePaymentId();
+ if (linkedInvoicePaymentId != null) {
+ q.bind("linked_invoice_payment_id", linkedInvoicePaymentId.toString());
+ } else {
+ q.bindNull("linked_invoice_payment_id", Types.VARCHAR);
+ }
}
};
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentMapper.java
index af80d53..de11209 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentMapper.java
@@ -35,7 +35,7 @@ public class BusinessInvoicePaymentMapper implements ResultSetMapper<BusinessInv
final UUID paymentId = UUID.fromString(r.getString(1));
final DateTime createdDate = new DateTime(r.getLong(2), DateTimeZone.UTC);
final DateTime updatedDate = new DateTime(r.getLong(3), DateTimeZone.UTC);
- final UUID attemptId = UUID.fromString(r.getString(4));
+ final String extPaymentRefId = r.getString(4);
final String accountKey = r.getString(5);
final UUID invoiceId = UUID.fromString(r.getString(6));
final DateTime effectiveDate = new DateTime(r.getLong(7), DateTimeZone.UTC);
@@ -49,9 +49,19 @@ public class BusinessInvoicePaymentMapper implements ResultSetMapper<BusinessInv
final String paymentMethod = r.getString(15);
final String cardType = r.getString(16);
final String cardCountry = r.getString(17);
+ final String invoicePaymentType = r.getString(18);
+ final String linkedInvoicePaymentIdString = r.getString(19);
- return new BusinessInvoicePayment(accountKey, amount, attemptId, cardCountry, cardType, createdDate, currency,
+ final UUID linkedInvoicePaymentId;
+ if (linkedInvoicePaymentIdString != null) {
+ linkedInvoicePaymentId = UUID.fromString(linkedInvoicePaymentIdString);
+ } else {
+ linkedInvoicePaymentId = null;
+ }
+
+ return new BusinessInvoicePayment(accountKey, amount, extPaymentRefId, cardCountry, cardType, createdDate, currency,
effectiveDate, invoiceId, paymentError, paymentId, paymentMethod, paymentType,
- pluginName, processingStatus, requestedAmount, updatedDate);
+ pluginName, processingStatus, requestedAmount, updatedDate, invoicePaymentType,
+ linkedInvoicePaymentId);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.java
index 681378d..d21613a 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.java
@@ -22,30 +22,26 @@ import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
+import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
+import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3;
import com.ning.billing.analytics.model.BusinessInvoicePayment;
@ExternalizedSqlViaStringTemplate3()
@RegisterMapper(BusinessInvoicePaymentMapper.class)
-public interface BusinessInvoicePaymentSqlDao {
+public interface BusinessInvoicePaymentSqlDao extends Transactional<BusinessInvoicePaymentSqlDao>, Transmogrifier {
@SqlQuery
- BusinessInvoicePayment getInvoicePaymentForPaymentAttempt(@Bind("attempt_id") final String attemptId);
+ BusinessInvoicePayment getInvoicePayment(@Bind("payment_id") final String paymentId);
@SqlQuery
- List<BusinessInvoicePayment> getInvoicePaymentsForPayment(@Bind("payment_id") final String paymentId);
-
- @SqlQuery
- List<BusinessInvoicePayment> getInvoicePaymentsForAccount(@Bind("account_key") final String accountKey);
+ List<BusinessInvoicePayment> getInvoicePaymentsForAccountByKey(@Bind("account_key") final String accountKey);
@SqlUpdate
int createInvoicePayment(@BusinessInvoicePaymentBinder final BusinessInvoicePayment payment);
@SqlUpdate
- int updateInvoicePaymentForPaymentAttempt(@BusinessInvoicePaymentBinder final BusinessInvoicePayment payment);
-
- @SqlUpdate
- int deleteInvoicePaymentForPaymentAttempt(@Bind("attempt_id") final String attemptId);
+ int deleteInvoicePayment(@Bind("payment_id") final String paymentId);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.java
index d3c8c6e..73fbb9b 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.java
@@ -35,16 +35,19 @@ public interface BusinessInvoiceSqlDao extends Transactional<BusinessInvoiceSqlD
BusinessInvoice getInvoice(@Bind("invoice_id") final String invoiceId);
@SqlQuery
- List<BusinessInvoice> getInvoicesForAccount(@Bind("account_key") final String accountKey);
+ List<BusinessInvoice> getInvoicesForAccount(@Bind("account_id") final String accountId);
+
+ @SqlQuery
+ List<BusinessInvoice> getInvoicesForAccountByKey(@Bind("account_key") final String accountKey);
@SqlUpdate
int createInvoice(@BusinessInvoiceBinder final BusinessInvoice invoice);
@SqlUpdate
- int updateInvoice(@BusinessInvoiceBinder final BusinessInvoice invoice);
+ int deleteInvoice(@Bind("invoice_id") final String invoiceId);
@SqlUpdate
- int deleteInvoice(@Bind("invoice_id") final String invoiceId);
+ void deleteInvoicesForAccount(@Bind("account_id") final String accountId);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusBinder.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusBinder.java
index eb1bd9d..879b2ee 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusBinder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusBinder.java
@@ -38,6 +38,8 @@ public @interface BusinessOverdueStatusBinder {
public Binder build(final Annotation annotation) {
return new Binder<BusinessOverdueStatusBinder, BusinessOverdueStatus>() {
public void bind(final SQLStatement q, final BusinessOverdueStatusBinder bind, final BusinessOverdueStatus overdueStatus) {
+ q.bind("account_key", overdueStatus.getAccountKey());
+ q.bind("bundle_id", overdueStatus.getBundleId().toString());
q.bind("external_key", overdueStatus.getExternalKey());
q.bind("status", overdueStatus.getStatus());
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusMapper.java
index dcd6bf2..35ef90e 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusMapper.java
@@ -18,6 +18,7 @@ package com.ning.billing.analytics.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -29,11 +30,13 @@ import com.ning.billing.analytics.model.BusinessOverdueStatus;
public class BusinessOverdueStatusMapper implements ResultSetMapper<BusinessOverdueStatus> {
@Override
public BusinessOverdueStatus map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
- final String externalKey = r.getString(1);
- final String status = r.getString(2);
- final DateTime startDate = new DateTime(r.getLong(3), DateTimeZone.UTC);
- final DateTime endDate = new DateTime(r.getLong(4), DateTimeZone.UTC);
+ final UUID bundleId = UUID.fromString(r.getString(1));
+ final String externalKey = r.getString(2);
+ final String accountKey = r.getString(3);
+ final String status = r.getString(4);
+ final DateTime startDate = new DateTime(r.getLong(5), DateTimeZone.UTC);
+ final DateTime endDate = new DateTime(r.getLong(6), DateTimeZone.UTC);
- return new BusinessOverdueStatus(endDate, externalKey, startDate, status);
+ return new BusinessOverdueStatus(accountKey, bundleId, endDate, externalKey, startDate, status);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.java
index 44668d0..c0d501b 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.java
@@ -22,19 +22,24 @@ import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
+import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
+import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3;
import com.ning.billing.analytics.model.BusinessOverdueStatus;
@ExternalizedSqlViaStringTemplate3()
@RegisterMapper(BusinessOverdueStatusMapper.class)
-public interface BusinessOverdueStatusSqlDao {
+public interface BusinessOverdueStatusSqlDao extends Transactional<BusinessOverdueStatusSqlDao>, Transmogrifier {
@SqlQuery
- List<BusinessOverdueStatus> getOverdueStatusesForBundle(@Bind("external_key") final String externalKey);
+ List<BusinessOverdueStatus> getOverdueStatusesForBundleByKey(@Bind("external_key") final String externalKey);
@SqlUpdate
int createOverdueStatus(@BusinessOverdueStatusBinder final BusinessOverdueStatus status);
@SqlUpdate
+ void deleteOverdueStatusesForBundle(@Bind("bundle_id") final String bundleId);
+
+ @SqlUpdate
void test();
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionBinder.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionBinder.java
index 9e5b507..73804a3 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionBinder.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionBinder.java
@@ -40,8 +40,11 @@ public @interface BusinessSubscriptionTransitionBinder {
return new Binder<BusinessSubscriptionTransitionBinder, BusinessSubscriptionTransition>() {
public void bind(final SQLStatement q, final BusinessSubscriptionTransitionBinder bind, final BusinessSubscriptionTransition arg) {
q.bind("total_ordering", arg.getTotalOrdering());
+ q.bind("bundle_id", arg.getBundleId().toString());
q.bind("external_key", arg.getExternalKey());
+ q.bind("account_id", arg.getAccountId().toString());
q.bind("account_key", arg.getAccountKey());
+ q.bind("subscription_id", arg.getSubscriptionId().toString());
q.bind("requested_timestamp", arg.getRequestedTimestamp().getMillis());
q.bind("event", arg.getEvent().toString());
@@ -59,8 +62,6 @@ public @interface BusinessSubscriptionTransitionBinder {
q.bindNull("prev_currency", Types.VARCHAR);
q.bindNull("prev_start_date", Types.BIGINT);
q.bindNull("prev_state", Types.VARCHAR);
- q.bindNull("prev_subscription_id", Types.VARCHAR);
- q.bindNull("prev_bundle_id", Types.VARCHAR);
} else {
q.bind("prev_product_name", previousSubscription.getProductName());
q.bind("prev_product_type", previousSubscription.getProductType());
@@ -86,16 +87,6 @@ public @interface BusinessSubscriptionTransitionBinder {
} else {
q.bind("prev_state", previousSubscription.getState().toString());
}
- if (previousSubscription.getSubscriptionId() == null) {
- q.bindNull("prev_subscription_id", Types.VARCHAR);
- } else {
- q.bind("prev_subscription_id", previousSubscription.getSubscriptionId().toString());
- }
- if (previousSubscription.getBundleId() == null) {
- q.bindNull("prev_bundle_id", Types.VARCHAR);
- } else {
- q.bind("prev_bundle_id", previousSubscription.getBundleId().toString());
- }
}
final BusinessSubscription nextSubscription = arg.getNextSubscription();
@@ -112,8 +103,6 @@ public @interface BusinessSubscriptionTransitionBinder {
q.bindNull("next_currency", Types.VARCHAR);
q.bindNull("next_start_date", Types.BIGINT);
q.bindNull("next_state", Types.VARCHAR);
- q.bindNull("next_subscription_id", Types.VARCHAR);
- q.bindNull("next_bundle_id", Types.VARCHAR);
} else {
q.bind("next_product_name", nextSubscription.getProductName());
q.bind("next_product_type", nextSubscription.getProductType());
@@ -139,16 +128,6 @@ public @interface BusinessSubscriptionTransitionBinder {
} else {
q.bind("next_state", nextSubscription.getState().toString());
}
- if (nextSubscription.getSubscriptionId() == null) {
- q.bindNull("next_subscription_id", Types.VARCHAR);
- } else {
- q.bind("next_subscription_id", nextSubscription.getSubscriptionId().toString());
- }
- if (nextSubscription.getBundleId() == null) {
- q.bindNull("next_bundle_id", Types.VARCHAR);
- } else {
- q.bind("next_bundle_id", nextSubscription.getBundleId().toString());
- }
}
}
};
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldMapper.java
index 68ef0e2..56540b8 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldMapper.java
@@ -18,6 +18,7 @@ package com.ning.billing.analytics.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
@@ -27,6 +28,11 @@ import com.ning.billing.analytics.model.BusinessSubscriptionTransitionField;
public class BusinessSubscriptionTransitionFieldMapper implements ResultSetMapper<BusinessSubscriptionTransitionField> {
@Override
public BusinessSubscriptionTransitionField map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
- return new BusinessSubscriptionTransitionField(r.getString(1), r.getString(2), r.getString(3));
+ final UUID bundleId = UUID.fromString(r.getString(1));
+ final String externalKey = r.getString(2);
+ final String accountKey = r.getString(3);
+ final String name = r.getString(4);
+ final String value = r.getString(5);
+ return new BusinessSubscriptionTransitionField(accountKey, bundleId, externalKey, name, value);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.java
index d22076e..3a3411d 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.java
@@ -30,13 +30,14 @@ import com.ning.billing.analytics.model.BusinessSubscriptionTransitionField;
@RegisterMapper(BusinessSubscriptionTransitionFieldMapper.class)
public interface BusinessSubscriptionTransitionFieldSqlDao {
@SqlQuery
- List<BusinessSubscriptionTransitionField> getFieldsForBusinessSubscriptionTransition(@Bind("external_key") final String externalKey);
+ List<BusinessSubscriptionTransitionField> getFieldsForBusinessSubscriptionTransitionByKey(@Bind("external_key") final String externalKey);
@SqlUpdate
- int addField(@Bind("external_key") final String externalKey, @Bind("name") final String name, @Bind("value") final String value);
+ int addField(@Bind("account_key") final String accountKey, @Bind("bundle_id") final String bundleId, @Bind("external_key") final String externalKey,
+ @Bind("name") final String name, @Bind("value") final String value);
@SqlUpdate
- int removeField(@Bind("external_key") final String externalKey, @Bind("name") final String name);
+ int removeField(@Bind("bundle_id") final String bundleId, @Bind("name") final String name);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionMapper.java
index c5bdf96..97ecc5b 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionMapper.java
@@ -37,20 +37,18 @@ public class BusinessSubscriptionTransitionMapper implements ResultSetMapper<Bus
@Override
public BusinessSubscriptionTransition map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
BusinessSubscription prev = new BusinessSubscription(
- r.getString(6), // productName
- r.getString(7), // productType
- r.getString(8) == null ? null : ProductCategory.valueOf(r.getString(8)), // productCategory
- r.getString(9), // slug
- r.getString(10), // phase
- r.getString(11), // billing period
- BigDecimal.valueOf(r.getDouble(12)), // price
- r.getString(13), // priceList
- BigDecimal.valueOf(r.getDouble(14)), // mrr
- r.getString(15), // currency
- r.getLong(16) == 0 ? null : new DateTime(r.getLong(16), DateTimeZone.UTC), // startDate
- r.getString(17) == null ? null : SubscriptionState.valueOf(r.getString(17)), // state
- r.getString(18) == null ? null : UUID.fromString(r.getString(18)), // subscriptionId
- r.getString(19) == null ? null : UUID.fromString(r.getString(19)) //bundleId
+ r.getString(9), // productName
+ r.getString(10), // productType
+ r.getString(11) == null ? null : ProductCategory.valueOf(r.getString(11)), // productCategory
+ r.getString(12), // slug
+ r.getString(13), // phase
+ r.getString(14), // billing period
+ BigDecimal.valueOf(r.getDouble(15)), // price
+ r.getString(16), // priceList
+ BigDecimal.valueOf(r.getDouble(17)), // mrr
+ r.getString(18), // currency
+ r.getLong(19) == 0 ? null : new DateTime(r.getLong(19), DateTimeZone.UTC), // startDate
+ r.getString(20) == null ? null : SubscriptionState.valueOf(r.getString(20)) // state
);
// Avoid creating a dummy subscriptions with all null fields
@@ -59,20 +57,18 @@ public class BusinessSubscriptionTransitionMapper implements ResultSetMapper<Bus
}
BusinessSubscription next = new BusinessSubscription(
- r.getString(20), // productName
- r.getString(21), // productType
- r.getString(22) == null ? null : ProductCategory.valueOf(r.getString(22)), // productCategory
- r.getString(23), // slug8
- r.getString(24), // phase
- r.getString(25), // billing period
- BigDecimal.valueOf(r.getDouble(26)), // price
- r.getString(27), // priceList
- BigDecimal.valueOf(r.getDouble(28)), // mrr
- r.getString(29), // currency
- r.getLong(30) == 0 ? null : new DateTime(r.getLong(30), DateTimeZone.UTC), // startDate
- r.getString(31) == null ? null : SubscriptionState.valueOf(r.getString(31)), // state
- r.getString(32) == null ? null : UUID.fromString(r.getString(32)), // subscriptionId
- r.getString(33) == null ? null : UUID.fromString(r.getString(33)) //bundleId
+ r.getString(21), // productName
+ r.getString(22), // productType
+ r.getString(23) == null ? null : ProductCategory.valueOf(r.getString(23)), // productCategory
+ r.getString(24), // slug8
+ r.getString(25), // phase
+ r.getString(26), // billing period
+ BigDecimal.valueOf(r.getDouble(27)), // price
+ r.getString(28), // priceList
+ BigDecimal.valueOf(r.getDouble(29)), // mrr
+ r.getString(30), // currency
+ r.getLong(31) == 0 ? null : new DateTime(r.getLong(31), DateTimeZone.UTC), // startDate
+ r.getString(32) == null ? null : SubscriptionState.valueOf(r.getString(32)) // state
);
// Avoid creating a dummy subscriptions with all null fields
@@ -80,13 +76,16 @@ public class BusinessSubscriptionTransitionMapper implements ResultSetMapper<Bus
next = null;
}
- final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.valueOf(r.getString(5));
+ final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.valueOf(r.getString(8));
return new BusinessSubscriptionTransition(
r.getLong(1),
- r.getString(2),
+ UUID.fromString(r.getString(2)),
r.getString(3),
- new DateTime(r.getLong(4), DateTimeZone.UTC),
+ UUID.fromString(r.getString(4)),
+ r.getString(5),
+ UUID.fromString(r.getString(6)),
+ new DateTime(r.getLong(7), DateTimeZone.UTC),
event,
prev,
next
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.java
index fe90321..3c8fd44 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.java
@@ -22,19 +22,26 @@ import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
+import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
@ExternalizedSqlViaStringTemplate3()
@RegisterMapper(BusinessSubscriptionTransitionMapper.class)
-public interface BusinessSubscriptionTransitionSqlDao {
+public interface BusinessSubscriptionTransitionSqlDao extends Transactional<BusinessSubscriptionTransitionSqlDao> {
@SqlQuery
- List<BusinessSubscriptionTransition> getTransitions(@Bind("external_key") final String externalKey);
+ List<BusinessSubscriptionTransition> getTransitionsByKey(@Bind("external_key") final String externalKey);
+
+ @SqlQuery
+ List<BusinessSubscriptionTransition> getTransitionForSubscription(@Bind("subscription_id") final String subscriptionId);
@SqlUpdate
int createTransition(@BusinessSubscriptionTransitionBinder final BusinessSubscriptionTransition transition);
@SqlUpdate
+ void deleteTransitionsForBundle(@Bind("bundle_id") final String bundleId);
+
+ @SqlUpdate
void test();
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagMapper.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagMapper.java
index 36f7631..25ae0be 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagMapper.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagMapper.java
@@ -18,6 +18,7 @@ package com.ning.billing.analytics.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.UUID;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
@@ -27,6 +28,10 @@ import com.ning.billing.analytics.model.BusinessSubscriptionTransitionTag;
public class BusinessSubscriptionTransitionTagMapper implements ResultSetMapper<BusinessSubscriptionTransitionTag> {
@Override
public BusinessSubscriptionTransitionTag map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
- return new BusinessSubscriptionTransitionTag(r.getString(1), r.getString(2));
+ final UUID bundleId = UUID.fromString(r.getString(1));
+ final String externalKey = r.getString(2);
+ final String accountKey = r.getString(3);
+ final String name = r.getString(4);
+ return new BusinessSubscriptionTransitionTag(accountKey, bundleId, externalKey, name);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.java
index c073a53..07d4f24 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.java
@@ -30,13 +30,14 @@ import com.ning.billing.analytics.model.BusinessSubscriptionTransitionTag;
@RegisterMapper(BusinessSubscriptionTransitionTagMapper.class)
public interface BusinessSubscriptionTransitionTagSqlDao {
@SqlQuery
- List<BusinessSubscriptionTransitionTag> getTagsForBusinessSubscriptionTransition(@Bind("external_key") final String externalKey);
+ List<BusinessSubscriptionTransitionTag> getTagsForBusinessSubscriptionTransitionByKey(@Bind("external_key") final String externalKey);
@SqlUpdate
- int addTag(@Bind("external_key") final String externalKey, @Bind("name") final String name);
+ int addTag(@Bind("account_key") final String accountKey, @Bind("bundle_id") final String bundleId,
+ @Bind("external_key") final String externalKey, @Bind("name") final String name);
@SqlUpdate
- int removeTag(@Bind("external_key") final String externalKey, @Bind("name") final String name);
+ int removeTag(@Bind("bundle_id") final String bundleId, @Bind("name") final String name);
@SqlUpdate
void test();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/dao/DefaultAnalyticsDao.java b/analytics/src/main/java/com/ning/billing/analytics/dao/DefaultAnalyticsDao.java
index d5f8627..d4855fd 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/dao/DefaultAnalyticsDao.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/dao/DefaultAnalyticsDao.java
@@ -19,15 +19,12 @@ package com.ning.billing.analytics.dao;
import javax.inject.Inject;
import java.util.List;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
-import org.skife.jdbi.v2.Transaction;
-import org.skife.jdbi.v2.TransactionStatus;
-
import com.ning.billing.analytics.model.BusinessAccount;
import com.ning.billing.analytics.model.BusinessAccountTag;
import com.ning.billing.analytics.model.BusinessInvoice;
import com.ning.billing.analytics.model.BusinessInvoiceItem;
+import com.ning.billing.analytics.model.BusinessInvoicePayment;
+import com.ning.billing.analytics.model.BusinessOverdueStatus;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
public class DefaultAnalyticsDao implements AnalyticsDao {
@@ -36,38 +33,44 @@ public class DefaultAnalyticsDao implements AnalyticsDao {
private final BusinessInvoiceSqlDao invoiceSqlDao;
private final BusinessInvoiceItemSqlDao invoiceItemSqlDao;
private final BusinessAccountTagSqlDao accountTagSqlDao;
+ private final BusinessOverdueStatusSqlDao overdueStatusSqlDao;
+ private final BusinessInvoicePaymentSqlDao invoicePaymentSqlDao;
@Inject
public DefaultAnalyticsDao(final BusinessAccountSqlDao accountSqlDao,
final BusinessSubscriptionTransitionSqlDao subscriptionTransitionSqlDao,
final BusinessInvoiceSqlDao invoiceSqlDao,
final BusinessInvoiceItemSqlDao invoiceItemSqlDao,
- final BusinessAccountTagSqlDao accountTagSqlDao) {
+ final BusinessAccountTagSqlDao accountTagSqlDao,
+ final BusinessOverdueStatusSqlDao overdueStatusSqlDao,
+ final BusinessInvoicePaymentSqlDao invoicePaymentSqlDao) {
this.accountSqlDao = accountSqlDao;
this.subscriptionTransitionSqlDao = subscriptionTransitionSqlDao;
this.invoiceSqlDao = invoiceSqlDao;
this.invoiceItemSqlDao = invoiceItemSqlDao;
this.accountTagSqlDao = accountTagSqlDao;
+ this.overdueStatusSqlDao = overdueStatusSqlDao;
+ this.invoicePaymentSqlDao = invoicePaymentSqlDao;
}
@Override
public BusinessAccount getAccountByKey(final String accountKey) {
- return accountSqlDao.getAccount(accountKey);
+ return accountSqlDao.getAccountByKey(accountKey);
}
@Override
public List<BusinessSubscriptionTransition> getTransitionsByKey(final String externalKey) {
- return subscriptionTransitionSqlDao.getTransitions(externalKey);
+ return subscriptionTransitionSqlDao.getTransitionsByKey(externalKey);
}
@Override
public List<BusinessInvoice> getInvoicesByKey(final String accountKey) {
- return invoiceSqlDao.getInvoicesForAccount(accountKey);
+ return invoiceSqlDao.getInvoicesForAccountByKey(accountKey);
}
@Override
public List<BusinessAccountTag> getTagsForAccount(final String accountKey) {
- return accountTagSqlDao.getTagsForAccount(accountKey);
+ return accountTagSqlDao.getTagsForAccountByKey(accountKey);
}
@Override
@@ -76,33 +79,12 @@ public class DefaultAnalyticsDao implements AnalyticsDao {
}
@Override
- public void createInvoice(final String accountKey, final BusinessInvoice invoice, final Iterable<BusinessInvoiceItem> invoiceItems) {
- invoiceSqlDao.inTransaction(new Transaction<Void, BusinessInvoiceSqlDao>() {
- @Override
- public Void inTransaction(final BusinessInvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
- // Create the invoice
- transactional.createInvoice(invoice);
-
- // Add associated invoice items
- final BusinessInvoiceItemSqlDao invoiceItemSqlDao = transactional.become(BusinessInvoiceItemSqlDao.class);
- for (final BusinessInvoiceItem invoiceItem : invoiceItems) {
- invoiceItemSqlDao.createInvoiceItem(invoiceItem);
- }
-
- // Update BAC
- final BusinessAccountSqlDao accountSqlDao = transactional.become(BusinessAccountSqlDao.class);
- final BusinessAccount account = accountSqlDao.getAccount(accountKey);
- if (account == null) {
- throw new IllegalStateException("Account does not exist for key " + accountKey);
- }
- account.setBalance(account.getBalance().add(invoice.getBalance()));
- account.setLastInvoiceDate(invoice.getInvoiceDate());
- account.setTotalInvoiceBalance(account.getTotalInvoiceBalance().add(invoice.getBalance()));
- account.setUpdatedDt(new DateTime(DateTimeZone.UTC));
- accountSqlDao.saveAccount(account);
+ public List<BusinessOverdueStatus> getOverdueStatusesForBundleByKey(final String externalKey) {
+ return overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey);
+ }
- return null;
- }
- });
+ @Override
+ public List<BusinessInvoicePayment> getInvoicePaymentsForAccountByKey(final String accountKey) {
+ return invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(accountKey);
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccount.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccount.java
index b8b056c..642a765 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccount.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccount.java
@@ -17,6 +17,7 @@
package com.ning.billing.analytics.model;
import java.math.BigDecimal;
+import java.util.UUID;
import org.joda.time.DateTime;
@@ -27,6 +28,7 @@ public class BusinessAccount {
private DateTime createdDt = null;
private DateTime updatedDt = null;
+ private final UUID accountId;
private String key;
private String name;
private BigDecimal balance;
@@ -37,10 +39,14 @@ public class BusinessAccount {
private String creditCardType;
private String billingAddressCountry;
- public BusinessAccount() {
+ public BusinessAccount(final UUID accountId) {
+ this.accountId = accountId;
}
- public BusinessAccount(final String key, final String name, final BigDecimal balance, final DateTime lastInvoiceDate, final BigDecimal totalInvoiceBalance, final String lastPaymentStatus, final String paymentMethod, final String creditCardType, final String billingAddressCountry) {
+ public BusinessAccount(final UUID accountId, final String key, final String name, final BigDecimal balance,
+ final DateTime lastInvoiceDate, final BigDecimal totalInvoiceBalance, final String lastPaymentStatus,
+ final String paymentMethod, final String creditCardType, final String billingAddressCountry) {
+ this.accountId = accountId;
this.key = key;
this.balance = balance;
this.billingAddressCountry = billingAddressCountry;
@@ -52,6 +58,10 @@ public class BusinessAccount {
this.totalInvoiceBalance = totalInvoiceBalance;
}
+ public UUID getAccountId() {
+ return accountId;
+ }
+
public String getKey() {
return key;
}
@@ -155,6 +165,7 @@ public class BusinessAccount {
sb.append("{balance=").append(balance);
sb.append(", createdDt=").append(createdDt);
sb.append(", updatedDt=").append(updatedDt);
+ sb.append(", accountId='").append(accountId).append('\'');
sb.append(", key='").append(key).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", lastInvoiceDate=").append(lastInvoiceDate);
@@ -190,6 +201,9 @@ public class BusinessAccount {
if (creditCardType != null ? !creditCardType.equals(that.creditCardType) : that.creditCardType != null) {
return false;
}
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
if (key != null ? !key.equals(that.key) : that.key != null) {
return false;
}
@@ -219,6 +233,7 @@ public class BusinessAccount {
public int hashCode() {
int result = createdDt != null ? createdDt.hashCode() : 0;
result = 31 * result + (updatedDt != null ? updatedDt.hashCode() : 0);
+ result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
result = 31 * result + (key != null ? key.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (balance != null ? balance.hashCode() : 0);
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountField.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountField.java
index b990125..b422838 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountField.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountField.java
@@ -16,14 +16,22 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
public class BusinessAccountField extends BusinessField {
+ private final UUID accountId;
private final String accountKey;
- public BusinessAccountField(final String accountKey, final String name, final String value) {
+ public BusinessAccountField(final UUID accountId, final String accountKey, final String name, final String value) {
super(name, value);
+ this.accountId = accountId;
this.accountKey = accountKey;
}
+ public UUID getAccountId() {
+ return accountId;
+ }
+
public String getAccountKey() {
return accountKey;
}
@@ -32,9 +40,10 @@ public class BusinessAccountField extends BusinessField {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessAccountField");
- sb.append("{accountKey='").append(accountKey).append('\'');
- sb.append(", name='").append(name).append('\'');
- sb.append(", value='").append(value).append('\'');
+ sb.append("{accountId='").append(accountId).append('\'');
+ sb.append(", accountKey='").append(accountKey).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
+ sb.append(", value='").append(getValue()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -50,13 +59,16 @@ public class BusinessAccountField extends BusinessField {
final BusinessAccountField that = (BusinessAccountField) o;
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
- if (value != null ? !value.equals(that.value) : that.value != null) {
+ if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) {
return false;
}
@@ -65,9 +77,10 @@ public class BusinessAccountField extends BusinessField {
@Override
public int hashCode() {
- int result = accountKey != null ? accountKey.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- result = 31 * result + (value != null ? value.hashCode() : 0);
+ int result = accountId != null ? accountId.hashCode() : 0;
+ result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
+ result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountTag.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountTag.java
index 3a8de99..877ab42 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountTag.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessAccountTag.java
@@ -16,14 +16,22 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
public class BusinessAccountTag extends BusinessTag {
+ private final UUID accountId;
private final String accountKey;
- public BusinessAccountTag(final String accountKey, final String name) {
+ public BusinessAccountTag(final UUID accountId, final String accountKey, final String name) {
super(name);
+ this.accountId = accountId;
this.accountKey = accountKey;
}
+ public UUID getAccountId() {
+ return accountId;
+ }
+
public String getAccountKey() {
return accountKey;
}
@@ -32,8 +40,9 @@ public class BusinessAccountTag extends BusinessTag {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessAccountTag");
- sb.append("{accountKey='").append(accountKey).append('\'');
- sb.append(", name='").append(name).append('\'');
+ sb.append("{accountId='").append(accountId).append('\'');
+ sb.append(", accountKey='").append(accountKey).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -49,10 +58,13 @@ public class BusinessAccountTag extends BusinessTag {
final BusinessAccountTag that = (BusinessAccountTag) o;
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
@@ -61,8 +73,9 @@ public class BusinessAccountTag extends BusinessTag {
@Override
public int hashCode() {
- int result = accountKey != null ? accountKey.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
+ int result = accountId != null ? accountId.hashCode() : 0;
+ result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessField.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessField.java
index 68552d0..5d5e727 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessField.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessField.java
@@ -17,8 +17,8 @@
package com.ning.billing.analytics.model;
public abstract class BusinessField {
- protected final String name;
- protected final String value;
+ private final String name;
+ private final String value;
public BusinessField(final String name, final String value) {
this.name = name;
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoice.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoice.java
index 31591c6..caae2a3 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoice.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoice.java
@@ -28,22 +28,24 @@ import com.ning.billing.invoice.api.Invoice;
public class BusinessInvoice {
private final UUID invoiceId;
+ private final Integer invoiceNumber;
private final DateTime createdDate;
-
- private DateTime updatedDate;
- private String accountKey;
- private DateTime invoiceDate;
- private DateTime targetDate;
- private Currency currency;
- private BigDecimal balance;
- private BigDecimal amountPaid;
- private BigDecimal amountCharged;
- private BigDecimal amountCredited;
-
- public BusinessInvoice(final String accountKey, final BigDecimal amountCharged, final BigDecimal amountCredited,
+ private final DateTime updatedDate;
+ private final UUID accountId;
+ private final String accountKey;
+ private final DateTime invoiceDate;
+ private final DateTime targetDate;
+ private final Currency currency;
+ private final BigDecimal balance;
+ private final BigDecimal amountPaid;
+ private final BigDecimal amountCharged;
+ private final BigDecimal amountCredited;
+
+ public BusinessInvoice(final UUID accountId, final String accountKey, final BigDecimal amountCharged, final BigDecimal amountCredited,
final BigDecimal amountPaid, final BigDecimal balance, final DateTime createdDate,
- final Currency currency, final DateTime invoiceDate, final UUID invoiceId,
+ final Currency currency, final DateTime invoiceDate, final UUID invoiceId, final Integer invoiceNumber,
final DateTime targetDate, final DateTime updatedDate) {
+ this.accountId = accountId;
this.accountKey = accountKey;
this.amountCharged = amountCharged;
this.amountCredited = amountCredited;
@@ -53,104 +55,79 @@ public class BusinessInvoice {
this.currency = currency;
this.invoiceDate = invoiceDate;
this.invoiceId = invoiceId;
+ this.invoiceNumber = invoiceNumber;
this.targetDate = targetDate;
this.updatedDate = updatedDate;
}
public BusinessInvoice(final String accountKey, final Invoice invoice) {
- this(accountKey, invoice.getAmountCharged(), invoice.getAmountCredited(), invoice.getAmountPaid(), invoice.getBalance(),
- new DateTime(DateTimeZone.UTC), invoice.getCurrency(), invoice.getInvoiceDate(), invoice.getId(), invoice.getTargetDate(),
+ this(invoice.getAccountId(), accountKey, invoice.getChargedAmount(), invoice.getCreditAdjAmount(), invoice.getPaidAmount(), invoice.getBalance(),
+ new DateTime(DateTimeZone.UTC), invoice.getCurrency(), invoice.getInvoiceDate(), invoice.getId(), invoice.getInvoiceNumber(), invoice.getTargetDate(),
new DateTime(DateTimeZone.UTC));
}
- public DateTime getCreatedDate() {
- return createdDate;
- }
-
- public UUID getInvoiceId() {
- return invoiceId;
+ public UUID getAccountId() {
+ return accountId;
}
public String getAccountKey() {
return accountKey;
}
- public void setAccountKey(final String accountKey) {
- this.accountKey = accountKey;
- }
-
public BigDecimal getAmountCharged() {
return amountCharged;
}
- public void setAmountCharged(final BigDecimal amountCharged) {
- this.amountCharged = amountCharged;
- }
-
public BigDecimal getAmountCredited() {
return amountCredited;
}
- public void setAmountCredited(final BigDecimal amountCredited) {
- this.amountCredited = amountCredited;
- }
-
public BigDecimal getAmountPaid() {
return amountPaid;
}
- public void setAmountPaid(final BigDecimal amountPaid) {
- this.amountPaid = amountPaid;
- }
-
public BigDecimal getBalance() {
return balance;
}
- public void setBalance(final BigDecimal balance) {
- this.balance = balance;
+ public DateTime getCreatedDate() {
+ return createdDate;
}
public Currency getCurrency() {
return currency;
}
- public void setCurrency(final Currency currency) {
- this.currency = currency;
- }
-
public DateTime getInvoiceDate() {
return invoiceDate;
}
- public void setInvoiceDate(final DateTime invoiceDate) {
- this.invoiceDate = invoiceDate;
+ public UUID getInvoiceId() {
+ return invoiceId;
}
- public DateTime getTargetDate() {
- return targetDate;
+ public Integer getInvoiceNumber() {
+ return invoiceNumber;
}
- public void setTargetDate(final DateTime targetDate) {
- this.targetDate = targetDate;
+ public DateTime getTargetDate() {
+ return targetDate;
}
public DateTime getUpdatedDate() {
return updatedDate;
}
- public void setUpdatedDate(final DateTime updatedDate) {
- this.updatedDate = updatedDate;
- }
-
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessInvoice");
- sb.append("{accountKey='").append(accountKey).append('\'');
+ sb.append("{accountId=").append(accountId);
sb.append(", invoiceId=").append(invoiceId);
+ sb.append(", invoiceNumber=").append(invoiceNumber);
sb.append(", createdDate=").append(createdDate);
sb.append(", updatedDate=").append(updatedDate);
+ sb.append(", accountKey='").append(accountKey).append('\'');
sb.append(", invoiceDate=").append(invoiceDate);
sb.append(", targetDate=").append(targetDate);
sb.append(", currency=").append(currency);
@@ -173,6 +150,9 @@ public class BusinessInvoice {
final BusinessInvoice that = (BusinessInvoice) o;
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
return false;
}
@@ -188,22 +168,25 @@ public class BusinessInvoice {
if (balance != null ? Rounder.round(balance) != Rounder.round(that.balance) : that.balance != null) {
return false;
}
- if (createdDate != null ? !createdDate.equals(that.createdDate) : that.createdDate != null) {
+ if (createdDate != null ? createdDate.compareTo(that.createdDate) != 0 : that.createdDate != null) {
return false;
}
if (currency != that.currency) {
return false;
}
- if (invoiceDate != null ? !invoiceDate.equals(that.invoiceDate) : that.invoiceDate != null) {
+ if (invoiceDate != null ? invoiceDate.compareTo(that.invoiceDate) != 0 : that.invoiceDate != null) {
return false;
}
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
- if (targetDate != null ? !targetDate.equals(that.targetDate) : that.targetDate != null) {
+ if (invoiceNumber != null ? !invoiceNumber.equals(that.invoiceNumber) : that.invoiceNumber != null) {
+ return false;
+ }
+ if (targetDate != null ? targetDate.compareTo(that.targetDate) != 0 : that.targetDate != null) {
return false;
}
- if (updatedDate != null ? !updatedDate.equals(that.updatedDate) : that.updatedDate != null) {
+ if (updatedDate != null ? updatedDate.compareTo(that.updatedDate) != 0 : that.updatedDate != null) {
return false;
}
@@ -213,8 +196,10 @@ public class BusinessInvoice {
@Override
public int hashCode() {
int result = invoiceId != null ? invoiceId.hashCode() : 0;
+ result = 31 * result + (invoiceNumber != null ? invoiceNumber.hashCode() : 0);
result = 31 * result + (createdDate != null ? createdDate.hashCode() : 0);
result = 31 * result + (updatedDate != null ? updatedDate.hashCode() : 0);
+ result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
result = 31 * result + (invoiceDate != null ? invoiceDate.hashCode() : 0);
result = 31 * result + (targetDate != null ? targetDate.hashCode() : 0);
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceField.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceField.java
index cf69497..d4597f4 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceField.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceField.java
@@ -35,8 +35,8 @@ public class BusinessInvoiceField extends BusinessField {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessInvoiceField");
sb.append("{invoiceId='").append(invoiceId).append('\'');
- sb.append(", name='").append(name).append('\'');
- sb.append(", value='").append(value).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
+ sb.append(", value='").append(getValue()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -55,10 +55,10 @@ public class BusinessInvoiceField extends BusinessField {
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
- if (value != null ? !value.equals(that.value) : that.value != null) {
+ if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) {
return false;
}
@@ -68,8 +68,8 @@ public class BusinessInvoiceField extends BusinessField {
@Override
public int hashCode() {
int result = invoiceId != null ? invoiceId.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- result = 31 * result + (value != null ? value.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
+ result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceItem.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceItem.java
index 03cb50c..357f4d1 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceItem.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceItem.java
@@ -31,21 +31,20 @@ import com.ning.billing.invoice.api.InvoiceItem;
public class BusinessInvoiceItem {
private final UUID itemId;
private final DateTime createdDate;
-
- private DateTime updatedDate;
- private UUID invoiceId;
- private String itemType;
- private String externalKey;
- private String productName;
- private String productType;
- private String productCategory;
- private String slug;
- private String phase;
- private String billingPeriod;
- private DateTime startDate;
- private DateTime endDate;
- private BigDecimal amount;
- private Currency currency;
+ private final DateTime updatedDate;
+ private final UUID invoiceId;
+ private final String itemType;
+ private final String externalKey;
+ private final String productName;
+ private final String productType;
+ private final String productCategory;
+ private final String slug;
+ private final String phase;
+ private final String billingPeriod;
+ private final DateTime startDate;
+ private final DateTime endDate;
+ private final BigDecimal amount;
+ private final Currency currency;
public BusinessInvoiceItem(final BigDecimal amount, final String billingPeriod, final DateTime createdDate,
final Currency currency, final DateTime endDate, final String externalKey,
@@ -89,114 +88,58 @@ public class BusinessInvoiceItem {
return amount;
}
- public void setAmount(final BigDecimal amount) {
- this.amount = amount;
- }
-
public String getBillingPeriod() {
return billingPeriod;
}
- public void setBillingPeriod(final String billingPeriod) {
- this.billingPeriod = billingPeriod;
- }
-
public Currency getCurrency() {
return currency;
}
- public void setCurrency(final Currency currency) {
- this.currency = currency;
- }
-
public DateTime getEndDate() {
return endDate;
}
- public void setEndDate(final DateTime endDate) {
- this.endDate = endDate;
- }
-
public String getExternalKey() {
return externalKey;
}
- public void setExternalKey(final String externalKey) {
- this.externalKey = externalKey;
- }
-
public UUID getInvoiceId() {
return invoiceId;
}
- public void setInvoiceId(final UUID invoiceId) {
- this.invoiceId = invoiceId;
- }
-
public String getItemType() {
return itemType;
}
- public void setItemType(final String itemType) {
- this.itemType = itemType;
- }
-
public String getPhase() {
return phase;
}
- public void setPhase(final String phase) {
- this.phase = phase;
- }
-
public String getProductCategory() {
return productCategory;
}
- public void setProductCategory(final String productCategory) {
- this.productCategory = productCategory;
- }
-
public String getProductName() {
return productName;
}
- public void setProductName(final String productName) {
- this.productName = productName;
- }
-
public String getProductType() {
return productType;
}
- public void setProductType(final String productType) {
- this.productType = productType;
- }
-
public String getSlug() {
return slug;
}
- public void setSlug(final String slug) {
- this.slug = slug;
- }
-
public DateTime getStartDate() {
return startDate;
}
- public void setStartDate(final DateTime startDate) {
- this.startDate = startDate;
- }
-
public DateTime getUpdatedDate() {
return updatedDate;
}
- public void setUpdatedDate(final DateTime updatedDate) {
- this.updatedDate = updatedDate;
- }
-
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePayment.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePayment.java
index 2622437..73a1f8d 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePayment.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePayment.java
@@ -16,6 +16,7 @@
package com.ning.billing.analytics.model;
+import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.UUID;
@@ -27,32 +28,34 @@ import com.ning.billing.catalog.api.Currency;
public class BusinessInvoicePayment {
private final UUID paymentId;
private final DateTime createdDate;
- private final UUID attemptId;
-
- private DateTime updatedDate;
- private String accountKey;
- private UUID invoiceId;
- private DateTime effectiveDate;
- private BigDecimal amount;
- private Currency currency;
- private String paymentError;
- private String processingStatus;
- private BigDecimal requestedAmount;
- private String pluginName;
- private String paymentType;
- private String paymentMethod;
- private String cardType;
- private String cardCountry;
-
- public BusinessInvoicePayment(final String accountKey, final BigDecimal amount, final UUID attemptId,
+ private final String extPaymentRefId;
+ private final DateTime updatedDate;
+ private final String accountKey;
+ private final UUID invoiceId;
+ private final DateTime effectiveDate;
+ private final BigDecimal amount;
+ private final Currency currency;
+ private final String paymentError;
+ private final String processingStatus;
+ private final BigDecimal requestedAmount;
+ private final String pluginName;
+ private final String paymentType;
+ private final String paymentMethod;
+ private final String cardType;
+ private final String cardCountry;
+ private final String invoicePaymentType;
+ private final UUID linkedInvoicePaymentId;
+
+ public BusinessInvoicePayment(final String accountKey, final BigDecimal amount, final String extPaymentRefId,
final String cardCountry, final String cardType, final DateTime createdDate,
final Currency currency, final DateTime effectiveDate, final UUID invoiceId,
final String paymentError, final UUID paymentId, final String paymentMethod,
final String paymentType, final String pluginName, final String processingStatus,
- final BigDecimal requestedAmount, final DateTime updatedDate) {
+ final BigDecimal requestedAmount, final DateTime updatedDate, @Nullable final String invoicePaymentType,
+ @Nullable final UUID linkedInvoicePaymentId) {
this.accountKey = accountKey;
this.amount = amount;
- this.attemptId = attemptId;
+ this.extPaymentRefId = extPaymentRefId;
this.cardCountry = cardCountry;
this.cardType = cardType;
this.createdDate = createdDate;
@@ -67,10 +70,12 @@ public class BusinessInvoicePayment {
this.processingStatus = processingStatus;
this.requestedAmount = requestedAmount;
this.updatedDate = updatedDate;
+ this.invoicePaymentType = invoicePaymentType;
+ this.linkedInvoicePaymentId = linkedInvoicePaymentId;
}
- public UUID getAttemptId() {
- return attemptId;
+ public String getExtPaymentRefId() {
+ return extPaymentRefId;
}
public DateTime getCreatedDate() {
@@ -85,112 +90,64 @@ public class BusinessInvoicePayment {
return accountKey;
}
- public void setAccountKey(final String accountKey) {
- this.accountKey = accountKey;
- }
-
public BigDecimal getAmount() {
return amount;
}
- public void setAmount(final BigDecimal amount) {
- this.amount = amount;
- }
-
public String getCardCountry() {
return cardCountry;
}
- public void setCardCountry(final String cardCountry) {
- this.cardCountry = cardCountry;
- }
-
public String getCardType() {
return cardType;
}
- public void setCardType(final String cardType) {
- this.cardType = cardType;
- }
-
public Currency getCurrency() {
return currency;
}
- public void setCurrency(final Currency currency) {
- this.currency = currency;
- }
-
public DateTime getEffectiveDate() {
return effectiveDate;
}
- public void setEffectiveDate(final DateTime effectiveDate) {
- this.effectiveDate = effectiveDate;
- }
-
public UUID getInvoiceId() {
return invoiceId;
}
- public void setInvoiceId(final UUID invoiceId) {
- this.invoiceId = invoiceId;
- }
-
public String getPaymentError() {
return paymentError;
}
- public void setPaymentError(final String paymentError) {
- this.paymentError = paymentError;
- }
-
public String getPaymentMethod() {
return paymentMethod;
}
- public void setPaymentMethod(final String paymentMethod) {
- this.paymentMethod = paymentMethod;
- }
-
public String getPaymentType() {
return paymentType;
}
- public void setPaymentType(final String paymentType) {
- this.paymentType = paymentType;
- }
-
public String getPluginName() {
return pluginName;
}
- public void setPluginName(final String pluginName) {
- this.pluginName = pluginName;
- }
-
public String getProcessingStatus() {
return processingStatus;
}
- public void setProcessingStatus(final String processingStatus) {
- this.processingStatus = processingStatus;
- }
-
public BigDecimal getRequestedAmount() {
return requestedAmount;
}
- public void setRequestedAmount(final BigDecimal requestedAmount) {
- this.requestedAmount = requestedAmount;
- }
-
public DateTime getUpdatedDate() {
return updatedDate;
}
- public void setUpdatedDate(final DateTime updatedDate) {
- this.updatedDate = updatedDate;
+ public String getInvoicePaymentType() {
+ return invoicePaymentType;
+ }
+
+ public UUID getLinkedInvoicePaymentId() {
+ return linkedInvoicePaymentId;
}
@Override
@@ -200,7 +157,7 @@ public class BusinessInvoicePayment {
sb.append("{accountKey='").append(accountKey).append('\'');
sb.append(", paymentId=").append(paymentId);
sb.append(", createdDate=").append(createdDate);
- sb.append(", attemptId=").append(attemptId);
+ sb.append(", extPaymentRefId=").append(extPaymentRefId);
sb.append(", updatedDate=").append(updatedDate);
sb.append(", invoiceId=").append(invoiceId);
sb.append(", effectiveDate=").append(effectiveDate);
@@ -214,6 +171,8 @@ public class BusinessInvoicePayment {
sb.append(", paymentMethod='").append(paymentMethod).append('\'');
sb.append(", cardType='").append(cardType).append('\'');
sb.append(", cardCountry='").append(cardCountry).append('\'');
+ sb.append(", invoicePaymentType='").append(invoicePaymentType).append('\'');
+ sb.append(", linkedInvoicePaymentId='").append(linkedInvoicePaymentId).append('\'');
sb.append('}');
return sb.toString();
}
@@ -235,7 +194,7 @@ public class BusinessInvoicePayment {
if (amount != null ? Rounder.round(amount) != Rounder.round(that.amount) : that.amount != null) {
return false;
}
- if (attemptId != null ? !attemptId.equals(that.attemptId) : that.attemptId != null) {
+ if (extPaymentRefId != null ? !extPaymentRefId.equals(that.extPaymentRefId) : that.extPaymentRefId != null) {
return false;
}
if (cardCountry != null ? !cardCountry.equals(that.cardCountry) : that.cardCountry != null) {
@@ -280,6 +239,12 @@ public class BusinessInvoicePayment {
if (updatedDate != null ? !updatedDate.equals(that.updatedDate) : that.updatedDate != null) {
return false;
}
+ if (invoicePaymentType != null ? !invoicePaymentType.equals(that.invoicePaymentType) : that.invoicePaymentType != null) {
+ return false;
+ }
+ if (linkedInvoicePaymentId != null ? !linkedInvoicePaymentId.equals(that.linkedInvoicePaymentId) : that.linkedInvoicePaymentId != null) {
+ return false;
+ }
return true;
}
@@ -288,7 +253,7 @@ public class BusinessInvoicePayment {
public int hashCode() {
int result = paymentId != null ? paymentId.hashCode() : 0;
result = 31 * result + (createdDate != null ? createdDate.hashCode() : 0);
- result = 31 * result + (attemptId != null ? attemptId.hashCode() : 0);
+ result = 31 * result + (extPaymentRefId != null ? extPaymentRefId.hashCode() : 0);
result = 31 * result + (updatedDate != null ? updatedDate.hashCode() : 0);
result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentField.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentField.java
index bcfc85b..c79b2b1 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentField.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentField.java
@@ -35,8 +35,8 @@ public class BusinessInvoicePaymentField extends BusinessField {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessPaymentField");
sb.append("{paymentId='").append(paymentId).append('\'');
- sb.append(", name='").append(name).append('\'');
- sb.append(", value='").append(value).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
+ sb.append(", value='").append(getValue()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -55,10 +55,10 @@ public class BusinessInvoicePaymentField extends BusinessField {
if (paymentId != null ? !paymentId.equals(that.paymentId) : that.paymentId != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
- if (value != null ? !value.equals(that.value) : that.value != null) {
+ if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) {
return false;
}
@@ -68,8 +68,8 @@ public class BusinessInvoicePaymentField extends BusinessField {
@Override
public int hashCode() {
int result = paymentId != null ? paymentId.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- result = 31 * result + (value != null ? value.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
+ result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentTag.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentTag.java
index fd48b1c..e1cbbd5 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentTag.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoicePaymentTag.java
@@ -35,7 +35,7 @@ public class BusinessInvoicePaymentTag extends BusinessTag {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessPaymentTag");
sb.append("{paymentId='").append(paymentId).append('\'');
- sb.append(", name='").append(name).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -54,7 +54,7 @@ public class BusinessInvoicePaymentTag extends BusinessTag {
if (paymentId != null ? !paymentId.equals(that.paymentId) : that.paymentId != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
@@ -64,7 +64,7 @@ public class BusinessInvoicePaymentTag extends BusinessTag {
@Override
public int hashCode() {
int result = paymentId != null ? paymentId.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceTag.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceTag.java
index e9efe5a..41b7d27 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceTag.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessInvoiceTag.java
@@ -35,7 +35,7 @@ public class BusinessInvoiceTag extends BusinessTag {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessInvoiceTag");
sb.append("{paymentId='").append(invoiceId).append('\'');
- sb.append(", name='").append(name).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -54,7 +54,7 @@ public class BusinessInvoiceTag extends BusinessTag {
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
@@ -64,7 +64,7 @@ public class BusinessInvoiceTag extends BusinessTag {
@Override
public int hashCode() {
int result = invoiceId != null ? invoiceId.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessOverdueStatus.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessOverdueStatus.java
index dd8a310..bd74d14 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessOverdueStatus.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessOverdueStatus.java
@@ -16,21 +16,36 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
import org.joda.time.DateTime;
public class BusinessOverdueStatus {
+ private final String accountKey;
+ private final UUID bundleId;
private final String externalKey;
private final String status;
private final DateTime startDate;
private final DateTime endDate;
- public BusinessOverdueStatus(final DateTime endDate, final String externalKey, final DateTime startDate, final String status) {
+ public BusinessOverdueStatus(final String accountKey, final UUID bundleId, final DateTime endDate,
+ final String externalKey, final DateTime startDate, final String status) {
+ this.accountKey = accountKey;
+ this.bundleId = bundleId;
this.endDate = endDate;
this.externalKey = externalKey;
this.startDate = startDate;
this.status = status;
}
+ public String getAccountKey() {
+ return accountKey;
+ }
+
+ public UUID getBundleId() {
+ return bundleId;
+ }
+
public DateTime getEndDate() {
return endDate;
}
@@ -51,7 +66,9 @@ public class BusinessOverdueStatus {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessOverdueStatus");
- sb.append("{endDate=").append(endDate);
+ sb.append("{accountKey=").append(accountKey);
+ sb.append(", bundleId='").append(bundleId).append('\'');
+ sb.append(", endDate='").append(endDate).append('\'');
sb.append(", externalKey='").append(externalKey).append('\'');
sb.append(", status='").append(status).append('\'');
sb.append(", startDate=").append(startDate);
@@ -70,6 +87,12 @@ public class BusinessOverdueStatus {
final BusinessOverdueStatus that = (BusinessOverdueStatus) o;
+ if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
+ return false;
+ }
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
+ return false;
+ }
if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) {
return false;
}
@@ -88,7 +111,9 @@ public class BusinessOverdueStatus {
@Override
public int hashCode() {
- int result = externalKey != null ? externalKey.hashCode() : 0;
+ int result = accountKey != null ? accountKey.hashCode() : 0;
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (externalKey != null ? externalKey.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
result = 31 * result + (endDate != null ? endDate.hashCode() : 0);
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscription.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscription.java
index 35d5ea1..86b6244 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscription.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscription.java
@@ -18,7 +18,6 @@ package com.ning.billing.analytics.model;
import java.math.BigDecimal;
import java.math.RoundingMode;
-import java.util.UUID;
import org.joda.time.DateTime;
import org.slf4j.Logger;
@@ -60,10 +59,10 @@ public class BusinessSubscription {
private final String currency;
private final DateTime startDate;
private final SubscriptionState state;
- private final UUID subscriptionId;
- private final UUID bundleId;
- public BusinessSubscription(final String productName, final String productType, final ProductCategory productCategory, final String slug, final String phase, final String billingPeriod, final BigDecimal price, final String priceList, final BigDecimal mrr, final String currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId) {
+ public BusinessSubscription(final String productName, final String productType, final ProductCategory productCategory,
+ final String slug, final String phase, final String billingPeriod, final BigDecimal price,
+ final String priceList, final BigDecimal mrr, final String currency, final DateTime startDate, final SubscriptionState state) {
this.productName = productName;
this.productType = productType;
this.productCategory = productCategory;
@@ -76,8 +75,6 @@ public class BusinessSubscription {
this.currency = currency;
this.startDate = startDate;
this.state = state;
- this.subscriptionId = subscriptionId;
- this.bundleId = bundleId;
}
/**
@@ -91,10 +88,13 @@ public class BusinessSubscription {
* @param catalog Catalog to use
*/
BusinessSubscription(final Subscription subscription, final Currency currency, final Catalog catalog) {
- this(subscription.getCurrentPriceList() == null ? null : subscription.getCurrentPriceList().getName(), subscription.getCurrentPlan().getName(), subscription.getCurrentPhase().getName(), currency, subscription.getStartDate(), subscription.getState(), subscription.getId(), subscription.getBundleId(), catalog);
+ this(subscription.getCurrentPriceList() == null ? null : subscription.getCurrentPriceList().getName(),
+ subscription.getCurrentPlan().getName(), subscription.getCurrentPhase().getName(), currency,
+ subscription.getStartDate(), subscription.getState(), catalog);
}
- public BusinessSubscription(final String priceList, final String currentPlan, final String currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId, final Catalog catalog) {
+ public BusinessSubscription(final String priceList, final String currentPlan, final String currentPhase, final Currency currency,
+ final DateTime startDate, final SubscriptionState state, final Catalog catalog) {
Plan thePlan = null;
PlanPhase thePhase = null;
try {
@@ -165,11 +165,10 @@ public class BusinessSubscription {
this.startDate = startDate;
this.state = state;
- this.subscriptionId = subscriptionId;
- this.bundleId = bundleId;
}
- public BusinessSubscription(final String priceList, final Plan currentPlan, final PlanPhase currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId) {
+ public BusinessSubscription(final String priceList, final Plan currentPlan, final PlanPhase currentPhase, final Currency currency,
+ final DateTime startDate, final SubscriptionState state) {
this.priceList = priceList;
// Record plan information
@@ -231,18 +230,12 @@ public class BusinessSubscription {
this.startDate = startDate;
this.state = state;
- this.subscriptionId = subscriptionId;
- this.bundleId = bundleId;
}
public String getBillingPeriod() {
return billingPeriod;
}
- public UUID getBundleId() {
- return bundleId;
- }
-
public String getCurrency() {
return currency;
}
@@ -295,10 +288,6 @@ public class BusinessSubscription {
return state;
}
- public UUID getSubscriptionId() {
- return subscriptionId;
- }
-
static BigDecimal getMrrFromISubscription(final Duration duration, final BigDecimal price) {
if (duration == null || duration.getUnit() == null || duration.getNumber() == 0) {
return BigDecimal.ZERO;
@@ -334,8 +323,6 @@ public class BusinessSubscription {
sb.append(", currency='").append(currency).append('\'');
sb.append(", startDate=").append(startDate);
sb.append(", state=").append(state);
- sb.append(", subscriptionId=").append(subscriptionId);
- sb.append(", bundleId=").append(bundleId);
sb.append('}');
return sb.toString();
}
@@ -354,9 +341,6 @@ public class BusinessSubscription {
if (billingPeriod != null ? !billingPeriod.equals(that.billingPeriod) : that.billingPeriod != null) {
return false;
}
- if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
- return false;
- }
if (currency != null ? !currency.equals(that.currency) : that.currency != null) {
return false;
}
@@ -390,9 +374,6 @@ public class BusinessSubscription {
if (state != that.state) {
return false;
}
- if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
- return false;
- }
return true;
}
@@ -410,8 +391,6 @@ public class BusinessSubscription {
result = 31 * result + (currency != null ? currency.hashCode() : 0);
result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
result = 31 * result + (state != null ? state.hashCode() : 0);
- result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
- result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
result = 31 * result + (billingPeriod != null ? billingPeriod.hashCode() : 0);
return result;
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransition.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransition.java
index 3618b7d..806b226 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransition.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransition.java
@@ -16,42 +16,60 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
import org.joda.time.DateTime;
/**
* Describe a state change between two BusinessSubscription
- * <p/>
- * The key is unique identifier that ties sets of subscriptions together.
*/
public class BusinessSubscriptionTransition {
private final long totalOrdering;
+ private final UUID bundleId;
private final String externalKey;
+ private final UUID accountId;
private final String accountKey;
+ private final UUID subscriptionId;
private final DateTime requestedTimestamp;
private final BusinessSubscriptionEvent event;
private final BusinessSubscription previousSubscription;
private final BusinessSubscription nextSubscription;
- public BusinessSubscriptionTransition(final Long totalOrdering, final String externalKey, final String accountKey, final DateTime requestedTimestamp, final BusinessSubscriptionEvent event, final BusinessSubscription previousSubscription, final BusinessSubscription nextSubscription) {
+ public BusinessSubscriptionTransition(final Long totalOrdering, final UUID bundleId, final String externalKey,
+ final UUID accountId, final String accountKey, final UUID subscriptionId,
+ final DateTime requestedTimestamp, final BusinessSubscriptionEvent event,
+ final BusinessSubscription previousSubscription, final BusinessSubscription nextSubscription) {
if (totalOrdering == null) {
- throw new IllegalArgumentException("An event must have a total ordering");
+ throw new IllegalArgumentException("A transition must have a total ordering");
+ }
+ if (bundleId == null) {
+ throw new IllegalArgumentException("A transition must have a bundle id");
}
if (externalKey == null) {
- throw new IllegalArgumentException("An event must have an external key");
+ throw new IllegalArgumentException("A transition must have an external key");
+ }
+ if (accountId == null) {
+ throw new IllegalArgumentException("A transition must have an account key");
+ }
+ if (subscriptionId == null) {
+ throw new IllegalArgumentException("A transition must have a subscription id");
}
if (accountKey == null) {
- throw new IllegalArgumentException("An event must have an account key");
+ throw new IllegalArgumentException("A transition must have an account key");
}
if (requestedTimestamp == null) {
- throw new IllegalArgumentException("An event must have a requestedTimestamp");
+ throw new IllegalArgumentException("A transition must have a requested timestamp");
}
if (event == null) {
throw new IllegalArgumentException("No event specified");
}
this.totalOrdering = totalOrdering;
+ this.bundleId = bundleId;
this.externalKey = externalKey;
+ this.accountId = accountId;
this.accountKey = accountKey;
+ this.subscriptionId = subscriptionId;
this.requestedTimestamp = requestedTimestamp;
this.event = event;
this.previousSubscription = previousSubscription;
@@ -66,10 +84,18 @@ public class BusinessSubscriptionTransition {
return event;
}
+ public UUID getBundleId() {
+ return bundleId;
+ }
+
public String getExternalKey() {
return externalKey;
}
+ public UUID getAccountId() {
+ return accountId;
+ }
+
public String getAccountKey() {
return accountKey;
}
@@ -82,6 +108,10 @@ public class BusinessSubscriptionTransition {
return previousSubscription;
}
+ public UUID getSubscriptionId() {
+ return subscriptionId;
+ }
+
public DateTime getRequestedTimestamp() {
return requestedTimestamp;
}
@@ -90,9 +120,12 @@ public class BusinessSubscriptionTransition {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessSubscriptionTransition");
- sb.append("{accountKey='").append(accountKey).append('\'');
+ sb.append("{accountId='").append(accountId).append('\'');
+ sb.append(", accountKey=").append(accountKey);
sb.append(", totalOrdering=").append(totalOrdering);
- sb.append(", key='").append(externalKey).append('\'');
+ sb.append(", bundleId='").append(bundleId).append('\'');
+ sb.append(", externalKey='").append(externalKey).append('\'');
+ sb.append(", subscriptionId='").append(subscriptionId).append('\'');
sb.append(", requestedTimestamp=").append(requestedTimestamp);
sb.append(", event=").append(event);
sb.append(", previousSubscription=").append(previousSubscription);
@@ -112,13 +145,35 @@ public class BusinessSubscriptionTransition {
final BusinessSubscriptionTransition that = (BusinessSubscriptionTransition) o;
+ return totalOrdering == that.totalOrdering && isDuplicateOf(that);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = (int) (totalOrdering ^ (totalOrdering >>> 32));
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (externalKey != null ? externalKey.hashCode() : 0);
+ result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
+ result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
+ result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
+ result = 31 * result + (requestedTimestamp != null ? requestedTimestamp.hashCode() : 0);
+ result = 31 * result + (event != null ? event.hashCode() : 0);
+ result = 31 * result + (previousSubscription != null ? previousSubscription.hashCode() : 0);
+ result = 31 * result + (nextSubscription != null ? nextSubscription.hashCode() : 0);
+ return result;
+ }
+
+ public boolean isDuplicateOf(final BusinessSubscriptionTransition that) {
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
return false;
}
if (event != null ? !event.equals(that.event) : that.event != null) {
return false;
}
- if (totalOrdering != that.totalOrdering) {
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
return false;
}
if (externalKey != null ? !externalKey.equals(that.externalKey) : that.externalKey != null) {
@@ -130,22 +185,13 @@ public class BusinessSubscriptionTransition {
if (previousSubscription != null ? !previousSubscription.equals(that.previousSubscription) : that.previousSubscription != null) {
return false;
}
+ if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
+ return false;
+ }
if (requestedTimestamp != null ? !requestedTimestamp.equals(that.requestedTimestamp) : that.requestedTimestamp != null) {
return false;
}
return true;
}
-
- @Override
- public int hashCode() {
- int result = (int) (totalOrdering ^ (totalOrdering >>> 32));
- result = 31 * result + (externalKey != null ? externalKey.hashCode() : 0);
- result = 31 * result + (accountKey != null ? accountKey.hashCode() : 0);
- result = 31 * result + (requestedTimestamp != null ? requestedTimestamp.hashCode() : 0);
- result = 31 * result + (event != null ? event.hashCode() : 0);
- result = 31 * result + (previousSubscription != null ? previousSubscription.hashCode() : 0);
- result = 31 * result + (nextSubscription != null ? nextSubscription.hashCode() : 0);
- return result;
- }
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionField.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionField.java
index bab1259..d570c68 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionField.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionField.java
@@ -16,14 +16,29 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
public class BusinessSubscriptionTransitionField extends BusinessField {
+ private final String accountKey;
+ private final UUID bundleId;
private final String externalKey;
- public BusinessSubscriptionTransitionField(final String externalKey, final String name, final String value) {
+ public BusinessSubscriptionTransitionField(final String accountKey, final UUID bundleId, final String externalKey,
+ final String name, final String value) {
super(name, value);
+ this.accountKey = accountKey;
+ this.bundleId = bundleId;
this.externalKey = externalKey;
}
+ public String getAccountKey() {
+ return accountKey;
+ }
+
+ public UUID getBundleId() {
+ return bundleId;
+ }
+
public String getExternalKey() {
return externalKey;
}
@@ -32,9 +47,11 @@ public class BusinessSubscriptionTransitionField extends BusinessField {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessSubscriptionTransitionField");
- sb.append("{externalKey='").append(externalKey).append('\'');
- sb.append(", name='").append(name).append('\'');
- sb.append(", value='").append(value).append('\'');
+ sb.append("{accountKey='").append(accountKey).append('\'');
+ sb.append(", bundleId='").append(bundleId).append('\'');
+ sb.append(", externalKey='").append(externalKey).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
+ sb.append(", value='").append(getValue()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -50,13 +67,19 @@ public class BusinessSubscriptionTransitionField extends BusinessField {
final BusinessSubscriptionTransitionField that = (BusinessSubscriptionTransitionField) o;
+ if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
+ return false;
+ }
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
+ return false;
+ }
if (externalKey != null ? !externalKey.equals(that.externalKey) : that.externalKey != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
- if (value != null ? !value.equals(that.value) : that.value != null) {
+ if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) {
return false;
}
@@ -65,9 +88,11 @@ public class BusinessSubscriptionTransitionField extends BusinessField {
@Override
public int hashCode() {
- int result = externalKey != null ? externalKey.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- result = 31 * result + (value != null ? value.hashCode() : 0);
+ int result = accountKey != null ? accountKey.hashCode() : 0;
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (externalKey != null ? externalKey.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
+ result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionTag.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionTag.java
index 522194a..e2b6e33 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionTag.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessSubscriptionTransitionTag.java
@@ -16,14 +16,28 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
public class BusinessSubscriptionTransitionTag extends BusinessTag {
+ private final String accountKey;
+ private final UUID bundleId;
private final String externalKey;
- public BusinessSubscriptionTransitionTag(final String externalKey, final String name) {
+ public BusinessSubscriptionTransitionTag(final String accountKey, final UUID bundleId, final String externalKey, final String name) {
super(name);
+ this.accountKey = accountKey;
+ this.bundleId = bundleId;
this.externalKey = externalKey;
}
+ public String getAccountKey() {
+ return accountKey;
+ }
+
+ public UUID getBundleId() {
+ return bundleId;
+ }
+
public String getExternalKey() {
return externalKey;
}
@@ -32,8 +46,10 @@ public class BusinessSubscriptionTransitionTag extends BusinessTag {
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BusinessSubscriptionTransitionTag");
- sb.append("{externalKey='").append(externalKey).append('\'');
- sb.append(", name='").append(name).append('\'');
+ sb.append("{accountKey='").append(accountKey).append('\'');
+ sb.append(", bundleId='").append(bundleId).append('\'');
+ sb.append(", externalKey='").append(externalKey).append('\'');
+ sb.append(", name='").append(getName()).append('\'');
sb.append('}');
return sb.toString();
}
@@ -49,10 +65,16 @@ public class BusinessSubscriptionTransitionTag extends BusinessTag {
final BusinessSubscriptionTransitionTag that = (BusinessSubscriptionTransitionTag) o;
+ if (accountKey != null ? !accountKey.equals(that.accountKey) : that.accountKey != null) {
+ return false;
+ }
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
+ return false;
+ }
if (externalKey != null ? !externalKey.equals(that.externalKey) : that.externalKey != null) {
return false;
}
- if (name != null ? !name.equals(that.name) : that.name != null) {
+ if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) {
return false;
}
@@ -61,8 +83,10 @@ public class BusinessSubscriptionTransitionTag extends BusinessTag {
@Override
public int hashCode() {
- int result = externalKey != null ? externalKey.hashCode() : 0;
- result = 31 * result + (name != null ? name.hashCode() : 0);
+ int result = accountKey != null ? accountKey.hashCode() : 0;
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (externalKey != null ? externalKey.hashCode() : 0);
+ result = 31 * result + (getName() != null ? getName().hashCode() : 0);
return result;
}
}
diff --git a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessTag.java b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessTag.java
index 80343e1..64ddaa9 100644
--- a/analytics/src/main/java/com/ning/billing/analytics/model/BusinessTag.java
+++ b/analytics/src/main/java/com/ning/billing/analytics/model/BusinessTag.java
@@ -17,7 +17,7 @@
package com.ning.billing.analytics.model;
public abstract class BusinessTag {
- protected final String name;
+ private final String name;
public BusinessTag(final String name) {
this.name = name;
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.sql.stg
index 8bb9e0b..2fd6b5c 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountFieldSqlDao.sql.stg
@@ -1,8 +1,9 @@
group BusinessAccountField;
-getFieldsForAccount(account_key) ::=<<
+getFieldsForAccountByKey(account_key) ::=<<
select
- account_key
+ account_id
+, account_key
, name
, value
from bac_fields
@@ -10,22 +11,24 @@ where account_key = :account_key
;
>>
-addField(account_key, name, value) ::=<<
+addField(account_id, account_key, name, value) ::=<<
insert into bac_fields (
- account_key
+ account_id
+, account_key
, name
, value
) values (
- :account_key
+ :account_id
+, :account_key
, :name
, :value
);
>>
-removeField(account_key, name) ::= <<
-delete from bac_fields where account_key = :account_key and name = :name;
+removeField(account_id, name) ::= <<
+delete from bac_fields where account_id = :account_id and name = :name;
>>
test() ::= <<
select 1 from bac_fields;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountSqlDao.sql.stg
index e4cfa8d..66052ec 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountSqlDao.sql.stg
@@ -1,8 +1,29 @@
group BusinessAccount;
-getAccount(account_key) ::= <<
+getAccount(account_id) ::= <<
select
- account_key
+ account_id
+ , account_key
+ , created_date
+ , updated_date
+ , balance
+ , name
+ , last_invoice_date
+ , total_invoice_balance
+ , last_payment_status
+ , payment_method
+ , credit_card_type
+ , billing_address_country
+ from bac
+ where account_id=:account_id
+ limit 1
+ ;
+>>
+
+getAccountByKey(account_key) ::= <<
+ select
+ account_id
+ , account_key
, created_date
, updated_date
, balance
@@ -21,7 +42,8 @@ getAccount(account_key) ::= <<
createAccount() ::= <<
insert into bac(
- account_key
+ account_id
+ , account_key
, created_date
, updated_date
, balance
@@ -33,7 +55,8 @@ createAccount() ::= <<
, credit_card_type
, billing_address_country
) values (
- :account_key
+ :account_id
+ , :account_key
, :created_date
, :updated_date
, :balance
@@ -58,7 +81,7 @@ saveAccount() ::= <<
, payment_method=:payment_method
, credit_card_type=:credit_card_type
, billing_address_country=:billing_address_country
- where account_key=:account_key
+ where account_id=:account_id
;
>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.sql.stg
index af34473..5c9a954 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessAccountTagSqlDao.sql.stg
@@ -1,28 +1,31 @@
group BusinessAccountTag;
-getTagsForAccount(account_key) ::=<<
+getTagsForAccountByKey(account_key) ::=<<
select
- account_key
+ account_id
+, account_key
, name
from bac_tags
where account_key = :account_key
;
>>
-addTag(account_key, name) ::=<<
+addTag(account_id, account_key, name) ::=<<
insert into bac_tags (
- account_key
+ account_id
+, account_key
, name
) values (
- :account_key
+ :account_id
+, :account_key
, :name
);
>>
-removeTag(account_key, name) ::= <<
-delete from bac_tags where account_key = :account_key and name = :name;
+removeTag(account_id, name) ::= <<
+delete from bac_tags where account_id = :account_id and name = :name;
>>
test() ::= <<
select 1 from bac_tags;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.sql.stg
index 7952eb6..2d55e1f 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceItemSqlDao.sql.stg
@@ -48,7 +48,7 @@ order by created_date asc
;
>>
-getInvoiceItemsForBundle(external_key) ::= <<
+getInvoiceItemsForBundleByKey(external_key) ::= <<
select
item_id
, created_date
@@ -110,30 +110,10 @@ insert into bii (
);
>>
-updateInvoiceItem() ::= <<
-update bii set
- updated_date = :updated_date
-, invoice_id = :invoice_id
-, item_type = :item_type
-, external_key = :external_key
-, product_name = :product_name
-, product_type = :product_type
-, product_category = :product_category
-, slug = :slug
-, phase = :phase
-, billing_period = :billing_period
-, start_date = :start_date
-, end_date = :end_date
-, amount = :amount
-, currency = :currency
-where item_id = :item_id
-;
->>
-
deleteInvoiceItem(item_id) ::= <<
delete from bii where item_id = :item_id;
>>
test() ::= <<
select 1 from bii;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.sql.stg
index c5d0fb8..a71f3d5 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoicePaymentSqlDao.sql.stg
@@ -1,36 +1,11 @@
group BusinessInvoicePayment;
-getInvoicePaymentForPaymentAttempt(attempt_id) ::= <<
+getInvoicePayment(payment_id) ::= <<
select
payment_id
, created_date
, updated_date
-, attempt_id
-, account_key
-, invoice_id
-, effective_date
-, amount
-, currency
-, payment_error
-, processing_status
-, requested_amount
-, plugin_name
-, payment_type
-, payment_method
-, card_type
-, card_country
-from bip
-where attempt_id = :attempt_id
-limit 1
-;
->>
-
-getInvoicePaymentsForPayment(payment_id) ::= <<
-select
- payment_id
-, created_date
-, updated_date
-, attempt_id
+, ext_payment_ref_id
, account_key
, invoice_id
, effective_date
@@ -44,18 +19,20 @@ select
, payment_method
, card_type
, card_country
+, invoice_payment_type
+, linked_invoice_payment_id
from bip
where payment_id = :payment_id
-order by created_date asc
+limit 1
;
>>
-getInvoicePaymentsForAccount(account_key) ::= <<
+getInvoicePaymentsForAccountByKey(account_key) ::= <<
select
payment_id
, created_date
, updated_date
-, attempt_id
+, ext_payment_ref_id
, account_key
, invoice_id
, effective_date
@@ -69,6 +46,8 @@ select
, payment_method
, card_type
, card_country
+, invoice_payment_type
+, linked_invoice_payment_id
from bip
where account_key = :account_key
order by created_date asc
@@ -80,7 +59,7 @@ insert into bip (
payment_id
, created_date
, updated_date
-, attempt_id
+, ext_payment_ref_id
, account_key
, invoice_id
, effective_date
@@ -94,11 +73,13 @@ insert into bip (
, payment_method
, card_type
, card_country
+, invoice_payment_type
+, linked_invoice_payment_id
) values (
:payment_id
, :created_date
, :updated_date
-, :attempt_id
+, :ext_payment_ref_id
, :account_key
, :invoice_id
, :effective_date
@@ -112,33 +93,15 @@ insert into bip (
, :payment_method
, :card_type
, :card_country
+, :invoice_payment_type
+, :linked_invoice_payment_id
);
>>
-updateInvoicePaymentForPaymentAttempt() ::= <<
-update bip set
- updated_date = :updated_date
-, account_key = :account_key
-, invoice_id = :invoice_id
-, effective_date = :effective_date
-, amount = :amount
-, currency = :currency
-, payment_error = :payment_error
-, processing_status = :processing_status
-, requested_amount = :requested_amount
-, plugin_name = :plugin_name
-, payment_type = :payment_type
-, payment_method = :payment_method
-, card_type = :card_type
-, card_country = :card_country
-where attempt_id = :attempt_id
-;
->>
-
-deleteInvoicePaymentForPaymentAttempt(attempt_id) ::= <<
-delete from bip where attempt_id = :attempt_id
+deleteInvoicePayment(payment_id) ::= <<
+delete from bip where payment_id = :payment_id
>>
test() ::= <<
select 1 from bip;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.sql.stg
index 83d3ffc..fed7d20 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessInvoiceSqlDao.sql.stg
@@ -3,8 +3,10 @@ group BusinessInvoice;
getInvoice(invoice_id) ::= <<
select
invoice_id
+, invoice_number
, created_date
, updated_date
+, account_id
, account_key
, invoice_date
, target_date
@@ -19,11 +21,34 @@ limit 1
;
>>
-getInvoicesForAccount(account_key) ::= <<
+getInvoicesForAccount(account_id) ::= <<
select
invoice_id
+, invoice_number
, created_date
, updated_date
+, account_id
+, account_key
+, invoice_date
+, target_date
+, currency
+, balance
+, amount_paid
+, amount_charged
+, amount_credited
+from bin
+where account_id = :account_id
+order by created_date asc
+;
+>>
+
+getInvoicesForAccountByKey(account_key) ::= <<
+select
+ invoice_id
+, invoice_number
+, created_date
+, updated_date
+, account_id
, account_key
, invoice_date
, target_date
@@ -41,8 +66,10 @@ order by created_date asc
createInvoice() ::= <<
insert into bin (
invoice_id
+, invoice_number
, created_date
, updated_date
+, account_id
, account_key
, invoice_date
, target_date
@@ -53,8 +80,10 @@ insert into bin (
, amount_credited
) values (
:invoice_id
+, :invoice_number
, :created_date
, :updated_date
+, :account_id
, :account_key
, :invoice_date
, :target_date
@@ -69,6 +98,7 @@ insert into bin (
updateInvoice() ::= <<
update bin set
updated_date = :updated_date
+, invoice_number = :invoice_number
, account_key = :account_key
, invoice_date = :invoice_date
, target_date = :target_date
@@ -85,6 +115,10 @@ deleteInvoice(invoice_id) ::= <<
delete from bin where invoice_id = :invoice_id;
>>
+deleteInvoicesForAccount(account_id) ::= <<
+delete from bin where account_id = :account_id;
+>>
+
test() ::= <<
select 1 from bin;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.sql.stg
index d412125..532a39b 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessOverdueStatusSqlDao.sql.stg
@@ -1,8 +1,10 @@
group BusinessOverdueStatus;
-getOverdueStatusesForBundle(external_key) ::= <<
+getOverdueStatusesForBundleByKey(external_key) ::= <<
select
- external_key
+ bundle_id
+, external_key
+, account_key
, status
, start_date
, end_date
@@ -14,18 +16,26 @@ order by start_date asc
createOverdueStatus() ::= <<
insert into bos (
- external_key
+ bundle_id
+, external_key
+, account_key
, status
, start_date
, end_date
) values (
- :external_key
+ :bundle_id
+, :external_key
+, :account_key
, :status
, :start_date
, :end_date
);
>>
+deleteOverdueStatusesForBundle(bundle_id) ::= <<
+delete from bos where bundle_id = :bundle_id;
+>>
+
test() ::= <<
select 1 from bos;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.sql.stg
index 522e6d7..8480e3f 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionFieldSqlDao.sql.stg
@@ -1,8 +1,10 @@
group BusinessSubscriptionTransitionField;
-getFieldsForBusinessSubscriptionTransition(external_key) ::=<<
+getFieldsForBusinessSubscriptionTransitionByKey(external_key) ::=<<
select
- external_key
+ bundle_id
+, external_key
+, account_key
, name
, value
from bst_fields
@@ -10,22 +12,26 @@ where external_key = :external_key
;
>>
-addField(external_key, name, value) ::=<<
+addField(bundle_id, external_key, name, value) ::=<<
insert into bst_fields (
- external_key
+ bundle_id
+, external_key
+, account_key
, name
, value
) values (
- :external_key
+ :bundle_id
+, :external_key
+, :account_key
, :name
, :value
);
>>
-removeField(external_key, name) ::= <<
-delete from bst_fields where external_key = :external_key and name = :name;
+removeField(bundle_id, name) ::= <<
+delete from bst_fields where bundle_id = :bundle_id and name = :name;
>>
test() ::= <<
select 1 from bst_fields;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.sql.stg
index c80b6b5..6bda4e4 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionSqlDao.sql.stg
@@ -1,10 +1,13 @@
group BusinessSubscriptionTransition;
-getTransitions(external_key) ::= <<
+getTransitionsByKey(external_key) ::= <<
select
total_ordering
+ , bundle_id
, external_key
+ , account_id
, account_key
+ , subscription_id
, requested_timestamp
, event
, prev_product_name
@@ -19,8 +22,6 @@ getTransitions(external_key) ::= <<
, prev_currency
, prev_start_date
, prev_state
- , prev_subscription_id
- , prev_bundle_id
, next_product_name
, next_product_type
, next_product_category
@@ -33,19 +34,60 @@ getTransitions(external_key) ::= <<
, next_currency
, next_start_date
, next_state
- , next_subscription_id
- , next_bundle_id
from bst
where external_key=:external_key
order by requested_timestamp asc
;
>>
+getTransitionForSubscription(subscription_id) ::= <<
+ select
+ total_ordering
+ , bundle_id
+ , external_key
+ , account_id
+ , account_key
+ , subscription_id
+ , requested_timestamp
+ , event
+ , prev_product_name
+ , prev_product_type
+ , prev_product_category
+ , prev_slug
+ , prev_phase
+ , prev_billing_period
+ , prev_price
+ , prev_price_list
+ , prev_mrr
+ , prev_currency
+ , prev_start_date
+ , prev_state
+ , next_product_name
+ , next_product_type
+ , next_product_category
+ , next_slug
+ , next_phase
+ , next_billing_period
+ , next_price
+ , next_price_list
+ , next_mrr
+ , next_currency
+ , next_start_date
+ , next_state
+ from bst
+ where subscription_id = :subscription_id
+ order by requested_timestamp asc
+ ;
+>>
+
createTransition() ::= <<
- insert ignore into bst(
+ insert into bst(
total_ordering
+ , bundle_id
, external_key
+ , account_id
, account_key
+ , subscription_id
, requested_timestamp
, event
, prev_product_name
@@ -60,8 +102,6 @@ createTransition() ::= <<
, prev_currency
, prev_start_date
, prev_state
- , prev_subscription_id
- , prev_bundle_id
, next_product_name
, next_product_type
, next_product_category
@@ -74,12 +114,13 @@ createTransition() ::= <<
, next_currency
, next_start_date
, next_state
- , next_subscription_id
- , next_bundle_id
) values (
:total_ordering
+ , :bundle_id
, :external_key
+ , :account_id
, :account_key
+ , :subscription_id
, :requested_timestamp
, :event
, :prev_product_name
@@ -94,8 +135,6 @@ createTransition() ::= <<
, :prev_currency
, :prev_start_date
, :prev_state
- , :prev_subscription_id
- , :prev_bundle_id
, :next_product_name
, :next_product_type
, :next_product_category
@@ -108,11 +147,15 @@ createTransition() ::= <<
, :next_currency
, :next_start_date
, :next_state
- , :next_subscription_id
- , :next_bundle_id
);
>>
+deleteTransitionsForBundle(bundle_id) ::= <<
+ delete from bst
+ where bundle_id=:bundle_id
+ ;
+>>
+
test() ::= <<
select 1 from bst;
>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.sql.stg b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.sql.stg
index 3d2255f..2eb6f37 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.sql.stg
+++ b/analytics/src/main/resources/com/ning/billing/analytics/dao/BusinessSubscriptionTransitionTagSqlDao.sql.stg
@@ -1,28 +1,34 @@
group BusinessSubscriptionTransitionTag;
-getTagsForBusinessSubscriptionTransition(external_key) ::=<<
+getTagsForBusinessSubscriptionTransitionByKey(external_key) ::=<<
select
- external_key
+ bundle_id
+, external_key
+, account_key
, name
from bst_tags
where external_key = :external_key
;
>>
-addTag(external_key, name) ::=<<
+addTag(bundle_id, external_key, name) ::=<<
insert into bst_tags (
- external_key
+ bundle_id
+, external_key
+, account_key
, name
) values (
- :external_key
+ :bundle_id
+, :external_key
+, :account_key
, :name
);
>>
-removeTag(external_key, name) ::= <<
-delete from bst_tags where external_key = :external_key and name = :name;
+removeTag(bundle_id, name) ::= <<
+delete from bst_tags where bundle_id = :bundle_id and name = :name;
>>
test() ::= <<
select 1 from bst_tags;
->>
\ No newline at end of file
+>>
diff --git a/analytics/src/main/resources/com/ning/billing/analytics/ddl.sql b/analytics/src/main/resources/com/ning/billing/analytics/ddl.sql
index 43aaad8..4e219d4 100644
--- a/analytics/src/main/resources/com/ning/billing/analytics/ddl.sql
+++ b/analytics/src/main/resources/com/ning/billing/analytics/ddl.sql
@@ -1,175 +1,214 @@
drop table if exists bst;
create table bst (
- total_ordering bigint default 0
+ record_id int(11) unsigned not null auto_increment
+, total_ordering bigint default 0
+, bundle_id char(36) not null
+, account_id char(36) not null
, external_key varchar(50) not null comment 'Bundle external key'
, account_key varchar(50) not null comment 'Account external key'
+, subscription_id char(36) not null
, requested_timestamp bigint not null
, event varchar(50) not null
-, prev_product_name varchar(32) default null
-, prev_product_type varchar(32) default null
-, prev_product_category varchar(32) default null
+, prev_product_name varchar(50) default null
+, prev_product_type varchar(50) default null
+, prev_product_category varchar(50) default null
, prev_slug varchar(50) default null
-, prev_phase varchar(32) default null
-, prev_billing_period varchar(32) default null
+, prev_phase varchar(50) default null
+, prev_billing_period varchar(50) default null
, prev_price numeric(10, 4) default 0
-, prev_price_list varchar(32) default null
+, prev_price_list varchar(50) default null
, prev_mrr numeric(10, 4) default 0
-, prev_currency varchar(32) default null
+, prev_currency varchar(50) default null
, prev_start_date bigint default null
-, prev_state varchar(32) default null
-, prev_subscription_id varchar(100) default null
-, prev_bundle_id varchar(100) default null
-, next_product_name varchar(32) default null
-, next_product_type varchar(32) default null
-, next_product_category varchar(32) default null
+, prev_state varchar(50) default null
+, next_product_name varchar(50) default null
+, next_product_type varchar(50) default null
+, next_product_category varchar(50) default null
, next_slug varchar(50) default null
-, next_phase varchar(32) default null
-, next_billing_period varchar(32) default null
+, next_phase varchar(50) default null
+, next_billing_period varchar(50) default null
, next_price numeric(10, 4) default 0
-, next_price_list varchar(32) default null
+, next_price_list varchar(50) default null
, next_mrr numeric(10, 4) default 0
-, next_currency varchar(32) default null
+, next_currency varchar(50) default null
, next_start_date bigint default null
-, next_state varchar(32) default null
-, next_subscription_id varchar(100) default null
-, next_bundle_id varchar(100) default null
-, primary key(total_ordering)
+, next_state varchar(50) default null
+, primary key(record_id)
) engine=innodb comment 'Business Subscription Transitions, track bundles lifecycle';
create index bst_key_index on bst (external_key, requested_timestamp asc);
drop table if exists bac;
create table bac (
- account_key varchar(50) not null
+ record_id int(11) unsigned not null auto_increment
+, account_id char(36) not null
+, account_key varchar(50) not null
, name varchar(100) not null
, created_date bigint not null
, updated_date bigint not null
, balance numeric(10, 4) default 0
, last_invoice_date bigint default null
, total_invoice_balance numeric(10, 4) default 0
-, last_payment_status varchar(100) default null
-, payment_method varchar(100) default null
-, credit_card_type varchar(32) default null
-, billing_address_country varchar(100) default null
-, currency char(3) default null
+, last_payment_status varchar(255) default null
+, payment_method varchar(50) default null
+, credit_card_type varchar(50) default null
+, billing_address_country varchar(50) default null
+, currency char(50) default null
+, primary key(record_id)
) engine=innodb comment 'Business ACcounts, keep a record of all accounts';
create unique index bac_key_index on bac (account_key);
drop table if exists bin;
create table bin (
- invoice_id char(36) not null
+ record_id int(11) unsigned not null auto_increment
+, invoice_id char(36) not null
+, invoice_number bigint default null
, created_date bigint not null
, updated_date bigint not null
+, account_id char(36) not null
, account_key varchar(50) not null
, invoice_date bigint not null
, target_date bigint not null
-, currency char(3) not null
+, currency char(50) not null
, balance numeric(10, 4) default 0 comment 'amount_charged - amount_paid - amount_credited'
, amount_paid numeric(10, 4) default 0 comment 'Sums of the successful payments made for this invoice minus the refunds associated with this invoice'
, amount_charged numeric(10, 4) default 0 comment 'Sums of the invoice items amount'
, amount_credited numeric(10, 4) default 0 comment 'Sums of the credit items'
+, primary key(record_id)
) engine=innodb comment 'Business INvoices, keep a record of generated invoices';
create unique index bin_key_index on bin (invoice_id);
drop table if exists bii;
create table bii (
- item_id char(36) not null
+ record_id int(11) unsigned not null auto_increment
+, item_id char(36) not null
, created_date bigint not null
, updated_date bigint not null
, invoice_id char(36) not null
-, item_type char(20) not null comment 'e.g. FIXED or RECURRING'
+, item_type char(50) not null comment 'e.g. FIXED or RECURRING'
, external_key varchar(50) not null comment 'Bundle external key'
-, product_name varchar(32) default null
-, product_type varchar(32) default null
-, product_category varchar(32) default null
+, product_name varchar(50) default null
+, product_type varchar(50) default null
+, product_category varchar(50) default null
, slug varchar(50) default null comment 'foo'
-, phase varchar(32) default null
-, billing_period varchar(32) default null
+, phase varchar(50) default null
+, billing_period varchar(50) default null
, start_date bigint default null
, end_date bigint default null
, amount numeric(10, 4) default 0
-, currency char(3) default null
+, currency char(50) default null
+, primary key(record_id)
) engine=innodb comment 'Business Invoice Items, keep a record of all invoice items';
create unique index bii_key_index on bii (item_id);
drop table if exists bip;
create table bip (
- payment_id char(36) not null
+ record_id int(11) unsigned not null auto_increment
+, payment_id char(36) not null
, created_date bigint not null
, updated_date bigint not null
-, attempt_id char(36) not null
+, ext_payment_ref_id varchar(255) default null
, account_key varchar(50) not null comment 'Account external key'
, invoice_id char(36) not null
, effective_date bigint default null
, amount numeric(10, 4) default 0
-, currency char(3) default null
-, payment_error varchar(256) default null
+, currency char(50) default null
+, payment_error varchar(255) default null
, processing_status varchar(50) default null
, requested_amount numeric(10, 4) default 0
-, plugin_name varchar(20) default null
-, payment_type varchar(20) default null
-, payment_method varchar(20) default null
-, card_type varchar(20) default null
-, card_country varchar(20) default null
-) engine=innodb comment 'Business Invoice Payments, track all payment attempts';
-create unique index bip_key_index on bip (attempt_id);
+, plugin_name varchar(50) default null
+, payment_type varchar(50) default null
+, payment_method varchar(50) default null
+, card_type varchar(50) default null
+, card_country varchar(50) default null
+, invoice_payment_type varchar(50) default null
+, linked_invoice_payment_id char(36) default null
+, primary key(record_id)
+) engine=innodb comment 'Business Invoice Payments, track all payments';
+create unique index bip_key_index on bip (payment_id);
drop table if exists bos;
create table bos (
- external_key varchar(50) not null comment 'Bundle external key'
+ record_id int(11) unsigned not null auto_increment
+, bundle_id char(36) not null
+, external_key varchar(50) not null comment 'Bundle external key'
+, account_key varchar(50) not null comment 'Account external key'
, status varchar(50) not null
, start_date bigint default null
, end_date bigint default null
+, primary key(record_id)
) engine=innodb comment 'Business Overdue Status, historical bundles overdue status';
create unique index bos_key_index on bos (external_key, status);
drop table if exists bac_tags;
create table bac_tags (
- account_key varchar(50) not null comment 'Account external key'
-, name varchar(20) not null
+ record_id int(11) unsigned not null auto_increment
+, account_id char(36) not null
+, account_key varchar(50) not null comment 'Account external key'
+, name varchar(50) not null
+, primary key(record_id)
) engine=innodb comment 'Tags associated to accounts';
drop table if exists bac_fields;
create table bac_fields (
- account_key varchar(50) not null comment 'Account external key'
-, name varchar(30) not null
+ record_id int(11) unsigned not null auto_increment
+, account_id char(36) not null
+, account_key varchar(50) not null comment 'Account external key'
+, name varchar(50) not null
, value varchar(255) default null
+, primary key(record_id)
) engine=innodb comment 'Custom fields associated to accounts';
drop table if exists bst_tags;
create table bst_tags (
- external_key varchar(50) not null comment 'Bundle external key'
-, name varchar(20) not null
+ record_id int(11) unsigned not null auto_increment
+, bundle_id char(36) not null
+, external_key varchar(50) not null comment 'Bundle external key'
+, account_key varchar(50) not null comment 'Account external key'
+, name varchar(50) not null
+, primary key(record_id)
) engine=innodb comment 'Tags associated to bundles';
drop table if exists bst_fields;
create table bst_fields (
- external_key varchar(50) not null comment 'Bundle external key'
-, name varchar(30) not null
+ record_id int(11) unsigned not null auto_increment
+, bundle_id char(36) not null
+, external_key varchar(50) not null comment 'Bundle external key'
+, account_key varchar(50) not null comment 'Account external key'
+, name varchar(50) not null
, value varchar(255) default null
+, primary key(record_id)
) engine=innodb comment 'Custom fields associated to bundles';
drop table if exists bin_tags;
create table bin_tags (
- invoice_id char(36) not null
-, name varchar(20) not null
+ record_id int(11) unsigned not null auto_increment
+, invoice_id char(36) not null
+, name varchar(50) not null
+, primary key(record_id)
) engine=innodb comment 'Tags associated to invoices';
drop table if exists bin_fields;
create table bin_fields (
- invoice_id char(36) not null
-, name varchar(30) not null
+ record_id int(11) unsigned not null auto_increment
+, invoice_id char(36) not null
+, name varchar(50) not null
, value varchar(255) default null
+, primary key(record_id)
) engine=innodb comment 'Custom fields associated to invoices';
drop table if exists bip_tags;
create table bip_tags (
- payment_id char(36) not null
-, name varchar(20) not null
+ record_id int(11) unsigned not null auto_increment
+, payment_id char(36) not null
+, name varchar(50) not null
+, primary key(record_id)
) engine=innodb comment 'Tags associated to payments';
drop table if exists bip_fields;
create table bip_fields (
- payment_id char(36) not null
-, name varchar(30) not null
+ record_id int(11) unsigned not null auto_increment
+, payment_id char(36) not null
+, name varchar(50) not null
, value varchar(255) default null
+, primary key(record_id)
) engine=innodb comment 'Custom fields associated to payments';
diff --git a/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestModule.java b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestModule.java
index e7c167e..d710c9f 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestModule.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestModule.java
@@ -62,7 +62,7 @@ public class AnalyticsTestModule extends AnalyticsModule {
install(new DefaultJunctionModule());
// Install the Dao layer
- final MysqlTestingHelper helper = TestWithEmbeddedDB.getMysqlTestingHelper();
+ final MysqlTestingHelper helper = AnalyticsTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
diff --git a/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuite.java b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuite.java
index 489f5a1..e388f51 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuite.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuite.java
@@ -16,27 +16,7 @@
package com.ning.billing.analytics;
-import java.lang.reflect.Method;
+import com.ning.billing.KillbillTestSuite;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-
-public abstract class AnalyticsTestSuite {
- private static final Logger log = LoggerFactory.getLogger(AnalyticsTestSuite.class);
-
- @BeforeMethod(alwaysRun = true)
- public void startTest(final Method method) throws Exception {
- log.info("***************************************************************************************************");
- log.info("*** Starting test {}:{}", method.getDeclaringClass().getName(), method.getName());
- log.info("***************************************************************************************************");
- }
-
- @AfterMethod(alwaysRun = true)
- public void endTest(final Method method) throws Exception {
- log.info("***************************************************************************************************");
- log.info("*** Ending test {}:{}", method.getDeclaringClass().getName(), method.getName());
- log.info("***************************************************************************************************");
- }
+public abstract class AnalyticsTestSuite extends KillbillTestSuite {
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuiteWithEmbeddedDB.java b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..8f6bd92
--- /dev/null
+++ b/analytics/src/test/java/com/ning/billing/analytics/AnalyticsTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.analytics;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class AnalyticsTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/api/TestAnalyticsService.java b/analytics/src/test/java/com/ning/billing/analytics/api/TestAnalyticsService.java
index 5d452e1..2e71aa4 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/api/TestAnalyticsService.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/api/TestAnalyticsService.java
@@ -38,9 +38,8 @@ import com.ning.billing.account.api.user.DefaultAccountCreationEvent;
import com.ning.billing.analytics.AnalyticsTestModule;
import com.ning.billing.analytics.MockDuration;
import com.ning.billing.analytics.MockPhase;
-import com.ning.billing.analytics.MockPlan;
import com.ning.billing.analytics.MockProduct;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.dao.BusinessAccountSqlDao;
import com.ning.billing.analytics.dao.BusinessSubscriptionTransitionSqlDao;
import com.ning.billing.analytics.model.BusinessSubscription;
@@ -57,12 +56,12 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.PriceList;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
-import com.ning.billing.entitlement.api.user.DefaultSubscriptionEvent;
+import com.ning.billing.entitlement.api.user.DefaultEffectiveSubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.SubscriptionEvent;
import com.ning.billing.entitlement.api.user.SubscriptionTransitionData;
import com.ning.billing.entitlement.events.EntitlementEvent;
import com.ning.billing.entitlement.events.user.ApiEventType;
@@ -73,6 +72,7 @@ import com.ning.billing.invoice.dao.InvoiceDao;
import com.ning.billing.invoice.model.DefaultInvoice;
import com.ning.billing.invoice.model.FixedPriceInvoiceItem;
import com.ning.billing.mock.MockAccountBuilder;
+import com.ning.billing.mock.MockPlan;
import com.ning.billing.payment.api.DefaultPaymentInfoEvent;
import com.ning.billing.payment.api.PaymentInfoEvent;
import com.ning.billing.payment.api.PaymentStatus;
@@ -88,13 +88,14 @@ import com.ning.billing.util.clock.DefaultClock;
import static org.testng.Assert.fail;
@Guice(modules = {AnalyticsTestModule.class})
-public class TestAnalyticsService extends TestWithEmbeddedDB {
+public class TestAnalyticsService extends AnalyticsTestSuiteWithEmbeddedDB {
final Product product = new MockProduct("platinum", "subscription", ProductCategory.BASE);
final Plan plan = new MockPlan("platinum-monthly", product);
final PlanPhase phase = new MockPhase(PhaseType.EVERGREEN, plan, MockDuration.UNLIMITED(), 25.95);
private static final Long TOTAL_ORDERING = 11L;
private static final String EXTERNAL_KEY = "12345";
+ private static final UUID ACCOUNT_ID = UUID.randomUUID();
private static final String ACCOUNT_KEY = "pierre-12345";
private static final Currency ACCOUNT_CURRENCY = Currency.EUR;
private static final BigDecimal INVOICE_AMOUNT = BigDecimal.valueOf(1243.11);
@@ -126,7 +127,7 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
@Inject
private BusinessAccountSqlDao accountSqlDao;
- private SubscriptionEvent transition;
+ private EffectiveSubscriptionEvent transition;
private BusinessSubscriptionTransition expectedTransition;
private AccountCreationEvent accountCreationNotification;
@@ -180,8 +181,7 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
final DateTime requestedTransitionTime = clock.getUTCNow();
final PriceList priceList = new MockPriceList().setName("something");
-
- transition = new DefaultSubscriptionEvent(new SubscriptionTransitionData(
+ transition = new DefaultEffectiveSubscriptionEvent(new SubscriptionTransitionData(
UUID.randomUUID(),
subscriptionId,
bundle.getId(),
@@ -202,12 +202,15 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
true), null);
expectedTransition = new BusinessSubscriptionTransition(
TOTAL_ORDERING,
+ transition.getBundleId(),
EXTERNAL_KEY,
+ ACCOUNT_ID,
ACCOUNT_KEY,
+ transition.getSubscriptionId(),
requestedTransitionTime,
BusinessSubscriptionEvent.subscriptionCreated(plan.getName(), catalog, new DateTime(), new DateTime()),
null,
- new BusinessSubscription(priceList.getName(), plan.getName(), phase.getName(), ACCOUNT_CURRENCY, effectiveTransitionTime, Subscription.SubscriptionState.ACTIVE, subscriptionId, bundle.getId(), catalog)
+ new BusinessSubscription(priceList.getName(), plan.getName(), phase.getName(), ACCOUNT_CURRENCY, effectiveTransitionTime, Subscription.SubscriptionState.ACTIVE, catalog)
);
}
@@ -222,7 +225,7 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
INVOICE_AMOUNT, ACCOUNT_CURRENCY);
invoice.addInvoiceItem(invoiceItem);
- invoiceDao.create(invoice, context);
+ invoiceDao.create(invoice, invoice.getTargetDate().getDayOfMonth(), context);
final List<Invoice> invoices = invoiceDao.getInvoicesByAccount(account.getId());
Assert.assertEquals(invoices.size(), 1);
Assert.assertEquals(invoices.get(0).getInvoiceItems().size(), 1);
@@ -231,7 +234,7 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
invoiceCreationNotification = new DefaultInvoiceCreationEvent(invoice.getId(), account.getId(),
INVOICE_AMOUNT, ACCOUNT_CURRENCY, clock.getUTCNow(), null);
- paymentInfoNotification = new DefaultPaymentInfoEvent(account.getId(), invoices.get(0).getId(), null, invoices.get(0).getBalance(), -1, PaymentStatus.UNKNOWN, null, new DateTime());
+ paymentInfoNotification = new DefaultPaymentInfoEvent(account.getId(), invoices.get(0).getId(), null, invoices.get(0).getBalance(), -1, PaymentStatus.UNKNOWN, null, null, new DateTime());
//STEPH talk to Pierre
/*
@@ -257,23 +260,23 @@ public class TestAnalyticsService extends TestWithEmbeddedDB {
Assert.fail("Unable to start the bus or service! " + t);
}
- Assert.assertNull(accountSqlDao.getAccount(ACCOUNT_KEY));
+ Assert.assertNull(accountSqlDao.getAccountByKey(ACCOUNT_KEY));
// Send events and wait for the async part...
bus.post(transition);
bus.post(accountCreationNotification);
Thread.sleep(5000);
- Assert.assertEquals(subscriptionSqlDao.getTransitions(EXTERNAL_KEY).size(), 1);
- Assert.assertEquals(subscriptionSqlDao.getTransitions(EXTERNAL_KEY).get(0), expectedTransition);
+ Assert.assertEquals(subscriptionSqlDao.getTransitionsByKey(EXTERNAL_KEY).size(), 1);
+ Assert.assertEquals(subscriptionSqlDao.getTransitionsByKey(EXTERNAL_KEY).get(0), expectedTransition);
// Test invoice integration - the account creation notification has triggered a BAC update
- Assert.assertTrue(accountSqlDao.getAccount(ACCOUNT_KEY).getTotalInvoiceBalance().compareTo(INVOICE_AMOUNT) == 0);
+ Assert.assertTrue(accountSqlDao.getAccountByKey(ACCOUNT_KEY).getTotalInvoiceBalance().compareTo(INVOICE_AMOUNT) == 0);
// Post the same invoice event again - the invoice balance shouldn't change
bus.post(invoiceCreationNotification);
Thread.sleep(5000);
- Assert.assertTrue(accountSqlDao.getAccount(ACCOUNT_KEY).getTotalInvoiceBalance().compareTo(INVOICE_AMOUNT) == 0);
+ Assert.assertTrue(accountSqlDao.getAccountByKey(ACCOUNT_KEY).getTotalInvoiceBalance().compareTo(INVOICE_AMOUNT) == 0);
// Test payment integration - the fields have already been populated, just make sure the code is exercised
bus.post(paymentInfoNotification);
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestAnalyticsDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestAnalyticsDao.java
index 5d6b3a6..67fec93 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestAnalyticsDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestAnalyticsDao.java
@@ -30,15 +30,14 @@ import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import com.ning.billing.analytics.MockDuration;
+import com.ning.billing.analytics.MockPhase;
+import com.ning.billing.analytics.MockProduct;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessAccount;
import com.ning.billing.analytics.model.BusinessSubscription;
import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
-import com.ning.billing.analytics.MockDuration;
-import com.ning.billing.analytics.MockPhase;
-import com.ning.billing.analytics.MockPlan;
-import com.ning.billing.analytics.MockProduct;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
import com.ning.billing.analytics.utils.Rounder;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogApiException;
@@ -50,10 +49,13 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.mock.MockPlan;
-public class TestAnalyticsDao extends TestWithEmbeddedDB {
+public class TestAnalyticsDao extends AnalyticsTestSuiteWithEmbeddedDB {
private static final Long TOTAL_ORDERING = 1L;
+ private static final UUID BUNDLE_ID = UUID.randomUUID();
private static final String EXTERNAL_KEY = "23456";
+ private static final UUID ACCOUNT_ID = UUID.randomUUID();
private static final String ACCOUNT_KEY = "pierre-143343-vcc";
private final Product product = new MockProduct("platinium", "subscription", ProductCategory.BASE);
@@ -81,11 +83,12 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
private void setupBusinessSubscriptionTransition() {
final DateTime requestedTimestamp = new DateTime(DateTimeZone.UTC);
- final BusinessSubscription prevSubscription = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, new DateTime(DateTimeZone.UTC), Subscription.SubscriptionState.ACTIVE, UUID.randomUUID(), UUID.randomUUID(), catalog);
- final BusinessSubscription nextSubscription = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, new DateTime(DateTimeZone.UTC), Subscription.SubscriptionState.CANCELLED, UUID.randomUUID(), UUID.randomUUID(), catalog);
+ final BusinessSubscription prevSubscription = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, new DateTime(DateTimeZone.UTC), Subscription.SubscriptionState.ACTIVE, catalog);
+ final BusinessSubscription nextSubscription = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, new DateTime(DateTimeZone.UTC), Subscription.SubscriptionState.CANCELLED, catalog);
final BusinessSubscriptionEvent event = BusinessSubscriptionEvent.subscriptionCancelled(plan.getName(), catalog, requestedTimestamp, requestedTimestamp);
- transition = new BusinessSubscriptionTransition(TOTAL_ORDERING, EXTERNAL_KEY, ACCOUNT_KEY, requestedTimestamp, event, prevSubscription, nextSubscription);
+ transition = new BusinessSubscriptionTransition(TOTAL_ORDERING, BUNDLE_ID, EXTERNAL_KEY, ACCOUNT_ID, ACCOUNT_KEY,
+ UUID.randomUUID(), requestedTimestamp, event, prevSubscription, nextSubscription);
final IDBI dbi = helper.getDBI();
businessSubscriptionTransitionSqlDao = dbi.onDemand(BusinessSubscriptionTransitionSqlDao.class);
@@ -99,7 +102,7 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
}
private void setupBusinessAccount() {
- account = new BusinessAccount(ACCOUNT_KEY, UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(DateTimeZone.UTC), BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "FRANCE");
+ account = new BusinessAccount(UUID.randomUUID(), ACCOUNT_KEY, UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(DateTimeZone.UTC), BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "FRANCE");
final IDBI dbi = helper.getDBI();
businessAccountSqlDao = dbi.onDemand(BusinessAccountSqlDao.class);
@@ -113,50 +116,14 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
}
@Test(groups = "slow")
- public void testHandleDuplicatedEvents() {
- final BusinessSubscriptionTransition transitionWithNullPrev = new BusinessSubscriptionTransition(
- transition.getTotalOrdering(),
- transition.getExternalKey(),
- transition.getAccountKey(),
- transition.getRequestedTimestamp(),
- transition.getEvent(),
- null,
- transition.getNextSubscription()
- );
-
- businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPrev);
- List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
- Assert.assertEquals(transitions.size(), 1);
- Assert.assertEquals(transitions.get(0), transitionWithNullPrev);
- // Try to add the same transition, with the same UUID - we should only store one though
- businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPrev);
- transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
- Assert.assertEquals(transitions.size(), 1);
- Assert.assertEquals(transitions.get(0), transitionWithNullPrev);
-
- // Try now to store a look-alike transition (same fields except UUID) - we should store it this time
- final BusinessSubscriptionTransition secondTransitionWithNullPrev = new BusinessSubscriptionTransition(
- 12L,
- transition.getExternalKey(),
- transition.getAccountKey(),
- transition.getRequestedTimestamp(),
- transition.getEvent(),
- null,
- transition.getNextSubscription()
- );
- businessSubscriptionTransitionSqlDao.createTransition(secondTransitionWithNullPrev);
- transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
- Assert.assertEquals(transitions.size(), 2);
- Assert.assertTrue(transitions.contains(transitionWithNullPrev));
- Assert.assertTrue(transitions.contains(secondTransitionWithNullPrev));
- }
-
- @Test(groups = "slow")
public void testTransitionsWithNullPrevSubscription() {
final BusinessSubscriptionTransition transitionWithNullPrev = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
null,
@@ -164,7 +131,7 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPrev);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0), transitionWithNullPrev);
}
@@ -173,8 +140,11 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
public void testTransitionsWithNullNextSubscription() {
final BusinessSubscriptionTransition transitionWithNullNext = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
transition.getPreviousSubscription(),
@@ -182,18 +152,21 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullNext);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0), transitionWithNullNext);
}
@Test(groups = "slow")
public void testTransitionsWithNullFieldsInSubscription() {
- final BusinessSubscription subscriptionWithNullFields = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, null, null, null, null, catalog);
+ final BusinessSubscription subscriptionWithNullFields = new BusinessSubscription(null, plan.getName(), phase.getName(), Currency.USD, null, null, catalog);
final BusinessSubscriptionTransition transitionWithNullFields = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
subscriptionWithNullFields,
@@ -201,18 +174,21 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullFields);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0), transitionWithNullFields);
}
@Test(groups = "slow")
public void testTransitionsWithNullPlanAndPhase() throws Exception {
- final BusinessSubscription subscriptionWithNullPlanAndPhase = new BusinessSubscription(null, null, null, Currency.USD, null, null, null, null, catalog);
+ final BusinessSubscription subscriptionWithNullPlanAndPhase = new BusinessSubscription(null, null, null, Currency.USD, null, null, catalog);
final BusinessSubscriptionTransition transitionWithNullPlanAndPhase = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
subscriptionWithNullPlanAndPhase,
@@ -220,7 +196,7 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPlanAndPhase);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0).getExternalKey(), transition.getExternalKey());
Assert.assertEquals(transitions.get(0).getRequestedTimestamp(), transition.getRequestedTimestamp());
@@ -231,11 +207,14 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testTransitionsWithNullPlan() throws Exception {
- final BusinessSubscription subscriptionWithNullPlan = new BusinessSubscription(null, null, phase.getName(), Currency.USD, null, null, null, null, catalog);
+ final BusinessSubscription subscriptionWithNullPlan = new BusinessSubscription(null, null, phase.getName(), Currency.USD, null, null, catalog);
final BusinessSubscriptionTransition transitionWithNullPlan = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
subscriptionWithNullPlan,
@@ -243,7 +222,7 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPlan);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
// Null Plan but Phase - we don't turn the subscription into a null
Assert.assertEquals(transitions.get(0), transitionWithNullPlan);
@@ -251,11 +230,14 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testTransitionsWithNullPhase() throws Exception {
- final BusinessSubscription subscriptionWithNullPhase = new BusinessSubscription(null, plan.getName(), null, Currency.USD, null, null, null, null, catalog);
+ final BusinessSubscription subscriptionWithNullPhase = new BusinessSubscription(null, plan.getName(), null, Currency.USD, null, null, catalog);
final BusinessSubscriptionTransition transitionWithNullPhase = new BusinessSubscriptionTransition(
transition.getTotalOrdering(),
+ transition.getBundleId(),
transition.getExternalKey(),
+ transition.getAccountId(),
transition.getAccountKey(),
+ transition.getSubscriptionId(),
transition.getRequestedTimestamp(),
transition.getEvent(),
subscriptionWithNullPhase,
@@ -263,14 +245,14 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
);
businessSubscriptionTransitionSqlDao.createTransition(transitionWithNullPhase);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0).getExternalKey(), transition.getExternalKey());
Assert.assertEquals(transitions.get(0).getRequestedTimestamp(), transition.getRequestedTimestamp());
Assert.assertEquals(transitions.get(0).getEvent(), transition.getEvent());
// Null Phase but Plan - we don't turn the subscription into a null, however price and mrr are both set to 0 (not null)
- final BusinessSubscription blankSubscription = new BusinessSubscription(null, plan.getName(), new MockPhase(null, null, null, 0.0).getName(), Currency.USD, null, null, null, null, catalog);
+ final BusinessSubscription blankSubscription = new BusinessSubscription(null, plan.getName(), new MockPhase(null, null, null, 0.0).getName(), Currency.USD, null, null, catalog);
Assert.assertEquals(transitions.get(0).getPreviousSubscription(), blankSubscription);
Assert.assertEquals(transitions.get(0).getNextSubscription(), blankSubscription);
}
@@ -279,18 +261,18 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
public void testCreateAndRetrieveTransitions() {
businessSubscriptionTransitionSqlDao.createTransition(transition);
- final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitions(EXTERNAL_KEY);
+ final List<BusinessSubscriptionTransition> transitions = businessSubscriptionTransitionSqlDao.getTransitionsByKey(EXTERNAL_KEY);
Assert.assertEquals(transitions.size(), 1);
Assert.assertEquals(transitions.get(0), transition);
- Assert.assertEquals(businessSubscriptionTransitionSqlDao.getTransitions("Doesn't exist").size(), 0);
+ Assert.assertEquals(businessSubscriptionTransitionSqlDao.getTransitionsByKey("Doesn't exist").size(), 0);
}
@Test(groups = "slow")
public void testCreateSaveAndRetrieveAccounts() {
// Create and retrieve an account
businessAccountSqlDao.createAccount(account);
- final BusinessAccount foundAccount = businessAccountSqlDao.getAccount(ACCOUNT_KEY);
+ final BusinessAccount foundAccount = businessAccountSqlDao.getAccountByKey(ACCOUNT_KEY);
Assert.assertNotNull(foundAccount.getCreatedDt());
Assert.assertEquals(foundAccount.getCreatedDt(), foundAccount.getUpdatedDt());
// Verify the dates by backfilling them
@@ -304,12 +286,12 @@ public class TestAnalyticsDao extends TestWithEmbeddedDB {
account.setPaymentMethod("PayPal");
businessAccountSqlDao.saveAccount(account);
// Verify the save worked as expected
- account = businessAccountSqlDao.getAccount(ACCOUNT_KEY);
+ account = businessAccountSqlDao.getAccountByKey(ACCOUNT_KEY);
Assert.assertEquals(Rounder.round(BigDecimal.TEN), account.getRoundedBalance());
Assert.assertEquals("PayPal", account.getPaymentMethod());
Assert.assertTrue(account.getUpdatedDt().compareTo(previousUpdatedDt) > 0);
// ACCOUNT not found
- Assert.assertNull(businessAccountSqlDao.getAccount("Doesn't exist"));
+ Assert.assertNull(businessAccountSqlDao.getAccountByKey("Doesn't exist"));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountFieldSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountFieldSqlDao.java
index 69fed56..196da64 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountFieldSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountFieldSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessAccountField;
-public class TestBusinessAccountFieldSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessAccountFieldSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessAccountFieldSqlDao accountFieldSqlDao;
@BeforeMethod(groups = "slow")
@@ -38,49 +38,53 @@ public class TestBusinessAccountFieldSqlDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testCRUD() throws Exception {
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString().substring(0, 30);
final String value = UUID.randomUUID().toString();
// Verify initial state
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey).size(), 0);
- Assert.assertEquals(accountFieldSqlDao.removeField(accountKey, name), 0);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey).size(), 0);
+ Assert.assertEquals(accountFieldSqlDao.removeField(accountId.toString(), name), 0);
// Add an entry
- Assert.assertEquals(accountFieldSqlDao.addField(accountKey, name, value), 1);
- final List<BusinessAccountField> fieldsForAccount = accountFieldSqlDao.getFieldsForAccount(accountKey);
+ Assert.assertEquals(accountFieldSqlDao.addField(accountId.toString(), accountKey, name, value), 1);
+ final List<BusinessAccountField> fieldsForAccount = accountFieldSqlDao.getFieldsForAccountByKey(accountKey);
Assert.assertEquals(fieldsForAccount.size(), 1);
// Retrieve it
final BusinessAccountField accountField = fieldsForAccount.get(0);
+ Assert.assertEquals(accountField.getAccountId(), accountId);
Assert.assertEquals(accountField.getAccountKey(), accountKey);
Assert.assertEquals(accountField.getName(), name);
Assert.assertEquals(accountField.getValue(), value);
// Delete it
- Assert.assertEquals(accountFieldSqlDao.removeField(accountKey, name), 1);
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey).size(), 0);
+ Assert.assertEquals(accountFieldSqlDao.removeField(accountId.toString(), name), 1);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
+ final UUID accountId1 = UUID.randomUUID();
final String accountKey1 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString().substring(0, 30);
+ final UUID accountId2 = UUID.randomUUID();
final String accountKey2 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString().substring(0, 30);
// Add a field to both accounts
- Assert.assertEquals(accountFieldSqlDao.addField(accountKey1, name1, UUID.randomUUID().toString()), 1);
- Assert.assertEquals(accountFieldSqlDao.addField(accountKey2, name2, UUID.randomUUID().toString()), 1);
+ Assert.assertEquals(accountFieldSqlDao.addField(accountId1.toString(), accountKey1, name1, UUID.randomUUID().toString()), 1);
+ Assert.assertEquals(accountFieldSqlDao.addField(accountId2.toString(), accountKey2, name2, UUID.randomUUID().toString()), 1);
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey1).size(), 1);
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey1).size(), 1);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey2).size(), 1);
// Remove the field for the first account
- Assert.assertEquals(accountFieldSqlDao.removeField(accountKey1, name1), 1);
+ Assert.assertEquals(accountFieldSqlDao.removeField(accountId1.toString(), name1), 1);
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey1).size(), 0);
- Assert.assertEquals(accountFieldSqlDao.getFieldsForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey1).size(), 0);
+ Assert.assertEquals(accountFieldSqlDao.getFieldsForAccountByKey(accountKey2).size(), 1);
}
@Test(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountTagSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountTagSqlDao.java
index 20ccfc8..1a55220 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountTagSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessAccountTagSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessAccountTag;
-public class TestBusinessAccountTagSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessAccountTagSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessAccountTagSqlDao accountTagSqlDao;
@BeforeMethod(groups = "slow")
@@ -38,47 +38,51 @@ public class TestBusinessAccountTagSqlDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testCRUD() throws Exception {
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString().substring(0, 20);
// Verify initial state
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey).size(), 0);
- Assert.assertEquals(accountTagSqlDao.removeTag(accountKey, name), 0);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey).size(), 0);
+ Assert.assertEquals(accountTagSqlDao.removeTag(accountId.toString(), name), 0);
// Add an entry
- Assert.assertEquals(accountTagSqlDao.addTag(accountKey, name), 1);
- final List<BusinessAccountTag> tagsForAccount = accountTagSqlDao.getTagsForAccount(accountKey);
+ Assert.assertEquals(accountTagSqlDao.addTag(accountId.toString(), accountKey, name), 1);
+ final List<BusinessAccountTag> tagsForAccount = accountTagSqlDao.getTagsForAccountByKey(accountKey);
Assert.assertEquals(tagsForAccount.size(), 1);
// Retrieve it
final BusinessAccountTag accountTag = tagsForAccount.get(0);
+ Assert.assertEquals(accountTag.getAccountId(), accountId);
Assert.assertEquals(accountTag.getAccountKey(), accountKey);
Assert.assertEquals(accountTag.getName(), name);
// Delete it
- Assert.assertEquals(accountTagSqlDao.removeTag(accountKey, name), 1);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey).size(), 0);
+ Assert.assertEquals(accountTagSqlDao.removeTag(accountId.toString(), name), 1);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
+ final UUID accountId1 = UUID.randomUUID();
final String accountKey1 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString().substring(0, 20);
+ final UUID accountId2 = UUID.randomUUID();
final String accountKey2 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString().substring(0, 20);
// Add a tag to both accounts
- Assert.assertEquals(accountTagSqlDao.addTag(accountKey1, name1), 1);
- Assert.assertEquals(accountTagSqlDao.addTag(accountKey2, name2), 1);
+ Assert.assertEquals(accountTagSqlDao.addTag(accountId1.toString(), accountKey1, name1), 1);
+ Assert.assertEquals(accountTagSqlDao.addTag(accountId2.toString(), accountKey2, name2), 1);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey1).size(), 1);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey1).size(), 1);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey2).size(), 1);
// Remove the tag for the first account
- Assert.assertEquals(accountTagSqlDao.removeTag(accountKey1, name1), 1);
+ Assert.assertEquals(accountTagSqlDao.removeTag(accountId1.toString(), name1), 1);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey1).size(), 0);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey1).size(), 0);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey2).size(), 1);
}
@Test(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceFieldSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceFieldSqlDao.java
index 9553dfa..910fe74 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceFieldSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceFieldSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoiceField;
-public class TestBusinessInvoiceFieldSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoiceFieldSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoiceFieldSqlDao invoiceFieldSqlDao;
@BeforeMethod(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceItemSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceItemSqlDao.java
index 1bd7b31..de6aa69 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceItemSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceItemSqlDao.java
@@ -26,11 +26,11 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoiceItem;
import com.ning.billing.catalog.api.Currency;
-public class TestBusinessInvoiceItemSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoiceItemSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoiceItemSqlDao invoiceItemSqlDao;
@BeforeMethod(groups = "slow")
@@ -54,24 +54,15 @@ public class TestBusinessInvoiceItemSqlDao extends TestWithEmbeddedDB {
// Retrieve it
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItem(invoiceItem.getItemId().toString()), invoiceItem);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(invoiceItem.getExternalKey()).size(), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(invoiceItem.getExternalKey()).get(0), invoiceItem);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceItem.getInvoiceId().toString()).size(), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceItem.getInvoiceId().toString()).get(0), invoiceItem);
-
- // Update and retrieve it
- invoiceItem.setProductName(UUID.randomUUID().toString().substring(0, 20));
- Assert.assertEquals(invoiceItemSqlDao.updateInvoiceItem(invoiceItem), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItem(invoiceItem.getItemId().toString()), invoiceItem);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(invoiceItem.getExternalKey()).size(), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(invoiceItem.getExternalKey()).get(0), invoiceItem);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(invoiceItem.getExternalKey()).size(), 1);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(invoiceItem.getExternalKey()).get(0), invoiceItem);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceItem.getInvoiceId().toString()).size(), 1);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceItem.getInvoiceId().toString()).get(0), invoiceItem);
// Delete it
Assert.assertEquals(invoiceItemSqlDao.deleteInvoiceItem(invoiceItem.getItemId().toString()), 1);
Assert.assertNull(invoiceItemSqlDao.getInvoiceItem(invoiceItem.getItemId().toString()));
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(invoiceItem.getExternalKey()).size(), 0);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(invoiceItem.getExternalKey()).size(), 0);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceItem.getInvoiceId().toString()).size(), 0);
}
@@ -88,16 +79,16 @@ public class TestBusinessInvoiceItemSqlDao extends TestWithEmbeddedDB {
Assert.assertEquals(invoiceItemSqlDao.createInvoiceItem(invoiceItem1), 1);
Assert.assertEquals(invoiceItemSqlDao.createInvoiceItem(invoiceItem2), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(externalKey1).size(), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(externalKey2).size(), 1);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(externalKey1).size(), 1);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(externalKey2).size(), 1);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceId1.toString()).size(), 1);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceId2.toString()).size(), 1);
// Remove the first invoice item
Assert.assertEquals(invoiceItemSqlDao.deleteInvoiceItem(invoiceItem1.getItemId().toString()), 1);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(externalKey1).size(), 0);
- Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundle(externalKey2).size(), 1);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(externalKey1).size(), 0);
+ Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForBundleByKey(externalKey2).size(), 1);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceId1.toString()).size(), 0);
Assert.assertEquals(invoiceItemSqlDao.getInvoiceItemsForInvoice(invoiceId2.toString()).size(), 1);
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentFieldSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentFieldSqlDao.java
index b97849d..c898a7f 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentFieldSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentFieldSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoicePaymentField;
-public class TestBusinessInvoicePaymentFieldSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoicePaymentFieldSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoicePaymentFieldSqlDao invoicePaymentFieldSqlDao;
@BeforeMethod(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentSqlDao.java
index 94a8066..7aed3b6 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentSqlDao.java
@@ -26,11 +26,11 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoicePayment;
import com.ning.billing.catalog.api.Currency;
-public class TestBusinessInvoicePaymentSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoicePaymentSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoicePaymentSqlDao invoicePaymentSqlDao;
@BeforeMethod(groups = "slow")
@@ -41,69 +41,53 @@ public class TestBusinessInvoicePaymentSqlDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testCRUD() throws Exception {
- final UUID attemptId = UUID.randomUUID();
+ final String extPaymentRefId = UUID.randomUUID().toString();
final String accountKey = UUID.randomUUID().toString();
- final BusinessInvoicePayment invoicePayment = createInvoicePayment(attemptId, accountKey);
+ final BusinessInvoicePayment invoicePayment = createInvoicePayment(extPaymentRefId, accountKey);
// Verify initial state
- Assert.assertNull(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()));
- Assert.assertEquals(invoicePaymentSqlDao.deleteInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()), 0);
+ Assert.assertNull(invoicePaymentSqlDao.getInvoicePayment(invoicePayment.getPaymentId().toString()));
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment.getAccountKey()).size(), 0);
// Add the invoice payment
Assert.assertEquals(invoicePaymentSqlDao.createInvoicePayment(invoicePayment), 1);
// Retrieve it
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()), invoicePayment);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment.getAccountKey()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment.getAccountKey()).get(0), invoicePayment);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment.getPaymentId().toString()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment.getPaymentId().toString()).get(0), invoicePayment);
-
- // Update and retrieve it
- invoicePayment.setCardType(UUID.randomUUID().toString().substring(0, 20));
- Assert.assertEquals(invoicePaymentSqlDao.updateInvoicePaymentForPaymentAttempt(invoicePayment), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()), invoicePayment);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment.getAccountKey()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment.getAccountKey()).get(0), invoicePayment);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment.getPaymentId().toString()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment.getPaymentId().toString()).get(0), invoicePayment);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePayment(invoicePayment.getPaymentId().toString()), invoicePayment);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment.getAccountKey()).size(), 1);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment.getAccountKey()).get(0), invoicePayment);
// Delete it
- Assert.assertEquals(invoicePaymentSqlDao.deleteInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()), 1);
- Assert.assertNull(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment.getAttemptId().toString()));
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment.getAccountKey()).size(), 0);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment.getPaymentId().toString()).size(), 0);
+ Assert.assertEquals(invoicePaymentSqlDao.deleteInvoicePayment(invoicePayment.getPaymentId().toString()), 1);
+ Assert.assertNull(invoicePaymentSqlDao.getInvoicePayment(invoicePayment.getPaymentId().toString()));
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment.getAccountKey()).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
- final UUID attemptId1 = UUID.randomUUID();
+ final String extPaymentRefId1 = UUID.randomUUID().toString();
final String accountKey1 = UUID.randomUUID().toString();
- final BusinessInvoicePayment invoicePayment1 = createInvoicePayment(attemptId1, accountKey1);
- final UUID attemptId2 = UUID.randomUUID();
+ final BusinessInvoicePayment invoicePayment1 = createInvoicePayment(extPaymentRefId1, accountKey1);
+ final String extPaymentRefId2 = UUID.randomUUID().toString();
final String accountKey2 = UUID.randomUUID().toString();
- final BusinessInvoicePayment invoicePayment2 = createInvoicePayment(attemptId2, accountKey2);
+ final BusinessInvoicePayment invoicePayment2 = createInvoicePayment(extPaymentRefId2, accountKey2);
// Create both invoice payments
Assert.assertEquals(invoicePaymentSqlDao.createInvoicePayment(invoicePayment1), 1);
Assert.assertEquals(invoicePaymentSqlDao.createInvoicePayment(invoicePayment2), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment1.getAttemptId().toString()), invoicePayment1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment2.getAttemptId().toString()), invoicePayment2);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment1.getAccountKey()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment2.getAccountKey()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment1.getPaymentId().toString()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment2.getPaymentId().toString()).size(), 1);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePayment(invoicePayment1.getPaymentId().toString()), invoicePayment1);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePayment(invoicePayment2.getPaymentId().toString()), invoicePayment2);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment1.getAccountKey()).size(), 1);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment2.getAccountKey()).size(), 1);
// Remove the first invoice payment
- Assert.assertEquals(invoicePaymentSqlDao.deleteInvoicePaymentForPaymentAttempt(invoicePayment1.getAttemptId().toString()), 1);
-
- Assert.assertNull(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment1.getAttemptId().toString()));
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentForPaymentAttempt(invoicePayment2.getAttemptId().toString()), invoicePayment2);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment1.getAccountKey()).size(), 0);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccount(invoicePayment2.getAccountKey()).size(), 1);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment1.getPaymentId().toString()).size(), 0);
- Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForPayment(invoicePayment2.getPaymentId().toString()).size(), 1);
+ Assert.assertEquals(invoicePaymentSqlDao.deleteInvoicePayment(invoicePayment1.getPaymentId().toString()), 1);
+
+ Assert.assertNull(invoicePaymentSqlDao.getInvoicePayment(invoicePayment1.getPaymentId().toString()));
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePayment(invoicePayment2.getPaymentId().toString()), invoicePayment2);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment1.getAccountKey()).size(), 0);
+ Assert.assertEquals(invoicePaymentSqlDao.getInvoicePaymentsForAccountByKey(invoicePayment2.getAccountKey()).size(), 1);
}
@Test(groups = "slow")
@@ -116,7 +100,7 @@ public class TestBusinessInvoicePaymentSqlDao extends TestWithEmbeddedDB {
}
}
- private BusinessInvoicePayment createInvoicePayment(final UUID attemptId, final String accountKey) {
+ private BusinessInvoicePayment createInvoicePayment(final String extPaymentRefId, final String accountKey) {
final BigDecimal amount = BigDecimal.ONE;
final String cardCountry = UUID.randomUUID().toString().substring(0, 20);
final String cardType = UUID.randomUUID().toString().substring(0, 20);
@@ -132,12 +116,15 @@ public class TestBusinessInvoicePaymentSqlDao extends TestWithEmbeddedDB {
final String processingStatus = UUID.randomUUID().toString();
final BigDecimal requestedAmount = BigDecimal.ZERO;
final DateTime updatedDate = new DateTime(DateTimeZone.UTC);
+ final String invoicePaymentType = UUID.randomUUID().toString().substring(0, 10);
+ final UUID linkedInvoicePaymentId = UUID.randomUUID();
- return new BusinessInvoicePayment(accountKey, amount, attemptId,
+ return new BusinessInvoicePayment(accountKey, amount, extPaymentRefId,
cardCountry, cardType, createdDate,
currency, effectiveDate, invoiceId,
paymentError, paymentId, paymentMethod,
paymentType, pluginName, processingStatus,
- requestedAmount, updatedDate);
+ requestedAmount, updatedDate, invoicePaymentType,
+ linkedInvoicePaymentId);
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentTagSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentTagSqlDao.java
index 5ae8f48..2fa6025 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentTagSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoicePaymentTagSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoicePaymentTag;
-public class TestBusinessInvoicePaymentTagSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoicePaymentTagSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoicePaymentTagSqlDao invoicePaymentTagSqlDao;
@BeforeMethod(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceSqlDao.java
index 8373f81..226c058 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceSqlDao.java
@@ -26,11 +26,11 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoice;
import com.ning.billing.catalog.api.Currency;
-public class TestBusinessInvoiceSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoiceSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoiceSqlDao invoiceSqlDao;
@BeforeMethod(groups = "slow")
@@ -42,8 +42,9 @@ public class TestBusinessInvoiceSqlDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testCRUD() throws Exception {
final UUID invoiceId = UUID.randomUUID();
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
- final BusinessInvoice invoice = createInvoice(invoiceId, accountKey);
+ final BusinessInvoice invoice = createInvoice(accountId, invoiceId, accountKey);
// Verify initial state
Assert.assertNull(invoiceSqlDao.getInvoice(invoice.getInvoiceId().toString()));
@@ -54,43 +55,38 @@ public class TestBusinessInvoiceSqlDao extends TestWithEmbeddedDB {
// Retrieve it
Assert.assertEquals(invoiceSqlDao.getInvoice(invoice.getInvoiceId().toString()), invoice);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountKey()).size(), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountKey()).get(0), invoice);
-
- // Update and retrieve it
- invoice.setInvoiceDate(new DateTime(DateTimeZone.UTC));
- Assert.assertEquals(invoiceSqlDao.updateInvoice(invoice), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoice(invoice.getInvoiceId().toString()), invoice);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountKey()).size(), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountKey()).get(0), invoice);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountId().toString()).size(), 1);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountId().toString()).get(0), invoice);
// Delete it
Assert.assertEquals(invoiceSqlDao.deleteInvoice(invoice.getInvoiceId().toString()), 1);
Assert.assertNull(invoiceSqlDao.getInvoice(invoice.getInvoiceId().toString()));
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountKey()).size(), 0);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(invoice.getAccountId().toString()).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
final UUID invoiceId1 = UUID.randomUUID();
+ final UUID accountId1 = UUID.randomUUID();
final String accountKey1 = UUID.randomUUID().toString();
- final BusinessInvoice invoice1 = createInvoice(invoiceId1, accountKey1);
+ final BusinessInvoice invoice1 = createInvoice(invoiceId1, accountId1, accountKey1);
final UUID invoiceId2 = UUID.randomUUID();
+ final UUID accountId2 = UUID.randomUUID();
final String accountKey2 = UUID.randomUUID().toString();
- final BusinessInvoice invoice2 = createInvoice(invoiceId2, accountKey2);
+ final BusinessInvoice invoice2 = createInvoice(invoiceId2, accountId2, accountKey2);
// Create both invoices
Assert.assertEquals(invoiceSqlDao.createInvoice(invoice1), 1);
Assert.assertEquals(invoiceSqlDao.createInvoice(invoice2), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountKey1).size(), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountId1.toString()).size(), 1);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountId2.toString()).size(), 1);
// Remove the first invoice
Assert.assertEquals(invoiceSqlDao.deleteInvoice(invoice1.getInvoiceId().toString()), 1);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountKey1).size(), 0);
- Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountKey2).size(), 1);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountId1.toString()).size(), 0);
+ Assert.assertEquals(invoiceSqlDao.getInvoicesForAccount(accountId2.toString()).size(), 1);
}
@Test(groups = "slow")
@@ -103,7 +99,7 @@ public class TestBusinessInvoiceSqlDao extends TestWithEmbeddedDB {
}
}
- private BusinessInvoice createInvoice(final UUID invoiceId, final String accountKey) {
+ private BusinessInvoice createInvoice(final UUID invoiceId, final UUID accountId, final String accountKey) {
final BigDecimal amountCharged = BigDecimal.ZERO;
final BigDecimal amountCredited = BigDecimal.ONE;
final BigDecimal amountPaid = BigDecimal.TEN;
@@ -114,7 +110,7 @@ public class TestBusinessInvoiceSqlDao extends TestWithEmbeddedDB {
final DateTime targetDate = new DateTime(DateTimeZone.UTC);
final DateTime updatedDate = new DateTime(DateTimeZone.UTC);
- return new BusinessInvoice(accountKey, amountCharged, amountCredited, amountPaid, balance,
- createdDate, currency, invoiceDate, invoiceId, targetDate, updatedDate);
+ return new BusinessInvoice(accountId, accountKey, amountCharged, amountCredited, amountPaid, balance,
+ createdDate, currency, invoiceDate, invoiceId, 12, targetDate, updatedDate);
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceTagSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceTagSqlDao.java
index 24ee93f..2c30a46 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceTagSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessInvoiceTagSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessInvoiceTag;
-public class TestBusinessInvoiceTagSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessInvoiceTagSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessInvoiceTagSqlDao invoiceTagSqlDao;
@BeforeMethod(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessOverdueStatusSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessOverdueStatusSqlDao.java
index c16ab3c..5db58e3 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessOverdueStatusSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessOverdueStatusSqlDao.java
@@ -25,10 +25,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessOverdueStatus;
-public class TestBusinessOverdueStatusSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessOverdueStatusSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessOverdueStatusSqlDao overdueStatusSqlDao;
@BeforeMethod(groups = "slow")
@@ -39,27 +39,29 @@ public class TestBusinessOverdueStatusSqlDao extends TestWithEmbeddedDB {
@Test(groups = "slow")
public void testCreate() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final String externalKey = UUID.randomUUID().toString();
- final BusinessOverdueStatus firstOverdueStatus = createOverdueStatus(externalKey);
+ final BusinessOverdueStatus firstOverdueStatus = createOverdueStatus(accountKey, bundleId, externalKey);
// Verify initial state
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).size(), 0);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).size(), 0);
// Add the overdue status
Assert.assertEquals(overdueStatusSqlDao.createOverdueStatus(firstOverdueStatus), 1);
// Retrieve it
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).size(), 1);
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).get(0), firstOverdueStatus);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).size(), 1);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).get(0), firstOverdueStatus);
// Add a second one
- final BusinessOverdueStatus secondOverdueStatus = createOverdueStatus(externalKey);
+ final BusinessOverdueStatus secondOverdueStatus = createOverdueStatus(accountKey, bundleId, externalKey);
Assert.assertEquals(overdueStatusSqlDao.createOverdueStatus(secondOverdueStatus), 1);
// Retrieve both
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).size(), 2);
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).get(0), firstOverdueStatus);
- Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundle(externalKey).get(1), secondOverdueStatus);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).size(), 2);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).get(0), firstOverdueStatus);
+ Assert.assertEquals(overdueStatusSqlDao.getOverdueStatusesForBundleByKey(externalKey).get(1), secondOverdueStatus);
}
@Test(groups = "slow")
@@ -72,11 +74,11 @@ public class TestBusinessOverdueStatusSqlDao extends TestWithEmbeddedDB {
}
}
- private BusinessOverdueStatus createOverdueStatus(final String externalKey) {
+ private BusinessOverdueStatus createOverdueStatus(final String accountKey, final UUID bundleId, final String externalKey) {
final DateTime endDate = new DateTime(DateTimeZone.UTC);
final DateTime startDate = new DateTime(DateTimeZone.UTC);
final String status = UUID.randomUUID().toString();
- return new BusinessOverdueStatus(endDate, externalKey, startDate, status);
+ return new BusinessOverdueStatus(accountKey, bundleId, endDate, externalKey, startDate, status);
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionFieldSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionFieldSqlDao.java
index 5233229..aac2fde 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionFieldSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionFieldSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessSubscriptionTransitionField;
-public class TestBusinessSubscriptionTransitionFieldSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessSubscriptionTransitionFieldSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessSubscriptionTransitionFieldSqlDao subscriptionTransitionFieldSqlDao;
@BeforeMethod(groups = "slow")
@@ -38,49 +38,55 @@ public class TestBusinessSubscriptionTransitionFieldSqlDao extends TestWithEmbed
@Test(groups = "slow")
public void testCRUD() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final String externalKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString().substring(0, 30);
final String value = UUID.randomUUID().toString();
// Verify initial state
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey).size(), 0);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(externalKey, name), 0);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(bundleId.toString(), name), 0);
// Add an entry
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(externalKey, name, value), 1);
- final List<BusinessSubscriptionTransitionField> fieldsForBusinessSubscriptionTransition = subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(accountKey, bundleId.toString(), externalKey, name, value), 1);
+ final List<BusinessSubscriptionTransitionField> fieldsForBusinessSubscriptionTransition = subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey);
Assert.assertEquals(fieldsForBusinessSubscriptionTransition.size(), 1);
// Retrieve it
final BusinessSubscriptionTransitionField subscriptionTransitionField = fieldsForBusinessSubscriptionTransition.get(0);
+ Assert.assertEquals(subscriptionTransitionField.getBundleId(), bundleId);
Assert.assertEquals(subscriptionTransitionField.getExternalKey(), externalKey);
Assert.assertEquals(subscriptionTransitionField.getName(), name);
Assert.assertEquals(subscriptionTransitionField.getValue(), value);
// Delete it
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(externalKey, name), 1);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(bundleId.toString(), name), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId1 = UUID.randomUUID();
final String externalKey1 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString().substring(0, 30);
+ final UUID bundleId2 = UUID.randomUUID();
final String externalKey2 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString().substring(0, 30);
// Add a field to both transitions
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(externalKey1, name1, UUID.randomUUID().toString()), 1);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(externalKey2, name2, UUID.randomUUID().toString()), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(accountKey, bundleId1.toString(), externalKey1, name1, UUID.randomUUID().toString()), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.addField(accountKey, bundleId2.toString(), externalKey2, name2, UUID.randomUUID().toString()), 1);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey1).size(), 1);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey2).size(), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey1).size(), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey2).size(), 1);
// Remove the field for the first transition
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(externalKey1, name1), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.removeField(bundleId1.toString(), name1), 1);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey1).size(), 0);
- Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransition(externalKey2).size(), 1);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey1).size(), 0);
+ Assert.assertEquals(subscriptionTransitionFieldSqlDao.getFieldsForBusinessSubscriptionTransitionByKey(externalKey2).size(), 1);
}
@Test(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionTagSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionTagSqlDao.java
index 8b4740f..60209fd 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionTagSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/dao/TestBusinessSubscriptionTransitionTagSqlDao.java
@@ -24,10 +24,10 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.ning.billing.analytics.TestWithEmbeddedDB;
+import com.ning.billing.analytics.AnalyticsTestSuiteWithEmbeddedDB;
import com.ning.billing.analytics.model.BusinessSubscriptionTransitionTag;
-public class TestBusinessSubscriptionTransitionTagSqlDao extends TestWithEmbeddedDB {
+public class TestBusinessSubscriptionTransitionTagSqlDao extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessSubscriptionTransitionTagSqlDao subscriptionTransitionTagSqlDao;
@BeforeMethod(groups = "slow")
@@ -38,47 +38,53 @@ public class TestBusinessSubscriptionTransitionTagSqlDao extends TestWithEmbedde
@Test(groups = "slow")
public void testCRUD() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final String externalKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString().substring(0, 20);
// Verify initial state
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey).size(), 0);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(externalKey, name), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(bundleId.toString(), name), 0);
// Add an entry
- Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(externalKey, name), 1);
- final List<BusinessSubscriptionTransitionTag> tagsForBusinessSubscriptionTransition = subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(accountKey, bundleId.toString(), externalKey, name), 1);
+ final List<BusinessSubscriptionTransitionTag> tagsForBusinessSubscriptionTransition = subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey);
Assert.assertEquals(tagsForBusinessSubscriptionTransition.size(), 1);
// Retrieve it
final BusinessSubscriptionTransitionTag subscriptionTransitionTag = tagsForBusinessSubscriptionTransition.get(0);
+ Assert.assertEquals(subscriptionTransitionTag.getBundleId(), bundleId);
Assert.assertEquals(subscriptionTransitionTag.getExternalKey(), externalKey);
Assert.assertEquals(subscriptionTransitionTag.getName(), name);
// Delete it
- Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(externalKey, name), 1);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(bundleId.toString(), name), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
}
@Test(groups = "slow")
public void testSegmentation() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId1 = UUID.randomUUID();
final String externalKey1 = UUID.randomUUID().toString();
final String name1 = UUID.randomUUID().toString().substring(0, 20);
+ final UUID bundleId2 = UUID.randomUUID();
final String externalKey2 = UUID.randomUUID().toString();
final String name2 = UUID.randomUUID().toString().substring(0, 20);
// Add a tag to both transitions
- Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(externalKey1, name1), 1);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(externalKey2, name2), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(accountKey, bundleId1.toString(), externalKey1, name1), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.addTag(accountKey, bundleId2.toString(), externalKey2, name2), 1);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey1).size(), 1);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey2).size(), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey1).size(), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey2).size(), 1);
// Remove the tag for the first transition
- Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(externalKey1, name1), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.removeTag(bundleId1.toString(), name1), 1);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey1).size(), 0);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey2).size(), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey1).size(), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey2).size(), 1);
}
@Test(groups = "slow")
diff --git a/analytics/src/test/java/com/ning/billing/analytics/MockBusinessSubscriptionTransitionSqlDao.java b/analytics/src/test/java/com/ning/billing/analytics/MockBusinessSubscriptionTransitionSqlDao.java
index a442f2a..2269957 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/MockBusinessSubscriptionTransitionSqlDao.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/MockBusinessSubscriptionTransitionSqlDao.java
@@ -21,30 +21,79 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.skife.jdbi.v2.Transaction;
import org.skife.jdbi.v2.sqlobject.Bind;
+import org.testng.Assert;
+import com.google.common.collect.ImmutableList;
import com.ning.billing.analytics.dao.BusinessSubscriptionTransitionBinder;
import com.ning.billing.analytics.dao.BusinessSubscriptionTransitionSqlDao;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
public class MockBusinessSubscriptionTransitionSqlDao implements BusinessSubscriptionTransitionSqlDao {
private final Map<String, List<BusinessSubscriptionTransition>> content = new HashMap<String, List<BusinessSubscriptionTransition>>();
+ private final Map<String, String> keyForBundleId = new HashMap<String, String>();
@Override
- public List<BusinessSubscriptionTransition> getTransitions(@Bind("event_key") final String key) {
+ public List<BusinessSubscriptionTransition> getTransitionsByKey(@Bind("event_key") final String key) {
return content.get(key);
}
@Override
+ public List<BusinessSubscriptionTransition> getTransitionForSubscription(@Bind("subscription_id") final String subscriptionId) {
+ return ImmutableList.<BusinessSubscriptionTransition>of();
+ }
+
+ @Override
public int createTransition(@BusinessSubscriptionTransitionBinder final BusinessSubscriptionTransition transition) {
if (content.get(transition.getExternalKey()) == null) {
content.put(transition.getExternalKey(), new ArrayList<BusinessSubscriptionTransition>());
}
content.get(transition.getExternalKey()).add(transition);
+ keyForBundleId.put(transition.getBundleId().toString(), transition.getExternalKey());
return 1;
}
@Override
+ public void deleteTransitionsForBundle(@Bind("bundle_id") final String bundleId) {
+ content.put(keyForBundleId.get(bundleId), new ArrayList<BusinessSubscriptionTransition>());
+ }
+
+ @Override
public void test() {
}
+
+ @Override
+ public void begin() {
+ }
+
+ @Override
+ public void commit() {
+ }
+
+ @Override
+ public void rollback() {
+ }
+
+ @Override
+ public void checkpoint(final String name) {
+ }
+
+ @Override
+ public void release(final String name) {
+ }
+
+ @Override
+ public void rollback(final String name) {
+ }
+
+ @Override
+ public <ReturnType> ReturnType inTransaction(final Transaction<ReturnType, BusinessSubscriptionTransitionSqlDao> func) {
+ try {
+ return func.inTransaction(this, null);
+ } catch (Exception e) {
+ Assert.fail(e.toString());
+ return null;
+ }
+ }
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccount.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccount.java
index 1a37ea8..88329f7 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccount.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccount.java
@@ -25,14 +25,14 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ning.billing.analytics.AnalyticsTestSuite;
-import com.ning.billing.analytics.model.BusinessAccount;
public class TestBusinessAccount extends AnalyticsTestSuite {
private BusinessAccount account;
@BeforeMethod(groups = "fast")
public void setUp() throws Exception {
- account = new BusinessAccount("pierre", UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(), BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "");
+ account = new BusinessAccount(UUID.randomUUID(), "pierre", UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(),
+ BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "");
}
@Test(groups = "fast")
@@ -41,7 +41,8 @@ public class TestBusinessAccount extends AnalyticsTestSuite {
Assert.assertEquals(account, account);
Assert.assertTrue(account.equals(account));
- final BusinessAccount otherAccount = new BusinessAccount("pierre cardin", UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(), BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "");
+ final BusinessAccount otherAccount = new BusinessAccount(UUID.randomUUID(), "pierre cardin", UUID.randomUUID().toString(), BigDecimal.ONE, new DateTime(),
+ BigDecimal.TEN, "ERROR_NOT_ENOUGH_FUNDS", "CreditCard", "Visa", "");
Assert.assertFalse(account.equals(otherAccount));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountField.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountField.java
index ebe3c9e..86ce86c 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountField.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountField.java
@@ -26,20 +26,24 @@ import com.ning.billing.analytics.AnalyticsTestSuite;
public class TestBusinessAccountField extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
final String value = UUID.randomUUID().toString();
- final BusinessAccountField accountField = new BusinessAccountField(accountKey,
+ final BusinessAccountField accountField = new BusinessAccountField(accountId,
+ accountKey,
name,
value);
Assert.assertSame(accountField, accountField);
Assert.assertEquals(accountField, accountField);
Assert.assertTrue(accountField.equals(accountField));
+ Assert.assertEquals(accountField.getAccountId(), accountId);
Assert.assertEquals(accountField.getAccountKey(), accountKey);
Assert.assertEquals(accountField.getName(), name);
Assert.assertEquals(accountField.getValue(), value);
- final BusinessAccountField otherAccountField = new BusinessAccountField(UUID.randomUUID().toString(),
+ final BusinessAccountField otherAccountField = new BusinessAccountField(UUID.randomUUID(),
+ UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString());
Assert.assertFalse(accountField.equals(otherAccountField));
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountTag.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountTag.java
index 1d9c072..4d0014e 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountTag.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessAccountTag.java
@@ -26,16 +26,18 @@ import com.ning.billing.analytics.AnalyticsTestSuite;
public class TestBusinessAccountTag extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
- final BusinessAccountTag accountTag = new BusinessAccountTag(accountKey, name);
+ final BusinessAccountTag accountTag = new BusinessAccountTag(accountId, accountKey, name);
Assert.assertSame(accountTag, accountTag);
Assert.assertEquals(accountTag, accountTag);
Assert.assertTrue(accountTag.equals(accountTag));
+ Assert.assertEquals(accountTag.getAccountId(), accountId);
Assert.assertEquals(accountTag.getAccountKey(), accountKey);
Assert.assertEquals(accountTag.getName(), name);
- final BusinessAccountTag otherAccountTag = new BusinessAccountTag(UUID.randomUUID().toString(), UUID.randomUUID().toString());
+ final BusinessAccountTag otherAccountTag = new BusinessAccountTag(UUID.randomUUID(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
Assert.assertFalse(accountTag.equals(otherAccountTag));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoice.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoice.java
index 869284d..9ec77f2 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoice.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoice.java
@@ -30,6 +30,7 @@ import com.ning.billing.catalog.api.Currency;
public class TestBusinessInvoice extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final UUID accountId = UUID.randomUUID();
final String accountKey = UUID.randomUUID().toString();
final BigDecimal amountCharged = BigDecimal.ZERO;
final BigDecimal amountCredited = BigDecimal.ONE;
@@ -39,13 +40,15 @@ public class TestBusinessInvoice extends AnalyticsTestSuite {
final Currency currency = Currency.MXN;
final DateTime invoiceDate = new DateTime(DateTimeZone.UTC);
final UUID invoiceId = UUID.randomUUID();
+ final Integer invoiceNumber = 15;
final DateTime targetDate = new DateTime(DateTimeZone.UTC);
final DateTime updatedDate = new DateTime(DateTimeZone.UTC);
- final BusinessInvoice invoice = new BusinessInvoice(accountKey, amountCharged, amountCredited, amountPaid, balance,
- createdDate, currency, invoiceDate, invoiceId, targetDate, updatedDate);
+ final BusinessInvoice invoice = new BusinessInvoice(accountId, accountKey, amountCharged, amountCredited, amountPaid, balance,
+ createdDate, currency, invoiceDate, invoiceId, invoiceNumber, targetDate, updatedDate);
Assert.assertSame(invoice, invoice);
Assert.assertEquals(invoice, invoice);
Assert.assertTrue(invoice.equals(invoice));
+ Assert.assertEquals(invoice.getAccountId(), accountId);
Assert.assertEquals(invoice.getAccountKey(), accountKey);
Assert.assertEquals(invoice.getAmountCharged(), amountCharged);
Assert.assertEquals(invoice.getAmountCredited(), amountCredited);
@@ -55,23 +58,12 @@ public class TestBusinessInvoice extends AnalyticsTestSuite {
Assert.assertEquals(invoice.getCurrency(), currency);
Assert.assertEquals(invoice.getInvoiceDate(), invoiceDate);
Assert.assertEquals(invoice.getInvoiceId(), invoiceId);
+ Assert.assertEquals(invoice.getInvoiceNumber(), invoiceNumber);
Assert.assertEquals(invoice.getTargetDate(), targetDate);
Assert.assertEquals(invoice.getUpdatedDate(), updatedDate);
- final BusinessInvoice otherInvoice = new BusinessInvoice(null, null, null, null, null, createdDate, null,
- null, invoiceId, null, null);
+ final BusinessInvoice otherInvoice = new BusinessInvoice(null, null, null, null, null, null, createdDate, null,
+ null, invoiceId, 0, null, null);
Assert.assertFalse(invoice.equals(otherInvoice));
-
- // Test setters
- otherInvoice.setAccountKey(accountKey);
- otherInvoice.setAmountCharged(amountCharged);
- otherInvoice.setAmountCredited(amountCredited);
- otherInvoice.setAmountPaid(amountPaid);
- otherInvoice.setBalance(balance);
- otherInvoice.setCurrency(currency);
- otherInvoice.setInvoiceDate(invoiceDate);
- otherInvoice.setTargetDate(targetDate);
- otherInvoice.setUpdatedDate(updatedDate);
- Assert.assertTrue(invoice.equals(otherInvoice));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoiceItem.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoiceItem.java
index e4460f6..50fac73 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoiceItem.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoiceItem.java
@@ -73,22 +73,5 @@ public class TestBusinessInvoiceItem extends AnalyticsTestSuite {
final BusinessInvoiceItem otherInvoiceItem = new BusinessInvoiceItem(null, null, createdDate, null, null, null, null, itemId,
null, null, null, null, null, null, null, null);
Assert.assertFalse(invoiceItem.equals(otherInvoiceItem));
-
- // Test setters
- otherInvoiceItem.setAmount(amount);
- otherInvoiceItem.setBillingPeriod(billingPeriod);
- otherInvoiceItem.setCurrency(currency);
- otherInvoiceItem.setEndDate(endDate);
- otherInvoiceItem.setExternalKey(externalKey);
- otherInvoiceItem.setInvoiceId(invoiceId);
- otherInvoiceItem.setItemType(itemType);
- otherInvoiceItem.setPhase(phase);
- otherInvoiceItem.setProductCategory(productCategory);
- otherInvoiceItem.setProductName(productName);
- otherInvoiceItem.setProductType(productType);
- otherInvoiceItem.setSlug(slug);
- otherInvoiceItem.setStartDate(startDate);
- otherInvoiceItem.setUpdatedDate(updatedDate);
- Assert.assertTrue(invoiceItem.equals(otherInvoiceItem));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoicePayment.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoicePayment.java
index 709db0f..ce31865 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoicePayment.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessInvoicePayment.java
@@ -32,7 +32,7 @@ public class TestBusinessInvoicePayment extends AnalyticsTestSuite {
public void testEquals() throws Exception {
final String accountKey = UUID.randomUUID().toString();
final BigDecimal amount = BigDecimal.ONE;
- final UUID attemptId = UUID.randomUUID();
+ final String extPaymentRefId = UUID.randomUUID().toString();
final String cardCountry = UUID.randomUUID().toString();
final String cardType = UUID.randomUUID().toString();
final DateTime createdDate = new DateTime(DateTimeZone.UTC);
@@ -47,18 +47,21 @@ public class TestBusinessInvoicePayment extends AnalyticsTestSuite {
final String processingStatus = UUID.randomUUID().toString();
final BigDecimal requestedAmount = BigDecimal.ZERO;
final DateTime updatedDate = new DateTime(DateTimeZone.UTC);
- final BusinessInvoicePayment invoicePayment = new BusinessInvoicePayment(accountKey, amount, attemptId,
+ final String invoicePaymentType = UUID.randomUUID().toString();
+ final UUID linkedInvoicePaymentId = UUID.randomUUID();
+ final BusinessInvoicePayment invoicePayment = new BusinessInvoicePayment(accountKey, amount, extPaymentRefId,
cardCountry, cardType, createdDate,
currency, effectiveDate, invoiceId,
paymentError, paymentId, paymentMethod,
paymentType, pluginName, processingStatus,
- requestedAmount, updatedDate);
+ requestedAmount, updatedDate, invoicePaymentType,
+ linkedInvoicePaymentId);
Assert.assertSame(invoicePayment, invoicePayment);
Assert.assertEquals(invoicePayment, invoicePayment);
Assert.assertTrue(invoicePayment.equals(invoicePayment));
Assert.assertEquals(invoicePayment.getAccountKey(), accountKey);
Assert.assertEquals(invoicePayment.getAmount(), amount);
- Assert.assertEquals(invoicePayment.getAttemptId(), attemptId);
+ Assert.assertEquals(invoicePayment.getExtPaymentRefId(), extPaymentRefId);
Assert.assertEquals(invoicePayment.getCardCountry(), cardCountry);
Assert.assertEquals(invoicePayment.getCardType(), cardType);
Assert.assertEquals(invoicePayment.getCreatedDate(), createdDate);
@@ -73,27 +76,12 @@ public class TestBusinessInvoicePayment extends AnalyticsTestSuite {
Assert.assertEquals(invoicePayment.getProcessingStatus(), processingStatus);
Assert.assertEquals(invoicePayment.getRequestedAmount(), requestedAmount);
Assert.assertEquals(invoicePayment.getUpdatedDate(), updatedDate);
+ Assert.assertEquals(invoicePayment.getInvoicePaymentType(), invoicePaymentType);
+ Assert.assertEquals(invoicePayment.getLinkedInvoicePaymentId(), linkedInvoicePaymentId);
- final BusinessInvoicePayment otherInvoicePayment = new BusinessInvoicePayment(null, null, attemptId, null, null, createdDate,
+ final BusinessInvoicePayment otherInvoicePayment = new BusinessInvoicePayment(null, null, extPaymentRefId, null, null, createdDate,
null, null, null, null, paymentId, null,
- null, null, null, null, null);
+ null, null, null, null, null, null, null);
Assert.assertFalse(invoicePayment.equals(otherInvoicePayment));
-
- // Test setters
- otherInvoicePayment.setAccountKey(accountKey);
- otherInvoicePayment.setAmount(amount);
- otherInvoicePayment.setCardCountry(cardCountry);
- otherInvoicePayment.setCardType(cardType);
- otherInvoicePayment.setCurrency(currency);
- otherInvoicePayment.setEffectiveDate(effectiveDate);
- otherInvoicePayment.setInvoiceId(invoiceId);
- otherInvoicePayment.setPaymentError(paymentError);
- otherInvoicePayment.setPaymentMethod(paymentMethod);
- otherInvoicePayment.setPaymentType(paymentType);
- otherInvoicePayment.setPluginName(pluginName);
- otherInvoicePayment.setProcessingStatus(processingStatus);
- otherInvoicePayment.setRequestedAmount(requestedAmount);
- otherInvoicePayment.setUpdatedDate(updatedDate);
- Assert.assertTrue(invoicePayment.equals(otherInvoicePayment));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessOverdueStatus.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessOverdueStatus.java
index b92ee12..be467e9 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessOverdueStatus.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessOverdueStatus.java
@@ -28,21 +28,29 @@ import com.ning.billing.analytics.AnalyticsTestSuite;
public class TestBusinessOverdueStatus extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final DateTime endDate = new DateTime(DateTimeZone.UTC);
final String externalKey = UUID.randomUUID().toString();
final DateTime startDate = new DateTime(DateTimeZone.UTC);
final String status = UUID.randomUUID().toString();
- final BusinessOverdueStatus overdueStatus = new BusinessOverdueStatus(endDate, externalKey, startDate, status);
+ final BusinessOverdueStatus overdueStatus = new BusinessOverdueStatus(accountKey, bundleId, endDate, externalKey, startDate, status);
Assert.assertSame(overdueStatus, overdueStatus);
Assert.assertEquals(overdueStatus, overdueStatus);
Assert.assertTrue(overdueStatus.equals(overdueStatus));
+ Assert.assertEquals(overdueStatus.getAccountKey(), accountKey);
+ Assert.assertEquals(overdueStatus.getBundleId(), bundleId);
Assert.assertEquals(overdueStatus.getEndDate(), endDate);
Assert.assertEquals(overdueStatus.getExternalKey(), externalKey);
Assert.assertEquals(overdueStatus.getStartDate(), startDate);
Assert.assertEquals(overdueStatus.getStatus(), status);
- final BusinessOverdueStatus otherOverdueStatus = new BusinessOverdueStatus(new DateTime(DateTimeZone.UTC), UUID.randomUUID().toString(),
- new DateTime(DateTimeZone.UTC), UUID.randomUUID().toString());
+ final BusinessOverdueStatus otherOverdueStatus = new BusinessOverdueStatus(UUID.randomUUID().toString(),
+ UUID.randomUUID(),
+ new DateTime(DateTimeZone.UTC),
+ UUID.randomUUID().toString(),
+ new DateTime(DateTimeZone.UTC),
+ UUID.randomUUID().toString());
Assert.assertFalse(overdueStatus.equals(otherOverdueStatus));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscription.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscription.java
index c102d35..7a2cbd7 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscription.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscription.java
@@ -27,10 +27,7 @@ import org.testng.annotations.Test;
import com.ning.billing.analytics.AnalyticsTestSuite;
import com.ning.billing.analytics.MockDuration;
import com.ning.billing.analytics.MockPhase;
-import com.ning.billing.analytics.MockPlan;
import com.ning.billing.analytics.MockProduct;
-import com.ning.billing.analytics.MockSubscription;
-import com.ning.billing.analytics.model.BusinessSubscription;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.Duration;
@@ -40,6 +37,8 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.mock.MockPlan;
+import com.ning.billing.mock.MockSubscription;
import static com.ning.billing.catalog.api.Currency.USD;
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionEvent.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionEvent.java
index 11c6215..de713a8 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionEvent.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionEvent.java
@@ -25,10 +25,7 @@ import org.testng.annotations.Test;
import com.ning.billing.analytics.AnalyticsTestSuite;
import com.ning.billing.analytics.MockDuration;
import com.ning.billing.analytics.MockPhase;
-import com.ning.billing.analytics.MockPlan;
import com.ning.billing.analytics.MockProduct;
-import com.ning.billing.analytics.MockSubscription;
-import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.PhaseType;
@@ -37,6 +34,8 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.mock.MockPlan;
+import com.ning.billing.mock.MockSubscription;
public class TestBusinessSubscriptionEvent extends AnalyticsTestSuite {
private Product product;
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransition.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransition.java
index 4c401a6..3e237bc 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransition.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransition.java
@@ -16,6 +16,8 @@
package com.ning.billing.analytics.model;
+import java.util.UUID;
+
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.mockito.Mockito;
@@ -26,12 +28,7 @@ import org.testng.annotations.Test;
import com.ning.billing.analytics.AnalyticsTestSuite;
import com.ning.billing.analytics.MockDuration;
import com.ning.billing.analytics.MockPhase;
-import com.ning.billing.analytics.MockPlan;
import com.ning.billing.analytics.MockProduct;
-import com.ning.billing.analytics.MockSubscription;
-import com.ning.billing.analytics.model.BusinessSubscription;
-import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
-import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.PhaseType;
@@ -40,6 +37,8 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.mock.MockPlan;
+import com.ning.billing.mock.MockSubscription;
import static com.ning.billing.catalog.api.Currency.USD;
@@ -49,8 +48,11 @@ public class TestBusinessSubscriptionTransition extends AnalyticsTestSuite {
private BusinessSubscriptionEvent event;
private DateTime requestedTimestamp;
private Long totalOrdering;
+ private UUID bundleId;
private String externalKey;
+ private UUID accountId;
private String accountKey;
+ private UUID subscriptionId;
private BusinessSubscriptionTransition transition;
private final CatalogService catalogService = Mockito.mock(CatalogService.class);
@@ -75,9 +77,13 @@ public class TestBusinessSubscriptionTransition extends AnalyticsTestSuite {
event = BusinessSubscriptionEvent.subscriptionCancelled(prevISubscription.getCurrentPlan().getName(), catalog, now, now);
requestedTimestamp = new DateTime(DateTimeZone.UTC);
totalOrdering = 12L;
+ bundleId = UUID.randomUUID();
externalKey = "1234";
+ accountId = UUID.randomUUID();
accountKey = "pierre-1234";
- transition = new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, requestedTimestamp, event, prevSubscription, nextSubscription);
+ subscriptionId = UUID.randomUUID();
+ transition = new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, prevSubscription, nextSubscription);
}
@Test(groups = "fast")
@@ -96,47 +102,56 @@ public class TestBusinessSubscriptionTransition extends AnalyticsTestSuite {
BusinessSubscriptionTransition otherTransition;
- otherTransition = new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, new DateTime(), event, prevSubscription, nextSubscription);
+ otherTransition = new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, new DateTime(), event, prevSubscription, nextSubscription);
Assert.assertTrue(!transition.equals(otherTransition));
- otherTransition = new BusinessSubscriptionTransition(totalOrdering, "12345", accountKey, requestedTimestamp, event, prevSubscription, nextSubscription);
+ otherTransition = new BusinessSubscriptionTransition(totalOrdering, bundleId, "12345", accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, prevSubscription, nextSubscription);
Assert.assertTrue(!transition.equals(otherTransition));
- otherTransition = new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, requestedTimestamp, event, prevSubscription, prevSubscription);
+ otherTransition = new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, prevSubscription, prevSubscription);
Assert.assertTrue(!transition.equals(otherTransition));
- otherTransition = new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, requestedTimestamp, event, nextSubscription, nextSubscription);
+ otherTransition = new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, nextSubscription, nextSubscription);
Assert.assertTrue(!transition.equals(otherTransition));
- otherTransition = new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, requestedTimestamp, event, nextSubscription, prevSubscription);
+ otherTransition = new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, nextSubscription, prevSubscription);
Assert.assertTrue(!transition.equals(otherTransition));
}
@Test(groups = "fast")
public void testRejectInvalidTransitions() throws Exception {
try {
- new BusinessSubscriptionTransition(null, externalKey, accountKey, requestedTimestamp, event, prevSubscription, nextSubscription);
+ new BusinessSubscriptionTransition(null, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, prevSubscription, nextSubscription);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
}
try {
- new BusinessSubscriptionTransition(totalOrdering, null, accountKey, requestedTimestamp, event, prevSubscription, nextSubscription);
+ new BusinessSubscriptionTransition(totalOrdering, bundleId, null, accountId, accountKey,
+ subscriptionId, requestedTimestamp, event, prevSubscription, nextSubscription);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
}
try {
- new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, null, event, prevSubscription, nextSubscription);
+ new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, null, event, prevSubscription, nextSubscription);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
}
try {
- new BusinessSubscriptionTransition(totalOrdering, externalKey, accountKey, requestedTimestamp, null, prevSubscription, nextSubscription);
+ new BusinessSubscriptionTransition(totalOrdering, bundleId, externalKey, accountId, accountKey,
+ subscriptionId, requestedTimestamp, null, prevSubscription, nextSubscription);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionField.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionField.java
index 5a1e31b..18a46f3 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionField.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionField.java
@@ -26,20 +26,28 @@ import com.ning.billing.analytics.AnalyticsTestSuite;
public class TestBusinessSubscriptionTransitionField extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final String externalKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
final String value = UUID.randomUUID().toString();
- final BusinessSubscriptionTransitionField subscriptionTransitionField = new BusinessSubscriptionTransitionField(externalKey,
+ final BusinessSubscriptionTransitionField subscriptionTransitionField = new BusinessSubscriptionTransitionField(accountKey,
+ bundleId,
+ externalKey,
name,
value);
Assert.assertSame(subscriptionTransitionField, subscriptionTransitionField);
Assert.assertEquals(subscriptionTransitionField, subscriptionTransitionField);
Assert.assertTrue(subscriptionTransitionField.equals(subscriptionTransitionField));
+ Assert.assertEquals(subscriptionTransitionField.getAccountKey(), accountKey);
+ Assert.assertEquals(subscriptionTransitionField.getBundleId(), bundleId);
Assert.assertEquals(subscriptionTransitionField.getExternalKey(), externalKey);
Assert.assertEquals(subscriptionTransitionField.getName(), name);
Assert.assertEquals(subscriptionTransitionField.getValue(), value);
final BusinessSubscriptionTransitionField otherSubscriptionField = new BusinessSubscriptionTransitionField(UUID.randomUUID().toString(),
+ UUID.randomUUID(),
+ UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString());
Assert.assertFalse(subscriptionTransitionField.equals(otherSubscriptionField));
diff --git a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionTag.java b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionTag.java
index b5a40d1..66c2da8 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionTag.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/model/TestBusinessSubscriptionTransitionTag.java
@@ -26,16 +26,26 @@ import com.ning.billing.analytics.AnalyticsTestSuite;
public class TestBusinessSubscriptionTransitionTag extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testEquals() throws Exception {
+ final String accountKey = UUID.randomUUID().toString();
+ final UUID bundleId = UUID.randomUUID();
final String externalKey = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
- final BusinessSubscriptionTransitionTag subscriptionTransitionTag = new BusinessSubscriptionTransitionTag(externalKey, name);
+ final BusinessSubscriptionTransitionTag subscriptionTransitionTag = new BusinessSubscriptionTransitionTag(accountKey,
+ bundleId,
+ externalKey,
+ name);
Assert.assertSame(subscriptionTransitionTag, subscriptionTransitionTag);
Assert.assertEquals(subscriptionTransitionTag, subscriptionTransitionTag);
Assert.assertTrue(subscriptionTransitionTag.equals(subscriptionTransitionTag));
+ Assert.assertEquals(subscriptionTransitionTag.getAccountKey(), accountKey);
+ Assert.assertEquals(subscriptionTransitionTag.getBundleId(), bundleId);
Assert.assertEquals(subscriptionTransitionTag.getExternalKey(), externalKey);
Assert.assertEquals(subscriptionTransitionTag.getName(), name);
- final BusinessSubscriptionTransitionTag otherTransitionTag = new BusinessSubscriptionTransitionTag(UUID.randomUUID().toString(), UUID.randomUUID().toString());
+ final BusinessSubscriptionTransitionTag otherTransitionTag = new BusinessSubscriptionTransitionTag(UUID.randomUUID().toString(),
+ UUID.randomUUID(),
+ UUID.randomUUID().toString(),
+ UUID.randomUUID().toString());
Assert.assertFalse(subscriptionTransitionTag.equals(otherTransitionTag));
}
}
diff --git a/analytics/src/test/java/com/ning/billing/analytics/TestBusinessSubscriptionTransitionRecorder.java b/analytics/src/test/java/com/ning/billing/analytics/TestBusinessSubscriptionTransitionRecorder.java
index 531ab7b..44ccbce 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/TestBusinessSubscriptionTransitionRecorder.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/TestBusinessSubscriptionTransitionRecorder.java
@@ -24,24 +24,27 @@ import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.google.common.collect.ImmutableList;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.analytics.dao.BusinessSubscriptionTransitionSqlDao;
-import com.ning.billing.analytics.model.BusinessSubscription;
-import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogService;
-import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.entitlement.api.SubscriptionTransitionType;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
+import com.ning.billing.util.clock.DefaultClock;
public class TestBusinessSubscriptionTransitionRecorder extends AnalyticsTestSuite {
@Test(groups = "fast")
public void testCreateAddOn() throws Exception {
+ final UUID bundleId = UUID.randomUUID();
final UUID externalKey = UUID.randomUUID();
+ final UUID accountId = UUID.randomUUID();
+ final UUID subscriptionId = UUID.randomUUID();
// Setup the catalog
final CatalogService catalogService = Mockito.mock(CatalogService.class);
@@ -49,26 +52,11 @@ public class TestBusinessSubscriptionTransitionRecorder extends AnalyticsTestSui
// Setup the dao
final BusinessSubscriptionTransitionSqlDao sqlDao = new MockBusinessSubscriptionTransitionSqlDao();
- // Add a previous subscription to make sure it doesn't impact the addon
- final BusinessSubscription nextPrevSubscription = new BusinessSubscription(UUID.randomUUID().toString(),
- UUID.randomUUID().toString(),
- UUID.randomUUID().toString(),
- Currency.USD,
- new DateTime(DateTimeZone.UTC),
- Subscription.SubscriptionState.ACTIVE,
- UUID.randomUUID(),
- UUID.randomUUID(),
- catalogService.getFullCatalog());
- sqlDao.createTransition(new BusinessSubscriptionTransition(10L,
- externalKey.toString(),
- UUID.randomUUID().toString(),
- new DateTime(DateTimeZone.UTC),
- BusinessSubscriptionEvent.valueOf("ADD_MISC"),
- null,
- nextPrevSubscription));
// Setup the entitlement API
final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(bundleId);
+ Mockito.when(bundle.getAccountId()).thenReturn(accountId);
Mockito.when(bundle.getKey()).thenReturn(externalKey.toString());
final EntitlementUserApi entitlementApi = Mockito.mock(EntitlementUserApi.class);
Mockito.when(entitlementApi.getBundleFromId(Mockito.<UUID>any())).thenReturn(bundle);
@@ -79,20 +67,27 @@ public class TestBusinessSubscriptionTransitionRecorder extends AnalyticsTestSui
final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
Mockito.when(accountApi.getAccountById(bundle.getAccountId())).thenReturn(account);
- final BusinessSubscriptionTransitionRecorder recorder = new BusinessSubscriptionTransitionRecorder(sqlDao, catalogService, entitlementApi, accountApi);
-
// Create an new subscription event
- final SubscriptionEvent event = Mockito.mock(SubscriptionEvent.class);
- Mockito.when(event.getId()).thenReturn(UUID.randomUUID());
- Mockito.when(event.getRequestedTransitionTime()).thenReturn(new DateTime(DateTimeZone.UTC));
- Mockito.when(event.getNextPlan()).thenReturn(UUID.randomUUID().toString());
- Mockito.when(event.getEffectiveTransitionTime()).thenReturn(new DateTime(DateTimeZone.UTC));
- Mockito.when(event.getSubscriptionStartDate()).thenReturn(new DateTime(DateTimeZone.UTC));
- recorder.subscriptionCreated(event);
+ final EffectiveSubscriptionEvent eventEffective = Mockito.mock(EffectiveSubscriptionEvent.class);
+ Mockito.when(eventEffective.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(eventEffective.getTransitionType()).thenReturn(SubscriptionTransitionType.CREATE);
+ Mockito.when(eventEffective.getSubscriptionId()).thenReturn(subscriptionId);
+ Mockito.when(eventEffective.getRequestedTransitionTime()).thenReturn(new DateTime(DateTimeZone.UTC));
+ Mockito.when(eventEffective.getNextPlan()).thenReturn(UUID.randomUUID().toString());
+ Mockito.when(eventEffective.getEffectiveTransitionTime()).thenReturn(new DateTime(DateTimeZone.UTC));
+ Mockito.when(eventEffective.getSubscriptionStartDate()).thenReturn(new DateTime(DateTimeZone.UTC));
+
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(subscription.getId()).thenReturn(subscriptionId);
+ Mockito.when(subscription.getAllTransitions()).thenReturn(ImmutableList.<EffectiveSubscriptionEvent>of(eventEffective));
+ Mockito.when(entitlementApi.getSubscriptionsForBundle(Mockito.<UUID>any())).thenReturn(ImmutableList.<Subscription>of(subscription));
+
+ final BusinessSubscriptionTransitionRecorder recorder = new BusinessSubscriptionTransitionRecorder(sqlDao, catalogService, entitlementApi, accountApi, new DefaultClock());
+ recorder.rebuildTransitionsForBundle(bundle.getId());
- Assert.assertEquals(sqlDao.getTransitions(externalKey.toString()).size(), 2);
- final BusinessSubscriptionTransition transition = sqlDao.getTransitions(externalKey.toString()).get(1);
- Assert.assertEquals(transition.getTotalOrdering(), (long) event.getTotalOrdering());
+ Assert.assertEquals(sqlDao.getTransitionsByKey(externalKey.toString()).size(), 1);
+ final BusinessSubscriptionTransition transition = sqlDao.getTransitionsByKey(externalKey.toString()).get(0);
+ Assert.assertEquals(transition.getTotalOrdering(), (long) eventEffective.getTotalOrdering());
Assert.assertEquals(transition.getAccountKey(), externalKey.toString());
// Make sure all the prev_ columns are null
Assert.assertNull(transition.getPreviousSubscription());
diff --git a/analytics/src/test/java/com/ning/billing/analytics/TestBusinessTagRecorder.java b/analytics/src/test/java/com/ning/billing/analytics/TestBusinessTagRecorder.java
index 6f18739..f693718 100644
--- a/analytics/src/test/java/com/ning/billing/analytics/TestBusinessTagRecorder.java
+++ b/analytics/src/test/java/com/ning/billing/analytics/TestBusinessTagRecorder.java
@@ -60,7 +60,7 @@ import com.ning.billing.util.clock.DefaultClock;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.notificationq.DefaultNotificationQueueService;
-public class TestBusinessTagRecorder extends TestWithEmbeddedDB {
+public class TestBusinessTagRecorder extends AnalyticsTestSuiteWithEmbeddedDB {
private BusinessAccountTagSqlDao accountTagSqlDao;
private BusinessSubscriptionTransitionTagSqlDao subscriptionTransitionTagSqlDao;
private InMemoryBus eventBus;
@@ -85,7 +85,7 @@ public class TestBusinessTagRecorder extends TestWithEmbeddedDB {
final CatalogService catalogService = new DefaultCatalogService(Mockito.mock(CatalogConfig.class), Mockito.mock(VersionedCatalogLoader.class));
final AddonUtils addonUtils = new AddonUtils(catalogService);
final DefaultNotificationQueueService notificationQueueService = new DefaultNotificationQueueService(dbi, clock);
- final EntitlementDao entitlementDao = new AuditedEntitlementDao(dbi, clock, addonUtils, notificationQueueService, eventBus);
+ final EntitlementDao entitlementDao = new AuditedEntitlementDao(dbi, clock, addonUtils, notificationQueueService, eventBus, catalogService);
final PlanAligner planAligner = new PlanAligner(catalogService);
final DefaultSubscriptionApiService apiService = new DefaultSubscriptionApiService(clock, entitlementDao, catalogService, planAligner);
final DefaultSubscriptionFactory subscriptionFactory = new DefaultSubscriptionFactory(apiService, clock, catalogService);
@@ -115,11 +115,11 @@ public class TestBusinessTagRecorder extends TestWithEmbeddedDB {
final Account account = accountUserApi.createAccount(accountData, callContext);
final UUID accountId = account.getId();
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey).size(), 0);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey).size(), 0);
tagRecorder.tagAdded(ObjectType.ACCOUNT, accountId, name);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey).size(), 1);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey).size(), 1);
tagRecorder.tagRemoved(ObjectType.ACCOUNT, accountId, name);
- Assert.assertEquals(accountTagSqlDao.getTagsForAccount(accountKey).size(), 0);
+ Assert.assertEquals(accountTagSqlDao.getTagsForAccountByKey(accountKey).size(), 0);
}
@Test(groups = "slow")
@@ -135,10 +135,10 @@ public class TestBusinessTagRecorder extends TestWithEmbeddedDB {
final SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), externalKey, callContext);
final UUID bundleId = bundle.getId();
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
tagRecorder.tagAdded(ObjectType.BUNDLE, bundleId, name);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey).size(), 1);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey).size(), 1);
tagRecorder.tagRemoved(ObjectType.BUNDLE, bundleId, name);
- Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransition(externalKey).size(), 0);
+ Assert.assertEquals(subscriptionTransitionTagSqlDao.getTagsForBusinessSubscriptionTransitionByKey(externalKey).size(), 0);
}
}
api/pom.xml 2(+1 -1)
diff --git a/api/pom.xml b/api/pom.xml
index 538901a..396f57a 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-api</artifactId>
diff --git a/api/src/main/java/com/ning/billing/BillingExceptionBase.java b/api/src/main/java/com/ning/billing/BillingExceptionBase.java
index a074d3e..85761ab 100644
--- a/api/src/main/java/com/ning/billing/BillingExceptionBase.java
+++ b/api/src/main/java/com/ning/billing/BillingExceptionBase.java
@@ -16,12 +16,12 @@
package com.ning.billing;
+import javax.annotation.Nullable;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class BillingExceptionBase extends Exception {
-
private static final Logger log = LoggerFactory.getLogger(BillingExceptionBase.class);
private static final long serialVersionUID = 165720101383L;
@@ -42,9 +42,8 @@ public class BillingExceptionBase extends Exception {
this.cause = cause;
}
-
- public BillingExceptionBase(final Throwable cause, final ErrorCode code, final Object... args) {
- String tmp = null;
+ public BillingExceptionBase(@Nullable final Throwable cause, final ErrorCode code, final Object... args) {
+ final String tmp;
try {
tmp = String.format(code.getFormat(), args);
} catch (RuntimeException e) {
@@ -74,4 +73,14 @@ public class BillingExceptionBase extends Exception {
return code;
}
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("BillingExceptionBase");
+ sb.append("{cause=").append(cause);
+ sb.append(", code=").append(code);
+ sb.append(", formattedMsg='").append(formattedMsg).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/api/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java b/api/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java
index e6f024c..cb8993d 100644
--- a/api/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java
+++ b/api/src/main/java/com/ning/billing/entitlement/api/user/Subscription.java
@@ -31,7 +31,6 @@ import com.ning.billing.junction.api.Blockable;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.entity.Entity;
-
public interface Subscription extends Entity, Blockable {
public boolean cancel(DateTime requestedDate, boolean eot, CallContext context)
@@ -40,7 +39,7 @@ public interface Subscription extends Entity, Blockable {
public boolean uncancel(CallContext context)
throws EntitlementUserApiException;
- public boolean changePlan(String productName, BillingPeriod term, String planSet, DateTime requestedDate, CallContext context)
+ public boolean changePlan(String productName, BillingPeriod term, String priceList, DateTime requestedDate, CallContext context)
throws EntitlementUserApiException;
public boolean recreate(PlanPhaseSpecifier spec, DateTime requestedDate, CallContext context)
@@ -59,6 +58,8 @@ public interface Subscription extends Entity, Blockable {
public DateTime getEndDate();
+ public DateTime getFutureEndDate();
+
public Plan getCurrentPlan();
public PriceList getCurrentPriceList();
@@ -71,9 +72,11 @@ public interface Subscription extends Entity, Blockable {
public ProductCategory getCategory();
- public SubscriptionEvent getPendingTransition();
+ public EffectiveSubscriptionEvent getPendingTransition();
+
+ public EffectiveSubscriptionEvent getPreviousTransition();
- public SubscriptionEvent getPreviousTransition();
+ public List<EffectiveSubscriptionEvent> getBillingTransitions();
- public List<SubscriptionEvent> getBillingTransitions();
+ public List<EffectiveSubscriptionEvent> getAllTransitions();
}
diff --git a/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundle.java b/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundle.java
index 61c76ee..479dbf5 100644
--- a/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundle.java
+++ b/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundle.java
@@ -18,20 +18,14 @@ package com.ning.billing.entitlement.api.user;
import java.util.UUID;
-import org.joda.time.DateTime;
-
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.overdue.OverdueState;
import com.ning.billing.util.entity.Entity;
public interface SubscriptionBundle extends Blockable, Entity {
-
public UUID getAccountId();
- public DateTime getStartDate();
-
public String getKey();
public OverdueState<SubscriptionBundle> getOverdueState();
-
}
diff --git a/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvent.java b/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvent.java
index 6d22268..f5a345d 100644
--- a/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvent.java
+++ b/api/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvent.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2011 Ning, Inc.
+ * Copyright 2010-2012 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
@@ -25,7 +25,6 @@ import com.ning.billing.entitlement.api.user.Subscription.SubscriptionState;
import com.ning.billing.util.bus.BusEvent;
public interface SubscriptionEvent extends BusEvent {
-
UUID getId();
SubscriptionTransitionType getTransitionType();
@@ -59,5 +58,4 @@ public interface SubscriptionEvent extends BusEvent {
Integer getRemainingEventsForUserOperation();
Long getTotalOrdering();
-
}
diff --git a/api/src/main/java/com/ning/billing/ErrorCode.java b/api/src/main/java/com/ning/billing/ErrorCode.java
index 0cda076..68eadbe 100644
--- a/api/src/main/java/com/ning/billing/ErrorCode.java
+++ b/api/src/main/java/com/ning/billing/ErrorCode.java
@@ -22,6 +22,7 @@ public enum ErrorCode {
*/
NOT_IMPLEMENTED(1, "Api not implemented yet"),
DATA_TRUNCATION(2, "Data truncation error. (%s)"),
+ UNEXPECTED_ERROR(3, "%s"),
/*
*
* Range 1000 : ENTITLEMENTS
@@ -184,7 +185,7 @@ public enum ErrorCode {
INVOICE_TARGET_DATE_TOO_FAR_IN_THE_FUTURE(4005, "The target date was too far in the future. Target Date: %s"),
INVOICE_NOT_FOUND(4006, "No invoice could be found for id %s."),
INVOICE_NOTHING_TO_DO(4007, "No invoice to generate for account %s and date %s"),
-
+
/*
*
* Range 4900: Invoice payment
@@ -193,21 +194,25 @@ public enum ErrorCode {
INVOICE_PAYMENT_NOT_FOUND(4900, "No invoice payment could be found for id %s."),
CHARGE_BACK_AMOUNT_TOO_HIGH(4901, "Tried to charge back %s of a %s payment."),
CHARGE_BACK_AMOUNT_IS_NEGATIVE(4902, "Charge backs for negative amounts are not permitted"),
- CHARGE_BACK_COULD_NOT_FIND_ACCOUNT_ID(4093, "Could not find chargeback for id %s."),
- CHARGE_BACK_DOES_NOT_EXIST(4093, "Could not find chargeback for id %s."),
+ CHARGE_BACK_COULD_NOT_FIND_ACCOUNT_ID(4003, "Could not find chargeback for id %s."),
+ CHARGE_BACK_DOES_NOT_EXIST(4004, "Could not find chargeback for id %s."),
+ INVOICE_PAYMENT_BY_ATTEMPT_NOT_FOUND(4905, "No invoice payment could be found for paymentAttempt id %s."),
+ REFUND_AMOUNT_TOO_HIGH(4906, "Tried to refund %s of a %s payment."),
+ REFUND_AMOUNT_IS_POSITIVE(4907, "Refund for positve amounts are not permitted"),
+
/*
- *
+ *
* Range 5000: Overdue system
- *
+ *
*/
OVERDUE_CAT_ERROR_ENCOUNTERED(5001, "Catalog error encountered on Overdueable: id='%s', type='%s'"),
OVERDUE_TYPE_NOT_SUPPORTED(5002, "Overdue of this type is not supported: id='%s', type='%s'"),
OVERDUE_NO_REEVALUATION_INTERVAL(5003, "No valid reevaluation interval for state (name: %s)"),
OVERDUE_NOT_CONFIGURED(5004, "No configuration was found for the overdue system"),
/*
- *
+ *
* Range 6000: Blocking system
- *
+ *
*/
BLOCK_BLOCKED_ACTION(6000, "The action %s is block on this %s with id=%s"),
BLOCK_TYPE_NOT_SUPPORTED(6001, "The Blockable type '%s' is not supported"),
@@ -240,6 +245,9 @@ public enum ErrorCode {
PAYMENT_NO_SUCH_PAYMENT(7020, "Payment %s does not exist"),
PAYMENT_NO_DEFAULT_PAYMENT_METHOD(7021, "Account %s does not have a default payment method set"),
PAYMENT_DEL_DEFAULT_PAYMENT_METHOD(7022, "Cannot delete default payment method for account %s"),
+ PAYMENT_NO_SUCH_REFUND(7023, "Refund %s does not exist"),
+ PAYMENT_NO_SUCH_SUCCESS_PAYMENT(7024, "Payment %s did not succeed"),
+ PAYMENT_REFUND_AMOUNT_TOO_LARGE(7025, "Refund amount if larger than payment"),
PAYMENT_PLUGIN_TIMEOUT(7100, "Plugin timeout for account %s and invoice %s"),
PAYMENT_PLUGIN_ACCOUNT_INIT(7101, "Account initialization for account %s and plugin % s failed: %s"),
diff --git a/api/src/main/java/com/ning/billing/glue/InvoiceModule.java b/api/src/main/java/com/ning/billing/glue/InvoiceModule.java
index 7e55895..f513edd 100644
--- a/api/src/main/java/com/ning/billing/glue/InvoiceModule.java
+++ b/api/src/main/java/com/ning/billing/glue/InvoiceModule.java
@@ -17,13 +17,9 @@
package com.ning.billing.glue;
public interface InvoiceModule {
-
public abstract void installInvoiceUserApi();
public abstract void installInvoicePaymentApi();
public abstract void installInvoiceMigrationApi();
-
- public abstract void installInvoiceTestApi();
-
-}
\ No newline at end of file
+}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/Invoice.java b/api/src/main/java/com/ning/billing/invoice/api/Invoice.java
index 8fbf0cf..f79a46e 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/Invoice.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/Invoice.java
@@ -54,13 +54,19 @@ public interface Invoice extends Entity {
Currency getCurrency();
- DateTime getLastPaymentAttempt();
+ DateTime getLastPaymentDate();
- BigDecimal getAmountPaid();
+ BigDecimal getPaidAmount();
- BigDecimal getAmountCharged();
+ BigDecimal getChargedAmount();
- BigDecimal getAmountCredited();
+ BigDecimal getCBAAmount();
+
+ BigDecimal getTotalAdjAmount();
+
+ BigDecimal getCreditAdjAmount();
+
+ BigDecimal getRefundAdjAmount();
BigDecimal getBalance();
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoiceCreationEvent.java b/api/src/main/java/com/ning/billing/invoice/api/InvoiceCreationEvent.java
index 0385827..5fb8964 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoiceCreationEvent.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoiceCreationEvent.java
@@ -22,12 +22,10 @@ import java.util.UUID;
import org.joda.time.DateTime;
import com.ning.billing.catalog.api.Currency;
-import com.ning.billing.util.bus.BusEvent;
-public interface InvoiceCreationEvent extends BusEvent {
- public UUID getInvoiceId();
+public interface InvoiceCreationEvent extends InvoiceEvent {
- public UUID getAccountId();
+ public UUID getInvoiceId();
public BigDecimal getAmountOwed();
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoiceEvent.java b/api/src/main/java/com/ning/billing/invoice/api/InvoiceEvent.java
new file mode 100644
index 0000000..429e69c
--- /dev/null
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoiceEvent.java
@@ -0,0 +1,24 @@
+/*
+ * 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.invoice.api;
+
+import java.util.UUID;
+
+import com.ning.billing.util.bus.BusEvent;
+
+public interface InvoiceEvent extends BusEvent {
+ public UUID getAccountId();
+}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoiceItem.java b/api/src/main/java/com/ning/billing/invoice/api/InvoiceItem.java
index ca7f7af..6c5cbef 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoiceItem.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoiceItem.java
@@ -25,29 +25,32 @@ import com.ning.billing.catalog.api.Currency;
import com.ning.billing.util.entity.Entity;
public interface InvoiceItem extends Entity, Comparable<InvoiceItem> {
+
+ InvoiceItemType getInvoiceItemType();
+
UUID getInvoiceId();
UUID getAccountId();
- UUID getBundleId();
+ DateTime getStartDate();
- UUID getSubscriptionId();
+ DateTime getEndDate();
- String getPlanName();
+ BigDecimal getAmount();
- String getPhaseName();
+ Currency getCurrency();
String getDescription();
- DateTime getStartDate();
+ UUID getBundleId();
- DateTime getEndDate();
+ UUID getSubscriptionId();
- BigDecimal getAmount();
+ String getPlanName();
- Currency getCurrency();
+ String getPhaseName();
- InvoiceItemType getInvoiceItemType();
+ BigDecimal getRate();
- InvoiceItem asReversingItem();
+ UUID getLinkedItemId();
}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoiceItemType.java b/api/src/main/java/com/ning/billing/invoice/api/InvoiceItemType.java
index aaae9df..93afad8 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoiceItemType.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoiceItemType.java
@@ -19,9 +19,8 @@ package com.ning.billing.invoice.api;
public enum InvoiceItemType {
FIXED,
RECURRING,
- REVERSAL,
- MIGRATION,
- REFUND,
- CHARGE_BACK,
- CREDIT
+ REPAIR_ADJ,
+ CBA_ADJ,
+ CREDIT_ADJ,
+ REFUND_ADJ
}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoicePayment.java b/api/src/main/java/com/ning/billing/invoice/api/InvoicePayment.java
index 4a04248..c5b331e 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoicePayment.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoicePayment.java
@@ -25,20 +25,25 @@ import com.ning.billing.catalog.api.Currency;
import com.ning.billing.util.entity.Entity;
public interface InvoicePayment extends Entity {
- UUID getPaymentAttemptId();
+ UUID getPaymentId();
+
+ InvoicePaymentType getType();
UUID getInvoiceId();
- DateTime getPaymentAttemptDate();
+ DateTime getPaymentDate();
BigDecimal getAmount();
Currency getCurrency();
- UUID getReversedInvoicePaymentId();
+ UUID getLinkedInvoicePaymentId();
+
+ UUID getPaymentCookieId();
- /*
- * @param chargeBackAmount BigDecimal pass the amount as a positive number
- */
- InvoicePayment asChargeBack(BigDecimal chargeBackAmount, DateTime chargeBackDate) throws InvoiceApiException;
+ public enum InvoicePaymentType {
+ ATTEMPT,
+ CHARGED_BACK,
+ REFUND
+ }
}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoicePaymentApi.java b/api/src/main/java/com/ning/billing/invoice/api/InvoicePaymentApi.java
index 9c6eb69..197d8b9 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoicePaymentApi.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoicePaymentApi.java
@@ -27,26 +27,26 @@ import com.ning.billing.util.callcontext.CallContext;
public interface InvoicePaymentApi {
/**
- * @param accountId
+ * @param accountId id of the account
* @return All invoices, including migrated invoices
*/
public List<Invoice> getAllInvoicesByAccount(UUID accountId);
public Invoice getInvoice(UUID invoiceId);
- public Invoice getInvoiceForPaymentAttemptId(UUID paymentAttemptId);
+ public Invoice getInvoiceForPaymentId(UUID paymentId);
- public InvoicePayment getInvoicePayment(UUID paymentAttemptId);
+ public InvoicePayment getInvoicePayment(UUID paymentId);
- public void notifyOfPaymentAttempt(InvoicePayment invoicePayment, CallContext context);
+ public void notifyOfPayment(InvoicePayment invoicePayment, CallContext context);
- public void notifyOfPaymentAttempt(UUID invoiceId, BigDecimal amountOutstanding, Currency currency, UUID paymentAttemptId, DateTime paymentAttemptDate, CallContext context);
+ public void notifyOfPayment(UUID invoiceId, BigDecimal amountOutstanding, Currency currency, UUID paymentId, DateTime paymentDate, CallContext context);
- public void notifyOfPaymentAttempt(UUID invoiceId, UUID paymentAttemptId, DateTime paymentAttemptDate, CallContext context);
+ public InvoicePayment createRefund(UUID paymentId, BigDecimal amount, boolean isInvoiceAdjusted, UUID paymentCookieId, CallContext context) throws InvoiceApiException;
- public InvoicePayment processChargeback(UUID invoicePaymentId, BigDecimal amount, CallContext context) throws InvoiceApiException;
+ public InvoicePayment createChargeback(UUID invoicePaymentId, BigDecimal amount, CallContext context) throws InvoiceApiException;
- public InvoicePayment processChargeback(UUID invoicePaymentId, CallContext context) throws InvoiceApiException;
+ public InvoicePayment createChargeback(UUID invoicePaymentId, CallContext context) throws InvoiceApiException;
public BigDecimal getRemainingAmountPaid(UUID invoicePaymentId);
@@ -54,7 +54,7 @@ public interface InvoicePaymentApi {
public UUID getAccountIdFromInvoicePaymentId(UUID uuid) throws InvoiceApiException;
- public List<InvoicePayment> getChargebacksByPaymentAttemptId(UUID paymentAttemptId);
+ public List<InvoicePayment> getChargebacksByPaymentId(UUID paymentId);
public InvoicePayment getChargebackById(UUID chargebackId) throws InvoiceApiException;
}
diff --git a/api/src/main/java/com/ning/billing/invoice/api/InvoiceUserApi.java b/api/src/main/java/com/ning/billing/invoice/api/InvoiceUserApi.java
index d95f56d..403d176 100644
--- a/api/src/main/java/com/ning/billing/invoice/api/InvoiceUserApi.java
+++ b/api/src/main/java/com/ning/billing/invoice/api/InvoiceUserApi.java
@@ -38,7 +38,7 @@ public interface InvoiceUserApi {
public Invoice getInvoice(UUID invoiceId);
- public void notifyOfPaymentAttempt(InvoicePayment invoicePayment, CallContext context);
+ public void notifyOfPayment(InvoicePayment invoicePayment, CallContext context);
public Collection<Invoice> getUnpaidInvoicesByAccountId(UUID accountId, DateTime upToDate);
@@ -51,7 +51,10 @@ public interface InvoiceUserApi {
public InvoiceItem getCreditById(UUID creditId) throws InvoiceApiException;
public InvoiceItem insertCredit(UUID accountId, BigDecimal amount, DateTime effectiveDate,
- Currency currency, CallContext context) throws InvoiceApiException;
+ Currency currency, CallContext context) throws InvoiceApiException;
+
+ public InvoiceItem insertCreditForInvoice(UUID accountId, UUID invoiceId, BigDecimal amount, DateTime effectiveDate,
+ Currency currency, CallContext context) throws InvoiceApiException;
public String getInvoiceAsHTML(UUID invoiceId) throws AccountApiException, IOException, InvoiceApiException;
}
diff --git a/api/src/main/java/com/ning/billing/overdue/OverdueChangeEvent.java b/api/src/main/java/com/ning/billing/overdue/OverdueChangeEvent.java
new file mode 100644
index 0000000..daa731d
--- /dev/null
+++ b/api/src/main/java/com/ning/billing/overdue/OverdueChangeEvent.java
@@ -0,0 +1,32 @@
+/*
+ * 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.overdue;
+
+import java.util.UUID;
+
+import com.ning.billing.junction.api.Blockable;
+import com.ning.billing.util.bus.BusEvent;
+
+public interface OverdueChangeEvent extends BusEvent {
+ UUID getOverdueObjectId();
+
+ Blockable.Type getOverdueObjectType();
+
+ String getPreviousOverdueStateName();
+
+ String getNextOverdueStateName();
+}
diff --git a/api/src/main/java/com/ning/billing/payment/api/PaymentApi.java b/api/src/main/java/com/ning/billing/payment/api/PaymentApi.java
index c8f9b2f..479966a 100644
--- a/api/src/main/java/com/ning/billing/payment/api/PaymentApi.java
+++ b/api/src/main/java/com/ning/billing/payment/api/PaymentApi.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -31,8 +31,17 @@ public interface PaymentApi {
public Payment createPayment(final Account account, final UUID invoiceId, final BigDecimal amount, final CallContext context)
throws PaymentApiException;
- public Refund createRefund(final Account account, final UUID paymentId, final CallContext context)
- throws PaymentApiException;
+ public Refund getRefund(final UUID refundId)
+ throws PaymentApiException;
+
+ public Refund createRefund(final Account account, final UUID paymentId, final BigDecimal refundAmount, final boolean isAdjusted, final CallContext context)
+ throws PaymentApiException;
+
+ public List<Refund> getAccountRefunds(final Account account)
+ throws PaymentApiException;
+
+ public List<Refund> getPaymentRefunds(final UUID paymentId)
+ throws PaymentApiException;
public List<Payment> getInvoicePayments(final UUID invoiceId)
throws PaymentApiException;
diff --git a/api/src/main/java/com/ning/billing/payment/api/PaymentApiException.java b/api/src/main/java/com/ning/billing/payment/api/PaymentApiException.java
index 2ef846d..aa69bd0 100644
--- a/api/src/main/java/com/ning/billing/payment/api/PaymentApiException.java
+++ b/api/src/main/java/com/ning/billing/payment/api/PaymentApiException.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -18,11 +18,16 @@ package com.ning.billing.payment.api;
import com.ning.billing.BillingExceptionBase;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.AccountApiException;
+import com.ning.billing.invoice.api.InvoiceApiException;
public class PaymentApiException extends BillingExceptionBase {
private static final long serialVersionUID = 39445033L;
+ public PaymentApiException(final InvoiceApiException e) {
+ super(e, e.getCode(), e.getMessage());
+ }
+
public PaymentApiException(final AccountApiException e) {
super(e, e.getCode(), e.getMessage());
}
diff --git a/api/src/main/java/com/ning/billing/payment/api/PaymentInfoEvent.java b/api/src/main/java/com/ning/billing/payment/api/PaymentInfoEvent.java
index 8c5a1ef..8bbae11 100644
--- a/api/src/main/java/com/ning/billing/payment/api/PaymentInfoEvent.java
+++ b/api/src/main/java/com/ning/billing/payment/api/PaymentInfoEvent.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -38,4 +38,6 @@ public interface PaymentInfoEvent extends Entity, BusEvent {
public Integer getPaymentNumber();
public PaymentStatus getStatus();
+
+ public String getExtPaymentRefId();
}
diff --git a/api/src/main/java/com/ning/billing/payment/api/Refund.java b/api/src/main/java/com/ning/billing/payment/api/Refund.java
index e769e54..ed2e15c 100644
--- a/api/src/main/java/com/ning/billing/payment/api/Refund.java
+++ b/api/src/main/java/com/ning/billing/payment/api/Refund.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -15,6 +15,15 @@
*/
package com.ning.billing.payment.api;
-public interface Refund {
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import com.ning.billing.catalog.api.Currency;
+public interface Refund {
+ public UUID getId();
+ public UUID getPaymentId();
+ public boolean isAdjusted();
+ public BigDecimal getRefundAmount();
+ public Currency getCurrency();
}
diff --git a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentInfoPlugin.java b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentInfoPlugin.java
index 3e8b563..eeb356a 100644
--- a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentInfoPlugin.java
+++ b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentInfoPlugin.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -38,4 +38,6 @@ public interface PaymentInfoPlugin {
public String getGatewayError();
public String getGatewayErrorCode();
+
+ public String getExternalReferenceId();
}
diff --git a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApi.java b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApi.java
index 10b329e..5f8fe2d 100644
--- a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApi.java
+++ b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApi.java
@@ -33,8 +33,11 @@ public interface PaymentPluginApi {
public PaymentInfoPlugin getPaymentInfo(UUID paymentId)
throws PaymentPluginApiException;
- public List<PaymentInfoPlugin> processRefund(Account account)
- throws PaymentPluginApiException;
+ public void processRefund(Account account, UUID paymentId, BigDecimal refundAmout)
+ throws PaymentPluginApiException;
+
+ public int getNbRefundForPaymentAmount(final Account account, final UUID paymentId, final BigDecimal refundAmount)
+ throws PaymentPluginApiException;
public String createPaymentProviderAccount(Account account)
throws PaymentPluginApiException;
diff --git a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApiException.java b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApiException.java
index d201a27..81f1946 100644
--- a/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApiException.java
+++ b/api/src/main/java/com/ning/billing/payment/plugin/api/PaymentPluginApiException.java
@@ -13,10 +13,10 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.payment.plugin.api;
public class PaymentPluginApiException extends Exception {
-
private static final long serialVersionUID = 15642965L;
private final String errorType;
@@ -34,4 +34,14 @@ public class PaymentPluginApiException extends Exception {
public String getErrorMessage() {
return errorMessage;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("PaymentPluginApiException");
+ sb.append("{errorMessage='").append(errorMessage).append('\'');
+ sb.append(", errorType='").append(errorType).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/api/src/main/java/com/ning/billing/util/bus/BusEvent.java b/api/src/main/java/com/ning/billing/util/bus/BusEvent.java
index cfb8b0b..919924e 100644
--- a/api/src/main/java/com/ning/billing/util/bus/BusEvent.java
+++ b/api/src/main/java/com/ning/billing/util/bus/BusEvent.java
@@ -35,7 +35,8 @@ public interface BusEvent {
CONTROL_TAGDEFINITION_CREATION,
CONTROL_TAGDEFINITION_DELETION,
USER_TAGDEFINITION_CREATION,
- USER_TAGDEFINITION_DELETION
+ USER_TAGDEFINITION_DELETION,
+ OVERDUE_CHANGE
}
public BusEventType getBusEventType();
diff --git a/api/src/main/java/com/ning/billing/util/dao/ObjectType.java b/api/src/main/java/com/ning/billing/util/dao/ObjectType.java
index a158e77..b67e847 100644
--- a/api/src/main/java/com/ning/billing/util/dao/ObjectType.java
+++ b/api/src/main/java/com/ning/billing/util/dao/ObjectType.java
@@ -22,9 +22,10 @@ public enum ObjectType {
BUNDLE("subscription bundle"),
INVOICE("invoice"),
PAYMENT("payment"),
- RECURRING_INVOICE_ITEM("recurring_invoice_item"),
+ INVOICE_ITEM("invoice item"),
SUBSCRIPTION("subscription"),
- PAYMENT_METHOD("payment method");
+ PAYMENT_METHOD("payment method"),
+ REFUND("refund");
private final String objectName;
diff --git a/api/src/main/java/com/ning/billing/util/tag/api/TagEvent.java b/api/src/main/java/com/ning/billing/util/tag/api/TagEvent.java
index 1cd3cfd..dc05d00 100644
--- a/api/src/main/java/com/ning/billing/util/tag/api/TagEvent.java
+++ b/api/src/main/java/com/ning/billing/util/tag/api/TagEvent.java
@@ -23,6 +23,7 @@ import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.tag.TagDefinition;
public interface TagEvent extends BusEvent {
+
UUID getTagId();
UUID getObjectId();
diff --git a/api/src/main/java/com/ning/billing/util/template/translation/TranslatorConfig.java b/api/src/main/java/com/ning/billing/util/template/translation/TranslatorConfig.java
index 14dacf5..8d4e06e 100644
--- a/api/src/main/java/com/ning/billing/util/template/translation/TranslatorConfig.java
+++ b/api/src/main/java/com/ning/billing/util/template/translation/TranslatorConfig.java
@@ -22,13 +22,23 @@ import org.skife.config.Default;
import com.ning.billing.invoice.api.formatters.InvoiceFormatterFactory;
public interface TranslatorConfig {
- @Config("killbill.template.default.locale")
+ // Common
+
+ @Config("killbill.default.locale")
@Default("en_US")
public String getDefaultLocale();
+ // Catalog
+
+ @Config("killbill.catalog.bundlePath")
+ @Default("com/ning/billing/util/template/translation/CatalogTranslation")
+ String getCatalogBundlePath();
+
+ // Invoices
+
@Config("killbill.template.bundlePath")
@Default("com/ning/billing/util/template/translation/InvoiceTranslation")
- public String getBundlePath();
+ public String getInvoiceTemplateBundlePath();
@Config("killbill.template.name")
@Default("com/ning/billing/util/email/templates/HtmlInvoiceTemplate.mustache")
diff --git a/api/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestWaiter.java b/api/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestWaiter.java
index f491beb..b7c308d 100644
--- a/api/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestWaiter.java
+++ b/api/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestWaiter.java
@@ -20,8 +20,8 @@ import java.util.concurrent.TimeoutException;
import com.ning.billing.account.api.AccountChangeEvent;
import com.ning.billing.account.api.AccountCreationEvent;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
-import com.ning.billing.invoice.api.EmptyInvoiceEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
+import com.ning.billing.invoice.api.NullInvoiceEvent;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.payment.api.PaymentErrorEvent;
import com.ning.billing.payment.api.PaymentInfoEvent;
@@ -35,11 +35,11 @@ public interface CompletionUserRequestWaiter {
public void onAccountChange(final AccountChangeEvent curEvent);
- public void onSubscriptionTransition(final SubscriptionEvent curEvent);
+ public void onSubscriptionTransition(final EffectiveSubscriptionEvent curEventEffective);
public void onInvoiceCreation(final InvoiceCreationEvent curEvent);
- public void onEmptyInvoice(final EmptyInvoiceEvent curEvent);
+ public void onEmptyInvoice(final NullInvoiceEvent curEvent);
public void onPaymentInfo(final PaymentInfoEvent curEvent);
beatrix/pom.xml 2(+1 -1)
diff --git a/beatrix/pom.xml b/beatrix/pom.xml
index 406b097..3b373e7 100644
--- a/beatrix/pom.xml
+++ b/beatrix/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-beatrix</artifactId>
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuite.java b/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuite.java
new file mode 100644
index 0000000..a94d343
--- /dev/null
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.beatrix;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class BeatrixTestSuite extends KillbillTestSuite {
+}
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuiteWithEmbeddedDB.java b/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..b6a8d20
--- /dev/null
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/BeatrixTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.beatrix;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class BeatrixTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/BeatrixModule.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/BeatrixModule.java
index c26fac5..96fcca7 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/BeatrixModule.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/BeatrixModule.java
@@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Injector;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.account.api.AccountService;
import com.ning.billing.account.glue.AccountModule;
import com.ning.billing.analytics.setup.AnalyticsModule;
@@ -65,7 +66,6 @@ import static org.testng.Assert.assertNotNull;
public class BeatrixModule extends AbstractModule {
-
public static final String PLUGIN_NAME = "yoyo";
@Override
@@ -77,7 +77,7 @@ public class BeatrixModule extends AbstractModule {
bind(ClockMock.class).asEagerSingleton();
bind(Lifecycle.class).to(SubsetDefaultLifecycle.class).asEagerSingleton();
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi;
if (helper.isUsingLocalInstance()) {
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestAnalytics.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestAnalytics.java
index 9dadb9e..27dddf5 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestAnalytics.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestAnalytics.java
@@ -16,11 +16,14 @@
package com.ning.billing.beatrix.integration;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
@@ -38,34 +41,133 @@ import com.ning.billing.analytics.model.BusinessInvoiceItem;
import com.ning.billing.analytics.model.BusinessSubscriptionEvent;
import com.ning.billing.analytics.model.BusinessSubscriptionTransition;
import com.ning.billing.analytics.utils.Rounder;
+import com.ning.billing.api.TestApiListener;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.CatalogApiException;
import com.ning.billing.catalog.api.PhaseType;
+import com.ning.billing.catalog.api.Plan;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
+import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
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.invoice.generator.InvoiceDateUtils;
+import com.ning.billing.overdue.config.OverdueConfig;
+import com.ning.billing.payment.api.PaymentStatus;
import com.ning.billing.util.api.TagApiException;
import com.ning.billing.util.api.TagDefinitionApiException;
+import com.ning.billing.util.config.XMLLoader;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.tag.TagDefinition;
+import static org.testng.Assert.assertTrue;
+
@Guice(modules = BeatrixModule.class)
public class TestAnalytics extends TestIntegrationBase {
+ private Plan subscriptionPlan;
+
@BeforeMethod(groups = "slow")
public void setUpAnalyticsHandler() throws Exception {
+ final String configXml = "<overdueConfig>" +
+ " <bundleOverdueStates>" +
+ " <state name=\"OD3\">" +
+ " <condition>" +
+ " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " <unit>DAYS</unit><number>50</number>" +
+ " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " </condition>" +
+ " <externalMessage>Reached OD3</externalMessage>" +
+ " <blockChanges>true</blockChanges>" +
+ " <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" +
+ " <autoReevaluationInterval>" +
+ " <unit>DAYS</unit><number>5</number>" +
+ " </autoReevaluationInterval>" +
+ " </state>" +
+ " <state name=\"OD2\">" +
+ " <condition>" +
+ " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " <unit>DAYS</unit><number>40</number>" +
+ " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " </condition>" +
+ " <externalMessage>Reached OD2</externalMessage>" +
+ " <blockChanges>true</blockChanges>" +
+ " <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" +
+ " <autoReevaluationInterval>" +
+ " <unit>DAYS</unit><number>5</number>" +
+ " </autoReevaluationInterval>" +
+ " </state>" +
+ " <state name=\"OD1\">" +
+ " <condition>" +
+ " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " <unit>DAYS</unit><number>30</number>" +
+ " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
+ " </condition>" +
+ " <externalMessage>Reached OD1</externalMessage>" +
+ " <blockChanges>true</blockChanges>" +
+ " <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" +
+ " <autoReevaluationInterval>" +
+ " <unit>DAYS</unit><number>100</number>" + // this number is intentionally too high
+ " </autoReevaluationInterval>" +
+ " </state>" +
+ " </bundleOverdueStates>" +
+ "</overdueConfig>";
+ final InputStream is = new ByteArrayInputStream(configXml.getBytes());
+ final OverdueConfig config = XMLLoader.getObjectFromStreamNoValidation(is, OverdueConfig.class);
+ overdueWrapperFactory.setOverdueConfig(config);
+
busService.getBus().register(analyticsListener);
}
@AfterMethod(groups = "slow")
public void tearDownAnalyticsHandler() throws Exception {
busService.getBus().unregister(analyticsListener);
+ // Reset the payment plugin for other tests
+ paymentPlugin.clear();
}
@Test(groups = "slow")
- public void testAnalyticsEvents() throws Exception {
+ public void testCreateAndCancelSubscription() throws Exception {
+ // Create an account
+ final Account account = verifyAccountCreation();
+
+ // Create a bundle
+ final SubscriptionBundle bundle = verifyFirstBundle(account);
+
+ // Add a subscription
+ Subscription subscription = verifyFirstSubscription(account, bundle);
+
+ // Move after trial
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS);
+ busHandler.pushExpectedEvent(TestApiListener.NextEvent.PHASE);
+ busHandler.pushExpectedEvent(TestApiListener.NextEvent.INVOICE);
+ busHandler.pushExpectedEvent(TestApiListener.NextEvent.PAYMENT);
+ Assert.assertTrue(busHandler.isCompleted(DELAY));
+
+ // Check BST - nothing should have changed
+ verifyBSTWithTrialAndEvergreenPhases(account, bundle, subscription);
+
+ // Cancel end of term - refetch the subscription to have the CTD set
+ // (otherwise, cancellation would be immediate)
+ subscription = entitlementUserApi.getSubscriptionFromId(subscription.getId());
+ subscription.cancel(clock.getUTCNow(), true, context);
+
+ waitALittle();
+
+ verifyBSTWithTrialAndEvergreenPhasesAndCancellation(account, bundle, subscription);
+
+ // Move after cancel date
+ clock.addDeltaFromReality(AT_LEAST_ONE_MONTH_MS + 100);
+ assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+
+ // Check BST received the system cancel event
+ verifyBSTWithTrialAndEvergreenPhasesAndCancellationAndSystemCancellation(account, bundle, subscription);
+ }
+
+ @Test(groups = "slow")
+ public void testCreateAndUpdateSubscription() throws Exception {
// Create an account
final Account account = verifyAccountCreation();
@@ -85,6 +187,131 @@ public class TestAnalytics extends TestIntegrationBase {
verifyChangePlan(account, bundle, subscription);
}
+ @Test(groups = "slow")
+ public void testOverdue() throws Exception {
+ paymentPlugin.makeAllInvoicesFailWithError(true);
+
+ // Create an account
+ final Account account = verifyAccountCreation();
+
+ // Create a bundle
+ final SubscriptionBundle bundle = verifyFirstBundle(account);
+
+ // Add a subscription
+ busHandler.pushExpectedEvents(TestApiListener.NextEvent.CREATE, TestApiListener.NextEvent.INVOICE);
+ final Subscription subscription = verifyFirstSubscription(account, bundle);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ // Verify the initial state of payments
+ Assert.assertEquals(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).size(), 0);
+
+ // Verify the account payment fields
+ Assert.assertEquals(analyticsUserApi.getAccountByKey(account.getExternalKey()).getBalance().doubleValue(), Rounder.round(BigDecimal.ZERO));
+ Assert.assertNull(analyticsUserApi.getAccountByKey(account.getExternalKey()).getLastPaymentStatus());
+
+ // Verify the initial overdue status
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 0);
+
+ // Move after trial
+ busHandler.pushExpectedEvents(TestApiListener.NextEvent.PHASE, TestApiListener.NextEvent.INVOICE, TestApiListener.NextEvent.PAYMENT_ERROR);
+ clock.addDays(30); // DAY 30 have to get out of trial before first payment
+ Assert.assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+
+ // Check BST - nothing should have changed
+ verifyBSTWithTrialAndEvergreenPhases(account, bundle, subscription);
+
+ // Verify the payments - we should have received one
+ Assert.assertEquals(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).size(), 1);
+ Assert.assertEquals(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getAccountKey(), account.getExternalKey());
+ Assert.assertTrue(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getAmount().compareTo(BigDecimal.ZERO) > 0);
+ Assert.assertTrue(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getRequestedAmount().compareTo(BigDecimal.ZERO) > 0);
+ Assert.assertNull(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getExtPaymentRefId());
+ Assert.assertEquals(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getProcessingStatus(), PaymentStatus.PAYMENT_FAILURE.toString());
+ Assert.assertEquals(analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getPluginName(), BeatrixModule.PLUGIN_NAME);
+
+ // Verify the account object has been updated
+ Assert.assertEquals(analyticsUserApi.getAccountByKey(account.getExternalKey()).getBalance(),
+ analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getAmount());
+
+ // Verify the invoice balance isn't zero and is equal to the payment amount (don't look at the first, trial, invoice)
+ Assert.assertTrue(analyticsUserApi.getInvoicesForAccount(account.getExternalKey()).get(1).getBalance().compareTo(BigDecimal.ZERO) > 0);
+ Assert.assertEquals(analyticsUserApi.getInvoicesForAccount(account.getExternalKey()).get(1).getBalance(),
+ analyticsUserApi.getInvoicePaymentsForAccount(account.getExternalKey()).get(0).getAmount());
+
+ // Verify overdue status - we should still be in clear state
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 0);
+
+ clock.addDays(15); // DAY 45 - 15 days after invoice
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ // Check BST - nothing should have changed
+ verifyBSTWithTrialAndEvergreenPhases(account, bundle, subscription);
+
+ // Verify overdue status - we should still be in clear state
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 0);
+
+ busHandler.pushExpectedEvents(TestApiListener.NextEvent.INVOICE, TestApiListener.NextEvent.PAYMENT_ERROR);
+ clock.addDays(20); // DAY 65 - 35 days after invoice
+ assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+
+ // Verify overdue status - we should be in OD1
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 1);
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getStatus(), "OD1");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getAccountKey(), account.getExternalKey());
+
+ clock.addDays(2); // DAY 67 - 37 days after invoice
+ assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+ // Verify overdue status - we should still be in OD1
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 1);
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getStatus(), "OD1");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getAccountKey(), account.getExternalKey());
+
+ clock.addDays(8); // DAY 75 - 45 days after invoice
+ assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+ // Verify overdue status - we should be in OD2
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 2);
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getStatus(), "OD1");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getStatus(), "OD2");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getEndDate(),
+ analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getStartDate());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getAccountKey(), account.getExternalKey());
+
+ clock.addDays(10); // DAY 85 - 55 days after invoice
+ assertTrue(busHandler.isCompleted(DELAY));
+ waitALittle();
+ // Verify overdue status - we should be in OD3
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).size(), 3);
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getStatus(), "OD1");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getStatus(), "OD2");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(2).getStatus(), "OD3");
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getEndDate(),
+ analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getStartDate());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getEndDate(),
+ analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(2).getStartDate());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(0).getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(1).getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(2).getBundleId(), bundle.getId());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(2).getExternalKey(), bundle.getKey());
+ Assert.assertEquals(analyticsUserApi.getOverdueStatusesForBundle(bundle.getKey()).get(2).getAccountKey(), account.getExternalKey());
+ }
+
private Account verifyAccountCreation() throws Exception {
final AccountData accountData = getAccountData(1);
@@ -192,35 +419,12 @@ public class TestAnalytics extends TestIntegrationBase {
final String planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
final PlanPhaseSpecifier phaseSpecifier = new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null);
final Subscription subscription = entitlementUserApi.createSubscription(bundle.getId(), phaseSpecifier, null, context);
+ subscriptionPlan = subscription.getCurrentPlan();
waitALittle();
- // BST should have one transition
- final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
- Assert.assertEquals(transitions.size(), 1);
- final BusinessSubscriptionTransition transition = transitions.get(0);
- Assert.assertEquals(transition.getExternalKey(), bundle.getKey());
- Assert.assertEquals(transition.getAccountKey(), account.getExternalKey());
- Assert.assertEquals(transition.getEvent().getCategory(), phaseSpecifier.getProductCategory());
- Assert.assertEquals(transition.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.ADD);
-
- // This is the first transition
- Assert.assertNull(transition.getPreviousSubscription());
-
- Assert.assertEquals(transition.getNextSubscription().getBillingPeriod(), subscription.getCurrentPhase().getBillingPeriod().toString());
- Assert.assertEquals(transition.getNextSubscription().getBundleId(), subscription.getBundleId());
- Assert.assertEquals(transition.getNextSubscription().getCurrency(), account.getCurrency().toString());
- Assert.assertEquals(transition.getNextSubscription().getPhase(), subscription.getCurrentPhase().getPhaseType().toString());
- // Trial: fixed price of zero
- Assert.assertEquals(transition.getNextSubscription().getPrice().doubleValue(), subscription.getCurrentPhase().getFixedPrice().getPrice(account.getCurrency()).doubleValue());
- Assert.assertEquals(transition.getNextSubscription().getPriceList(), subscription.getCurrentPriceList().getName());
- Assert.assertEquals(transition.getNextSubscription().getProductCategory(), subscription.getCurrentPlan().getProduct().getCategory());
- Assert.assertEquals(transition.getNextSubscription().getProductName(), subscription.getCurrentPlan().getProduct().getName());
- Assert.assertEquals(transition.getNextSubscription().getProductType(), subscription.getCurrentPlan().getProduct().getCatalogName());
- Assert.assertEquals(transition.getNextSubscription().getSlug(), subscription.getCurrentPhase().getName());
- Assert.assertEquals(transition.getNextSubscription().getStartDate(), subscription.getStartDate());
- Assert.assertEquals(transition.getNextSubscription().getState(), subscription.getState());
- Assert.assertEquals(transition.getNextSubscription().getSubscriptionId(), subscription.getId());
+ // Verify BST
+ verifyBSTWithTrialAndEvergreenPhases(account, bundle, subscription);
// Make sure the account balance is still zero
final BusinessAccount businessAccount = analyticsUserApi.getAccountByKey(account.getExternalKey());
@@ -245,8 +449,9 @@ public class TestAnalytics extends TestIntegrationBase {
// No billing period for the trial item
Assert.assertEquals(invoiceItem.getBillingPeriod(), subscription.getCurrentPhase().getBillingPeriod().toString());
Assert.assertEquals(invoiceItem.getCurrency(), account.getCurrency());
- // The subscription end date is null (evergreen)
- Assert.assertEquals(invoiceItem.getEndDate(), subscription.getStartDate().plus(subscription.getCurrentPhase().getDuration().toJodaPeriod()));
+ final DateTime subscriptionEndDate = subscription.getStartDate().plus(subscription.getCurrentPhase().getDuration().toJodaPeriod());
+ final DateTime roundedSubscriptionEndDate = InvoiceDateUtils.roundDateTimeToDate(subscriptionEndDate, DateTimeZone.UTC);
+ Assert.assertEquals(invoiceItem.getEndDate(), roundedSubscriptionEndDate);
Assert.assertEquals(invoiceItem.getExternalKey(), bundle.getKey());
Assert.assertEquals(invoiceItem.getInvoiceId(), invoice.getInvoiceId());
Assert.assertEquals(invoiceItem.getItemType(), "FIXED");
@@ -255,11 +460,124 @@ public class TestAnalytics extends TestIntegrationBase {
Assert.assertEquals(invoiceItem.getProductName(), subscription.getCurrentPlan().getProduct().getName());
Assert.assertEquals(invoiceItem.getProductType(), subscription.getCurrentPlan().getProduct().getCatalogName());
Assert.assertEquals(invoiceItem.getSlug(), subscription.getCurrentPhase().getName());
- Assert.assertEquals(invoiceItem.getStartDate(), subscription.getStartDate());
+ final DateTime subscriptionStartDate = subscription.getStartDate();
+ final DateTime roundedSubscriptionStartDate = InvoiceDateUtils.roundDateTimeToDate(subscriptionStartDate, DateTimeZone.UTC);
+ Assert.assertEquals(invoiceItem.getStartDate(), roundedSubscriptionStartDate);
return subscription;
}
+ private void verifyBSTWithTrialAndEvergreenPhases(final Account account, final SubscriptionBundle bundle, final Subscription subscription) throws CatalogApiException {
+ // BST should have two transitions
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+ Assert.assertEquals(transitions.size(), 2);
+
+ verifyTrialAndEvergreenPhases(account, bundle, subscription);
+ }
+
+ private void verifyBSTWithTrialAndEvergreenPhasesAndCancellation(final Account account, final SubscriptionBundle bundle, final Subscription subscription) throws CatalogApiException {
+ // BST should have three transitions
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+ Assert.assertEquals(transitions.size(), 3);
+
+ verifyTrialAndEvergreenPhases(account, bundle, subscription);
+ verifyCancellationTransition(account, bundle);
+ }
+
+ private void verifyBSTWithTrialAndEvergreenPhasesAndCancellationAndSystemCancellation(final Account account, final SubscriptionBundle bundle, final Subscription subscription) throws CatalogApiException {
+ // BST should have four transitions
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+ Assert.assertEquals(transitions.size(), 4);
+
+ verifyTrialAndEvergreenPhases(account, bundle, subscription);
+ verifyCancellationTransition(account, bundle);
+ verifySystemCancellationTransition(account, bundle);
+ }
+
+ private void verifyTrialAndEvergreenPhases(final Account account, final SubscriptionBundle bundle, final Subscription subscription) throws CatalogApiException {
+ final Product currentProduct = subscriptionPlan.getProduct();
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+
+ // Check the first transition (into trial phase)
+ final BusinessSubscriptionTransition initialTransition = transitions.get(0);
+ Assert.assertEquals(initialTransition.getBundleId(), bundle.getId());
+ Assert.assertEquals(initialTransition.getExternalKey(), bundle.getKey());
+ Assert.assertEquals(initialTransition.getAccountId(), account.getId());
+ Assert.assertEquals(initialTransition.getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(initialTransition.getSubscriptionId(), subscription.getId());
+ Assert.assertEquals(initialTransition.getEvent().getCategory(), currentProduct.getCategory());
+ Assert.assertEquals(initialTransition.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.ADD);
+
+ // This is the first transition
+ Assert.assertNull(initialTransition.getPreviousSubscription());
+
+ Assert.assertEquals(initialTransition.getNextSubscription().getBillingPeriod(), BillingPeriod.NO_BILLING_PERIOD.toString());
+ Assert.assertEquals(initialTransition.getNextSubscription().getCurrency(), account.getCurrency().toString());
+ Assert.assertEquals(initialTransition.getNextSubscription().getPhase(), PhaseType.TRIAL.toString());
+ // Trial: fixed price of zero
+ Assert.assertEquals(initialTransition.getNextSubscription().getPrice().doubleValue(), (double) 0);
+ Assert.assertEquals(initialTransition.getNextSubscription().getPriceList(), subscription.getCurrentPriceList().getName());
+ Assert.assertEquals(initialTransition.getNextSubscription().getProductCategory(), currentProduct.getCategory());
+ Assert.assertEquals(initialTransition.getNextSubscription().getProductName(), currentProduct.getName());
+ Assert.assertEquals(initialTransition.getNextSubscription().getProductType(), currentProduct.getCatalogName());
+ Assert.assertEquals(initialTransition.getNextSubscription().getSlug(), currentProduct.getName().toLowerCase() + "-monthly-trial");
+ Assert.assertEquals(initialTransition.getNextSubscription().getStartDate(), subscription.getStartDate());
+ Assert.assertEquals(initialTransition.getNextSubscription().getState(), Subscription.SubscriptionState.ACTIVE);
+
+ // Check the second transition (from trial to evergreen)
+ final BusinessSubscriptionTransition futureTransition = transitions.get(1);
+ Assert.assertEquals(futureTransition.getExternalKey(), bundle.getKey());
+ Assert.assertEquals(futureTransition.getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(futureTransition.getEvent().getCategory(), currentProduct.getCategory());
+ Assert.assertEquals(futureTransition.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.SYSTEM_CHANGE);
+
+ Assert.assertEquals(futureTransition.getPreviousSubscription(), initialTransition.getNextSubscription());
+
+ // The billing period should have changed (NO_BILLING_PERIOD for the trial period)
+ Assert.assertEquals(futureTransition.getNextSubscription().getBillingPeriod(), BillingPeriod.MONTHLY.toString());
+ Assert.assertEquals(initialTransition.getNextSubscription().getCurrency(), account.getCurrency().toString());
+ // From trial to evergreen
+ Assert.assertEquals(futureTransition.getNextSubscription().getPhase(), PhaseType.EVERGREEN.toString());
+ Assert.assertTrue(futureTransition.getNextSubscription().getPrice().doubleValue() > 0);
+ Assert.assertEquals(futureTransition.getNextSubscription().getPriceList(), subscription.getCurrentPriceList().getName());
+ Assert.assertEquals(futureTransition.getNextSubscription().getProductCategory(), currentProduct.getCategory());
+ Assert.assertEquals(futureTransition.getNextSubscription().getProductName(), currentProduct.getName());
+ Assert.assertEquals(futureTransition.getNextSubscription().getProductType(), currentProduct.getCatalogName());
+ Assert.assertEquals(futureTransition.getNextSubscription().getSlug(), currentProduct.getName().toLowerCase() + "-monthly-evergreen");
+ // 30 days trial
+ Assert.assertEquals(futureTransition.getNextSubscription().getStartDate(), subscription.getStartDate().plusDays(30));
+ Assert.assertEquals(futureTransition.getNextSubscription().getState(), Subscription.SubscriptionState.ACTIVE);
+ }
+
+ private void verifyCancellationTransition(final Account account, final SubscriptionBundle bundle) throws CatalogApiException {
+ final Product currentProduct = subscriptionPlan.getProduct();
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+
+ final BusinessSubscriptionTransition cancellationRequest = transitions.get(2);
+ Assert.assertEquals(cancellationRequest.getExternalKey(), bundle.getKey());
+ Assert.assertEquals(cancellationRequest.getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(cancellationRequest.getEvent().getCategory(), currentProduct.getCategory());
+ Assert.assertEquals(cancellationRequest.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.CANCEL);
+
+ Assert.assertNull(cancellationRequest.getNextSubscription());
+ // The actual content has already been checked in verifyTrialAndEvergreenPhases
+ Assert.assertEquals(cancellationRequest.getPreviousSubscription(), transitions.get(1).getNextSubscription());
+ }
+
+ private void verifySystemCancellationTransition(final Account account, final SubscriptionBundle bundle) throws CatalogApiException {
+ final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
+
+ final BusinessSubscriptionTransition systemCancellation = transitions.get(3);
+ Assert.assertEquals(systemCancellation.getExternalKey(), bundle.getKey());
+ Assert.assertEquals(systemCancellation.getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(systemCancellation.getEvent().getCategory(), ProductCategory.BASE);
+ Assert.assertEquals(systemCancellation.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.SYSTEM_CANCEL);
+
+ Assert.assertNull(systemCancellation.getNextSubscription());
+ // The actual content has already been checked in verifyTrialAndEvergreenPhases
+ Assert.assertEquals(systemCancellation.getPreviousSubscription(), transitions.get(1).getNextSubscription());
+ }
+
private void verifyChangePlan(final Account account, final SubscriptionBundle bundle, final Subscription subscription) throws EntitlementUserApiException, InterruptedException {
final String newProductName = "Assault-Rifle";
final BillingPeriod newTerm = BillingPeriod.MONTHLY;
@@ -269,13 +587,16 @@ public class TestAnalytics extends TestIntegrationBase {
waitALittle();
- // BST should have two transitions
+ // BST should have three transitions (a ADD_BASE, CHANGE_BASE and SYSTEM_CHANGE_BASE)
final List<BusinessSubscriptionTransition> transitions = analyticsUserApi.getTransitionsForBundle(bundle.getKey());
- Assert.assertEquals(transitions.size(), 2);
+ Assert.assertEquals(transitions.size(), 3);
final BusinessSubscriptionTransition previousTransition = transitions.get(0);
final BusinessSubscriptionTransition transition = transitions.get(1);
+ Assert.assertEquals(transition.getBundleId(), bundle.getId());
Assert.assertEquals(transition.getExternalKey(), bundle.getKey());
+ Assert.assertEquals(transition.getAccountId(), account.getId());
Assert.assertEquals(transition.getAccountKey(), account.getExternalKey());
+ Assert.assertEquals(transition.getSubscriptionId(), subscription.getId());
Assert.assertEquals(transition.getEvent().getCategory(), ProductCategory.BASE);
Assert.assertEquals(transition.getEvent().getEventType(), BusinessSubscriptionEvent.EventType.CHANGE);
@@ -286,7 +607,6 @@ public class TestAnalytics extends TestIntegrationBase {
// Verify the next subscription
// No billing period for the trial phase
Assert.assertEquals(transition.getNextSubscription().getBillingPeriod(), BillingPeriod.NO_BILLING_PERIOD.toString());
- Assert.assertEquals(transition.getNextSubscription().getBundleId(), subscription.getBundleId());
Assert.assertEquals(transition.getNextSubscription().getCurrency(), account.getCurrency().toString());
Assert.assertEquals(transition.getNextSubscription().getPhase(), PhaseType.TRIAL.toString());
// We're still in trial
@@ -298,8 +618,6 @@ public class TestAnalytics extends TestIntegrationBase {
Assert.assertEquals(transition.getNextSubscription().getSlug(), subscription.getCurrentPhase().getName());
Assert.assertEquals(transition.getNextSubscription().getStartDate(), requestedDate);
Assert.assertEquals(transition.getNextSubscription().getState(), Subscription.SubscriptionState.ACTIVE);
- // It's still the same subscription
- Assert.assertEquals(transition.getNextSubscription().getSubscriptionId(), subscription.getId());
// The account should have two invoices for the trial phase of both subscriptions
Assert.assertEquals(analyticsUserApi.getInvoicesForAccount(account.getExternalKey()).size(), 2);
@@ -317,6 +635,6 @@ public class TestAnalytics extends TestIntegrationBase {
private void waitALittle() throws InterruptedException {
// We especially need to wait for entitlement events
- Thread.sleep(2000);
+ Thread.sleep(4000);
}
}
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 15910a3..9139a3e 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
@@ -41,123 +41,91 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
-@Test(groups = "slow")
@Guice(modules = {BeatrixModule.class})
public class TestIntegration extends TestIntegrationBase {
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testBasePlanCompleteWithBillingDayInPast() throws Exception {
log.info("Starting testBasePlanCompleteWithBillingDayInPast");
- final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
testBasePlanComplete(startDate, 31, false);
}
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testBasePlanCompleteWithBillingDayPresent() throws Exception {
log.info("Starting testBasePlanCompleteWithBillingDayPresent");
- final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
testBasePlanComplete(startDate, 1, false);
}
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testBasePlanCompleteWithBillingDayAlignedWithTrial() throws Exception {
log.info("Starting testBasePlanCompleteWithBillingDayAlignedWithTrial");
- final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
testBasePlanComplete(startDate, 2, false);
}
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testBasePlanCompleteWithBillingDayInFuture() throws Exception {
log.info("Starting testBasePlanCompleteWithBillingDayInFuture");
- final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime startDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
testBasePlanComplete(startDate, 3, true);
}
- @Test(groups = {"slow", "stress"}, enabled = false)
+ @Test(groups = {"stress"})
public void stressTest() throws Exception {
- final int maxIterations = 7;
+ final int maxIterations = 100;
for (int curIteration = 0; curIteration < maxIterations; curIteration++) {
+ if (curIteration != 0) {
+ setupTest();
+ }
+
log.info("################################ ITERATION " + curIteration + " #########################");
Thread.sleep(1000);
- setupTest();
testBasePlanCompleteWithBillingDayPresent();
Thread.sleep(1000);
+ cleanupTest();
setupTest();
testBasePlanCompleteWithBillingDayInPast();
Thread.sleep(1000);
+ cleanupTest();
setupTest();
testBasePlanCompleteWithBillingDayAlignedWithTrial();
Thread.sleep(1000);
+ cleanupTest();
setupTest();
testBasePlanCompleteWithBillingDayInFuture();
+ if (curIteration < maxIterations - 1) {
+ cleanupTest();
+ Thread.sleep(1000);
+ }
+
}
}
-// // STEPH set to disabled until test written properly and fixed
-// @Test(groups = "slow", enabled = true)
-// public void testRepairChangeBPWithAddonIncluded() throws Exception {
-//
-// log.info("Starting testRepairChangeBPWithAddonIncluded");
-//
-// DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
-// clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
-//
-// Account account = createAccountWithPaymentMethod(getAccountData(25));
-// 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 baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
-// new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
-// assertNotNull(baseSubscription);
-// assertTrue(busHandler.isCompleted(DELAY));
-//
-// // MOVE CLOCK A LITTLE BIT-- STILL IN TRIAL
-// Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(3));
-// clock.addDeltaFromReality(it.toDurationMillis());
-//
-// busHandler.pushExpectedEvent(NextEvent.CREATE);
-// busHandler.pushExpectedEvent(NextEvent.INVOICE);
-// busHandler.pushExpectedEvent(NextEvent.PAYMENT);
-// subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
-// new PlanPhaseSpecifier("Telescopic-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null), null, context));
-// assertTrue(busHandler.isCompleted(DELAY));
-//
-// busHandler.pushExpectedEvent(NextEvent.CREATE);
-// busHandler.pushExpectedEvent(NextEvent.INVOICE);
-// busHandler.pushExpectedEvent(NextEvent.PAYMENT);
-// subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
-// new PlanPhaseSpecifier("Laser-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null), null, context));
-// assertTrue(busHandler.isCompleted(DELAY));
-//
-//
-// // 26 / 5
-// int duration = 28;
-// it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(duration));
-// busHandler.pushExpectedEvent(NextEvent.PHASE);
-// busHandler.pushExpectedEvent(NextEvent.PHASE);
-// busHandler.pushExpectedEvent(NextEvent.PHASE);
-// busHandler.pushExpectedEvent(NextEvent.INVOICE);
-// busHandler.pushExpectedEvent(NextEvent.PAYMENT);
-// clock.addDeltaFromReality(it.toDurationMillis());
-// assertTrue(busHandler.isCompleted(DELAY));
-//
-// assertListenerStatus();
-// }
-
- // STEPH set to disabled until test written properly and fixed
- @Test(groups = "slow", enabled = false)
- public void testRepairChangeBPWithAddonIncluded() throws Exception {
+ @Test(groups = {"stress"})
+ public void stressTestDebug() throws Exception {
+ final int maxIterations = 100;
+ for (int curIteration = 0; curIteration < maxIterations; curIteration++) {
+ log.info("################################ ITERATION " + curIteration + " #########################");
+ if (curIteration != 0) {
+ setupTest();
+ }
+ testAddonsWithMultipleAlignments();
+ if (curIteration < maxIterations - 1) {
+ cleanupTest();
+ Thread.sleep(1000);
+ }
+ }
+ }
+
+
+ @Test(groups = "slow")
+ public void testAddonsWithMultipleAlignments() throws Exception {
log.info("Starting testRepairChangeBPWithAddonIncluded");
- final DateTime initialDate = new DateTime(2012, 4, 25, 0, 13, 42, 0);
+ final DateTime initialDate = new DateTime(2012, 4, 25, 0, 13, 42, 0, testTimeZone);
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
final Account account = createAccountWithPaymentMethod(getAccountData(25));
@@ -199,19 +167,16 @@ public class TestIntegration extends TestIntegrationBase {
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
- // MOVE CLOCK A LITTLE BIT MORE -- EITHER STAY IN TRIAL OR GET OUT
+ // MOVE CLOCK A LITTLE BIT MORE -- EITHER STAY IN TRIAL OR GET OUT
busHandler.pushExpectedEvent(NextEvent.PHASE);
busHandler.pushExpectedEvent(NextEvent.PHASE);
- busHandler.pushExpectedEvent(NextEvent.INVOICE);
busHandler.pushExpectedEvent(NextEvent.PAYMENT);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
- busHandler.pushExpectedEvent(NextEvent.PAYMENT);
log.info("Moving clock from" + clock.getUTCNow() + " to " + clock.getUTCNow().plusDays(28));
clock.addDays(28);// 26 / 5
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
-
busHandler.pushExpectedEvent(NextEvent.PHASE);
busHandler.pushExpectedEvent(NextEvent.INVOICE);
busHandler.pushExpectedEvent(NextEvent.PAYMENT);
@@ -220,13 +185,11 @@ public class TestIntegration extends TestIntegrationBase {
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
-
log.info("Moving clock from" + clock.getUTCNow() + " to " + clock.getUTCNow().plusDays(10));
clock.addDays(10);// 8 / 6
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
-
busHandler.pushExpectedEvent(NextEvent.INVOICE);
busHandler.pushExpectedEvent(NextEvent.PAYMENT);
log.info("Moving clock from" + clock.getUTCNow() + " to " + clock.getUTCNow().plusDays(18));
@@ -238,8 +201,6 @@ public class TestIntegration extends TestIntegrationBase {
clock.addDays(3);
assertTrue(busHandler.isCompleted(DELAY));
assertListenerStatus();
-
-
}
@@ -252,7 +213,7 @@ public class TestIntegration extends TestIntegrationBase {
final UUID accountId = account.getId();
assertNotNull(account);
- final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
+ final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0, testTimeZone);
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
final SubscriptionBundle bundle = entitlementUserApi.createBundleForAccount(account.getId(), "someBundle", context);
@@ -275,12 +236,12 @@ public class TestIntegration extends TestIntegrationBase {
// TODO: Jeff implement repair
}
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testWithRecreatePlan() throws Exception {
log.info("Starting testWithRecreatePlan");
- final DateTime initialDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime initialDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
final int billingDay = 2;
log.info("Beginning test with BCD of " + billingDay);
@@ -351,7 +312,6 @@ public class TestIntegration extends TestIntegrationBase {
private void testBasePlanComplete(final DateTime initialCreationDate, final int billingDay,
final boolean proRationExpected) throws Exception {
-
log.info("Beginning test with BCD of " + billingDay);
final Account account = createAccountWithPaymentMethod(getAccountData(billingDay));
final UUID accountId = account.getId();
@@ -554,7 +514,7 @@ public class TestIntegration extends TestIntegrationBase {
log.info("Starting testForMultipleRecurringPhases");
- final DateTime initialCreationDate = new DateTime(2012, 2, 1, 0, 3, 42, 0);
+ final DateTime initialCreationDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
clock.setDeltaFromReality(initialCreationDate.getMillis() - clock.getUTCNow().getMillis());
final Account account = createAccountWithPaymentMethod(getAccountData(2));
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationBase.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationBase.java
index fbf4a68..f20ac76 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationBase.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationBase.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.beatrix.integration;
import java.io.IOException;
@@ -33,6 +34,7 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import com.google.inject.Inject;
+import com.google.inject.name.Named;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountData;
import com.ning.billing.account.api.AccountService;
@@ -41,6 +43,7 @@ import com.ning.billing.analytics.AnalyticsListener;
import com.ning.billing.analytics.api.user.DefaultAnalyticsUserApi;
import com.ning.billing.api.TestApiListener;
import com.ning.billing.api.TestListenerStatus;
+import com.ning.billing.beatrix.BeatrixTestSuiteWithEmbeddedDB;
import com.ning.billing.beatrix.lifecycle.Lifecycle;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.dbi.MysqlTestingHelper;
@@ -54,10 +57,13 @@ import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceService;
import com.ning.billing.invoice.api.InvoiceUserApi;
+import com.ning.billing.invoice.generator.InvoiceDateUtils;
import com.ning.billing.invoice.model.InvoicingConfiguration;
import com.ning.billing.junction.plumbing.api.BlockingSubscription;
+import com.ning.billing.overdue.wrapper.OverdueWrapperFactory;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentMethodPlugin;
+import com.ning.billing.payment.provider.MockPaymentProviderPlugin;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.callcontext.CallContext;
@@ -72,7 +78,9 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
-public class TestIntegrationBase implements TestListenerStatus {
+public class TestIntegrationBase extends BeatrixTestSuiteWithEmbeddedDB implements TestListenerStatus {
+ protected static final DateTimeZone testTimeZone = DateTimeZone.UTC;
+
protected static final int NUMBER_OF_DECIMALS = InvoicingConfiguration.getNumberOfDecimals();
protected static final int ROUNDING_METHOD = InvoicingConfiguration.getRoundingMode();
@@ -84,7 +92,6 @@ public class TestIntegrationBase implements TestListenerStatus {
protected static final Logger log = LoggerFactory.getLogger(TestIntegration.class);
protected static long AT_LEAST_ONE_MONTH_MS = 31L * 24L * 3600L * 1000L;
-
protected static final long DELAY = 5000;
@Inject
@@ -124,6 +131,13 @@ public class TestIntegrationBase implements TestListenerStatus {
@Inject
protected PaymentApi paymentApi;
+ @Named(BeatrixModule.PLUGIN_NAME)
+ @Inject
+ protected MockPaymentProviderPlugin paymentPlugin;
+
+ @Inject
+ protected OverdueWrapperFactory overdueWrapperFactory;
+
@Inject
protected AccountUserApi accountUserApi;
@@ -138,7 +152,6 @@ public class TestIntegrationBase implements TestListenerStatus {
protected TestApiListener busHandler;
-
private boolean isListenerFailed;
private String listenerFailedMsg;
@@ -154,7 +167,6 @@ public class TestIntegrationBase implements TestListenerStatus {
listenerFailedMsg = null;
}
-
protected void assertListenerStatus() {
if (isListenerFailed) {
log.error(listenerFailedMsg);
@@ -162,52 +174,17 @@ public class TestIntegrationBase implements TestListenerStatus {
}
}
- protected void setupMySQL() throws IOException {
- final String accountDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/account/ddl.sql"));
- final String analyticsDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/analytics/ddl.sql"));
- final String entitlementDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/entitlement/ddl.sql"));
- final String invoiceDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/invoice/ddl.sql"));
- final String paymentDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/payment/ddl.sql"));
- final String utilDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- final String junctionDb = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/junction/ddl.sql"));
-
- helper.startMysql();
-
- helper.initDb(accountDdl);
- helper.initDb(analyticsDdl);
- helper.initDb(entitlementDdl);
- helper.initDb(invoiceDdl);
- helper.initDb(paymentDdl);
- helper.initDb(utilDdl);
- helper.initDb(junctionDb);
- }
-
-
@BeforeClass(groups = "slow")
public void setup() throws Exception {
-
- setupMySQL();
-
context = new DefaultCallContextFactory(clock).createCallContext("Integration Test", CallOrigin.TEST, UserType.TEST);
busHandler = new TestApiListener(this);
-
}
- @AfterClass(groups = "slow")
- public void tearDown() throws Exception {
- helper.stopMysql();
- }
-
-
@BeforeMethod(groups = "slow")
public void setupTest() throws Exception {
-
log.warn("\n");
log.warn("RESET TEST FRAMEWORK\n\n");
- // Pre test cleanup
- helper.cleanupAllTables();
-
clock.resetDeltaFromReality();
resetTestListenerStatus();
@@ -226,7 +203,6 @@ public class TestIntegrationBase implements TestListenerStatus {
log.warn("DONE WITH TEST\n");
}
-
protected void verifyTestResult(final UUID accountId, final UUID subscriptionId,
final DateTime startDate, final DateTime endDate,
final BigDecimal amount, final DateTime chargeThroughDate,
@@ -242,9 +218,12 @@ public class TestIntegrationBase implements TestListenerStatus {
boolean wasFound = false;
+ // Make sure to round the dates in the comparisons as the invoice items dates are rounded
+ final DateTime roundedStartDate = InvoiceDateUtils.roundDateTimeToDate(startDate, testTimeZone);
+ final DateTime roundedEndDate = InvoiceDateUtils.roundDateTimeToDate(endDate, testTimeZone);
for (final InvoiceItem item : invoiceItems) {
- if (item.getStartDate().compareTo(startDate) == 0) {
- if (item.getEndDate().compareTo(endDate) == 0) {
+ if (item.getStartDate().compareTo(roundedStartDate) == 0) {
+ if (item.getEndDate().compareTo(roundedEndDate) == 0) {
if (item.getAmount().compareTo(amount) == 0) {
wasFound = true;
break;
@@ -261,7 +240,8 @@ public class TestIntegrationBase implements TestListenerStatus {
assertNotNull(ctd);
log.info("Checking CTD: " + ctd.toString() + "; clock is " + clock.getUTCNow().toString());
assertTrue(clock.getUTCNow().isBefore(ctd));
- assertTrue(ctd.compareTo(chargeThroughDate) == 0);
+ // The CTD is rounded too
+ assertTrue(ctd.compareTo(InvoiceDateUtils.roundDateTimeToDate(chargeThroughDate, testTimeZone)) == 0);
}
protected SubscriptionData subscriptionDataFromSubscription(final Subscription sub) {
@@ -293,11 +273,11 @@ public class TestIntegrationBase implements TestListenerStatus {
return UUID.randomUUID().toString();
}
};
+
paymentApi.addPaymentMethod(BeatrixModule.PLUGIN_NAME, account, true, info, context);
return accountUserApi.getAccountById(account.getId());
}
-
protected AccountData getAccountData(final int billingDay) {
final String someRandomKey = UUID.randomUUID().toString();
return new AccountData() {
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
index 426bac7..217cb1b 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoInvoiceOffTag.java
@@ -79,9 +79,9 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
@Test(groups = {"slow"}, enabled = true)
public void testAutoInvoiceOffAccount() throws Exception {
clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
- addTag(account.getId(), ObjectType.ACCOUNT);
+ add_AUTO_INVOICING_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
- // set next invoice to fail and create network
+ // set next invoice to fail and create network
busHandler.pushExpectedEvents(NextEvent.CREATE);
final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
@@ -111,7 +111,7 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
public void testAutoInvoiceOffSingleSubscription() throws Exception {
clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
- // set next invoice to fail and create network
+ // set next invoice to fail and create network
busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.INVOICE);
final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
@@ -122,7 +122,7 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
assertEquals(invoices.size(), 1); // first invoice is generated immediately after creation can't reliably stop it
- addTag(baseSubscription.getBundleId(), ObjectType.BUNDLE);
+ add_AUTO_INVOICING_OFF_Tag(baseSubscription.getBundleId(), ObjectType.BUNDLE);
busHandler.pushExpectedEvents(NextEvent.PHASE);
clock.addDays(40); // DAY 40 out of trial
@@ -138,7 +138,7 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
public void testAutoInvoiceOffMultipleSubscriptions() throws Exception {
clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
- // set next invoice to fail and create network
+ // set next invoice to fail and create network
busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.INVOICE);
final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
@@ -156,7 +156,7 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
Collection<Invoice> invoices = invoiceApi.getInvoicesByAccount(account.getId());
assertEquals(invoices.size(), 2); // first invoice is generated immediately after creation can't reliably stop it
- addTag(baseSubscription.getBundleId(), ObjectType.BUNDLE);
+ add_AUTO_INVOICING_OFF_Tag(baseSubscription.getBundleId(), ObjectType.BUNDLE);
busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.PHASE, NextEvent.INVOICE);
clock.addDays(40); // DAY 40 out of trial
@@ -167,7 +167,7 @@ public class TestIntegrationWithAutoInvoiceOffTag extends TestIntegrationBase {
}
- private void addTag(final UUID id, final ObjectType type) throws TagDefinitionApiException, TagApiException {
+ private void add_AUTO_INVOICING_OFF_Tag(final UUID id, final ObjectType type) throws TagDefinitionApiException, TagApiException {
final TagDefinition def = tagApi.getTagDefinition(ControlTagType.AUTO_INVOICING_OFF.name());
tagApi.addTag(id, type, def, context);
final Map<String, Tag> tags = tagApi.getTags(id, type);
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java
new file mode 100644
index 0000000..b988c7a
--- /dev/null
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/integration/TestIntegrationWithAutoPayOff.java
@@ -0,0 +1,294 @@
+/*
+ * 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.beatrix.integration;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
+import java.math.BigDecimal;
+import java.util.Collection;
+import java.util.Map;
+import java.util.UUID;
+
+import junit.framework.Assert;
+
+import org.joda.time.DateTime;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Guice;
+import org.testng.annotations.Test;
+
+import com.google.inject.Inject;
+import com.ning.billing.account.api.Account;
+import com.ning.billing.api.TestApiListener.NextEvent;
+import com.ning.billing.catalog.api.BillingPeriod;
+import com.ning.billing.catalog.api.PlanPhaseSpecifier;
+import com.ning.billing.catalog.api.PriceListSet;
+import com.ning.billing.catalog.api.ProductCategory;
+import com.ning.billing.config.PaymentConfig;
+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.InvoiceUserApi;
+import com.ning.billing.util.api.TagApiException;
+import com.ning.billing.util.api.TagDefinitionApiException;
+import com.ning.billing.util.api.TagUserApi;
+import com.ning.billing.util.dao.ObjectType;
+import com.ning.billing.util.tag.ControlTagType;
+import com.ning.billing.util.tag.Tag;
+import com.ning.billing.util.tag.TagDefinition;
+
+@Guice(modules = {BeatrixModule.class})
+public class TestIntegrationWithAutoPayOff extends TestIntegrationBase {
+
+
+ @Inject
+ private InvoiceUserApi invoiceApi;
+
+ @Inject
+ private TagUserApi tagApi;
+
+ @Inject
+ private PaymentConfig paymentConfig;
+
+
+ private Account account;
+ private SubscriptionBundle bundle;
+ private String productName;
+ private BillingPeriod term;
+ private String planSetName;
+
+ @BeforeMethod(groups = {"slow"})
+ public void setupOverdue() throws Exception {
+
+ account = createAccountWithPaymentMethod(getAccountData(25));
+ assertNotNull(account);
+
+ bundle = entitlementUserApi.createBundleForAccount(account.getId(), "whatever", context);
+
+ productName = "Shotgun";
+ term = BillingPeriod.MONTHLY;
+ planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
+ }
+
+ @Test(groups = {"slow"}, enabled = true)
+ public void testAutoPayOff() throws Exception {
+ clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
+ add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ busHandler.pushExpectedEvents(NextEvent.CREATE);
+ final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
+ new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
+ assertNotNull(baseSubscription);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ Collection<Invoice> invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 1);
+
+ busHandler.pushExpectedEvents(NextEvent.PHASE);
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ clock.addDays(40); // After trial
+
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT);
+ remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
+ assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
+ }
+ assertListenerStatus();
+ }
+
+
+ @Test(groups = {"slow"}, enabled = true)
+ public void testAutoPayOffWithPaymentFailure() throws Exception {
+ clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
+ add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ busHandler.pushExpectedEvents(NextEvent.CREATE);
+ final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
+ new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
+ assertNotNull(baseSubscription);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ Collection<Invoice> invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 1);
+
+ busHandler.pushExpectedEvents(NextEvent.PHASE);
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ clock.addDays(40); // After trial
+
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+
+ paymentPlugin.makeNextPaymentFailWithError();
+ remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT_ERROR);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+ assertListenerStatus();
+
+ int nbDaysBeforeRetry = paymentConfig.getPaymentRetryDays().get(0);
+
+ // MOVE TIME FOR RETRY TO HAPPEN
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT);
+ clock.addDays(nbDaysBeforeRetry + 1);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
+ assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
+ }
+ assertListenerStatus();
+
+ }
+
+
+ @Test(groups = {"slow"}, enabled = true)
+ public void testAutoPayOffWithPaymentFailureOn_AUTO_PAY_OFF() throws Exception {
+ clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0));
+ add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ busHandler.pushExpectedEvents(NextEvent.CREATE);
+ final SubscriptionData baseSubscription = subscriptionDataFromSubscription(entitlementUserApi.createSubscription(bundle.getId(),
+ new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSetName, null), null, context));
+ assertNotNull(baseSubscription);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ Collection<Invoice> invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 1);
+
+ busHandler.pushExpectedEvents(NextEvent.PHASE);
+ busHandler.pushExpectedEvents(NextEvent.INVOICE);
+ clock.addDays(40); // After trial
+
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+
+ paymentPlugin.makeNextPaymentFailWithError();
+ remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT_ERROR);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+ assertListenerStatus();
+
+ int nbDaysBeforeRetry = paymentConfig.getPaymentRetryDays().get(0);
+
+ // AUTO_PAY_OFF to ON
+ add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+
+ // MOVE TIME FOR RETRY TO HAPPEN
+ clock.addDays(nbDaysBeforeRetry + 1);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+ assertEquals(invoices.size(), 2);
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertEquals(cur.getBalance(), cur.getChargedAmount());
+ }
+ assertListenerStatus();
+
+ // SWICTH BACK AUTO_PAY_OFF OFF
+ busHandler.pushExpectedEvents(NextEvent.PAYMENT);
+ remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
+ assertTrue(busHandler.isCompleted(DELAY));
+
+
+ invoices = invoiceApi.getInvoicesByAccount(account.getId());
+ for (Invoice cur : invoices) {
+ if (cur.getChargedAmount().compareTo(BigDecimal.ZERO) == 0) {
+ continue;
+ }
+ assertTrue(cur.getBalance().compareTo(BigDecimal.ZERO) == 0);
+ assertTrue(cur.getPaidAmount().compareTo(cur.getChargedAmount()) == 0);
+ }
+ assertListenerStatus();
+
+ }
+
+
+ private void add_AUTO_PAY_OFF_Tag(final UUID id, final ObjectType type) throws TagDefinitionApiException, TagApiException {
+ final TagDefinition def = tagApi.getTagDefinition(ControlTagType.AUTO_PAY_OFF.name());
+ tagApi.addTag(id, type, def, context);
+ final Map<String, Tag> tags = tagApi.getTags(id, type);
+ assertNotNull(tags.get(ControlTagType.AUTO_PAY_OFF.name()));
+ }
+
+ private void remove_AUTO_PAY_OFF_Tag(final UUID id, final ObjectType type) throws TagDefinitionApiException, TagApiException {
+ final TagDefinition def = tagApi.getTagDefinition(ControlTagType.AUTO_PAY_OFF.name());
+ tagApi.removeTag(id, type, def, context);
+ }
+}
+
diff --git a/beatrix/src/test/java/com/ning/billing/beatrix/lifecycle/TestLifecycle.java b/beatrix/src/test/java/com/ning/billing/beatrix/lifecycle/TestLifecycle.java
index ac41b0e..649297c 100644
--- a/beatrix/src/test/java/com/ning/billing/beatrix/lifecycle/TestLifecycle.java
+++ b/beatrix/src/test/java/com/ning/billing/beatrix/lifecycle/TestLifecycle.java
@@ -27,13 +27,12 @@ import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Stage;
+import com.ning.billing.beatrix.BeatrixTestSuite;
import com.ning.billing.lifecycle.KillbillService;
import com.ning.billing.lifecycle.LifecycleHandlerType;
import com.ning.billing.lifecycle.LifecycleHandlerType.LifecycleLevel;
-
-public class TestLifecycle {
-
+public class TestLifecycle extends BeatrixTestSuite {
private static final Logger log = LoggerFactory.getLogger(TestLifecycle.class);
private Service1 s1;
@@ -42,7 +41,6 @@ public class TestLifecycle {
private DefaultLifecycle lifecycle;
public static class ServiceBase {
-
private int count = 0;
public ServiceBase() {
@@ -63,7 +61,6 @@ public class TestLifecycle {
}
public static class Service1 extends ServiceBase implements KillbillService {
-
@LifecycleHandlerType(LifecycleLevel.INIT_BUS)
public void initBus() {
log.info("Service1 : got INIT_BUS");
@@ -89,7 +86,6 @@ public class TestLifecycle {
}
public static class Service2 extends ServiceBase implements KillbillService {
-
@LifecycleHandlerType(LifecycleLevel.LOAD_CATALOG)
public void loadCatalog() {
log.info("Service2 : got LOAD_CATALOG");
@@ -120,8 +116,7 @@ public class TestLifecycle {
}
}
-
- @BeforeClass(alwaysRun = true)
+ @BeforeClass(groups = "fast")
public void setup() {
final Injector g = Guice.createInjector(Stage.DEVELOPMENT, new TestLifecycleModule());
s1 = g.getInstance(Service1.class);
@@ -129,7 +124,7 @@ public class TestLifecycle {
lifecycle = g.getInstance(DefaultLifecycle.class);
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testLifecycle() {
s1.reset();
s2.reset();
@@ -153,7 +148,6 @@ public class TestLifecycle {
}
public static class LifecycleNoWarn extends DefaultLifecycle {
-
@Inject
public LifecycleNoWarn(final Injector injector) {
super(injector);
@@ -165,14 +159,12 @@ public class TestLifecycle {
}
public static class TestLifecycleModule extends AbstractModule {
-
@Override
protected void configure() {
bind(DefaultLifecycle.class).to(LifecycleNoWarn.class).asEagerSingleton();
bind(Service1.class).asEagerSingleton();
bind(Service2.class).asEagerSingleton();
}
-
}
}
catalog/pom.xml 7(+6 -1)
diff --git a/catalog/pom.xml b/catalog/pom.xml
index 970a8a6..633f30b 100644
--- a/catalog/pom.xml
+++ b/catalog/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-catalog</artifactId>
@@ -39,6 +39,11 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
diff --git a/catalog/src/main/java/com/ning/billing/catalog/io/VersionedCatalogLoader.java b/catalog/src/main/java/com/ning/billing/catalog/io/VersionedCatalogLoader.java
index 95f5590..4bc57e3 100644
--- a/catalog/src/main/java/com/ning/billing/catalog/io/VersionedCatalogLoader.java
+++ b/catalog/src/main/java/com/ning/billing/catalog/io/VersionedCatalogLoader.java
@@ -22,6 +22,7 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.List;
+import com.google.common.io.Resources;
import com.google.inject.Inject;
import com.ning.billing.catalog.StandaloneCatalog;
import com.ning.billing.catalog.VersionedCatalog;
@@ -48,10 +49,23 @@ public class VersionedCatalogLoader implements ICatalogLoader {
try {
List<URI> xmlURIs = null;
- if (uriString.endsWith(XML_EXTENSION)) { //assume its an xml file
+ if (uriString.endsWith(XML_EXTENSION)) { // Assume its an xml file
xmlURIs = new ArrayList<URI>();
- xmlURIs.add(new URI(uriString));
- } else { //assume its a directory
+ URI uri = new URI(uriString);
+
+ // Try to expand the full path, if possible
+ final String schemeSpecificPart = uri.getSchemeSpecificPart();
+ if (schemeSpecificPart != null) {
+ final String[] split = schemeSpecificPart.split("/");
+ final String fileName = split[split.length - 1];
+ try {
+ uri = new URI(Resources.getResource(fileName).toExternalForm());
+ } catch (IllegalArgumentException ignored) {
+ }
+ }
+
+ xmlURIs.add(uri);
+ } else { // Assume its a directory
final String directoryContents = UriAccessor.accessUriAsString(uriString);
xmlURIs = findXmlReferences(directoryContents, new URL(uriString));
}
@@ -61,6 +75,7 @@ public class VersionedCatalogLoader implements ICatalogLoader {
final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(u, StandaloneCatalog.class);
result.add(catalog);
}
+
return result;
} catch (Exception e) {
throw new ServiceException("Problem encountered loading catalog", e);
diff --git a/catalog/src/test/java/com/ning/billing/catalog/CatalogTestSuite.java b/catalog/src/test/java/com/ning/billing/catalog/CatalogTestSuite.java
new file mode 100644
index 0000000..1db1839
--- /dev/null
+++ b/catalog/src/test/java/com/ning/billing/catalog/CatalogTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.catalog;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class CatalogTestSuite extends KillbillTestSuite {
+}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/io/TestVersionedCatalogLoader.java b/catalog/src/test/java/com/ning/billing/catalog/io/TestVersionedCatalogLoader.java
index dc2b28b..ac30ca3 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/io/TestVersionedCatalogLoader.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/io/TestVersionedCatalogLoader.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.catalog.io;
import javax.xml.bind.JAXBException;
@@ -26,47 +27,43 @@ import java.util.Iterator;
import java.util.List;
import org.joda.time.DateTime;
+import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import com.google.common.io.Resources;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.StandaloneCatalog;
import com.ning.billing.catalog.VersionedCatalog;
import com.ning.billing.catalog.api.InvalidConfigException;
import com.ning.billing.lifecycle.KillbillService.ServiceException;
import com.ning.billing.util.clock.DefaultClock;
-import static org.testng.AssertJUnit.assertEquals;
-
-public class TestVersionedCatalogLoader {
+public class TestVersionedCatalogLoader extends CatalogTestSuite {
private final VersionedCatalogLoader loader = new VersionedCatalogLoader(new DefaultClock());
-
- @Test(enabled = true)
- public void testAppendToURI() throws MalformedURLException, IOException, URISyntaxException {
+ @Test(groups = "fast")
+ public void testAppendToURI() throws IOException, URISyntaxException {
final URL u1 = new URL("http://www.ning.com/foo");
- assertEquals("http://www.ning.com/foo/bar", loader.appendToURI(u1, "bar").toString());
+ Assert.assertEquals(loader.appendToURI(u1, "bar").toString(), "http://www.ning.com/foo/bar");
final URL u2 = new URL("http://www.ning.com/foo/");
- assertEquals("http://www.ning.com/foo/bar", loader.appendToURI(u2, "bar").toString());
-
+ Assert.assertEquals(loader.appendToURI(u2, "bar").toString(), "http://www.ning.com/foo/bar");
}
-
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testFindXmlFileReferences() throws MalformedURLException, URISyntaxException {
final String page = "dg.xml\n" +
"replica.foo\n" +
"snv1/\n" +
"viking.xml\n";
final List<URI> urls = loader.findXmlFileReferences(page, new URL("http://ning.com/"));
- assertEquals(2, urls.size());
- assertEquals("http://ning.com/dg.xml", urls.get(0).toString());
- assertEquals("http://ning.com/viking.xml", urls.get(1).toString());
-
+ Assert.assertEquals(urls.size(), 2);
+ Assert.assertEquals(urls.get(0).toString(), "http://ning.com/dg.xml");
+ Assert.assertEquals(urls.get(1).toString(), "http://ning.com/viking.xml");
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testExtractHrefs() {
final String page = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">" +
"<html>" +
@@ -86,12 +83,12 @@ public class TestVersionedCatalogLoader {
"<address>Apache/2.2.3 (CentOS) Server at <a href=\"mailto:kate@ning.com\">gepo.ningops.net</a> Port 80</address>" +
"</body></html>";
final List<String> hrefs = loader.extractHrefs(page);
- assertEquals(8, hrefs.size());
- assertEquals("/config/trunk/", hrefs.get(0));
- assertEquals("dg.xml", hrefs.get(1));
+ Assert.assertEquals(hrefs.size(), 8);
+ Assert.assertEquals(hrefs.get(0), "/config/trunk/");
+ Assert.assertEquals(hrefs.get(1), "dg.xml");
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testFindXmlUrlReferences() throws MalformedURLException, URISyntaxException {
final String page = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">" +
"<html>" +
@@ -111,22 +108,21 @@ public class TestVersionedCatalogLoader {
"<address>Apache/2.2.3 (CentOS) Server at <a href=\"mailto:kate@ning.com\">gepo.ningops.net</a> Port 80</address>" +
"</body></html>";
final List<URI> uris = loader.findXmlUrlReferences(page, new URL("http://ning.com/"));
- assertEquals(2, uris.size());
- assertEquals("http://ning.com/dg.xml", uris.get(0).toString());
- assertEquals("http://ning.com/viking.xml", uris.get(1).toString());
-
+ Assert.assertEquals(uris.size(), 2);
+ Assert.assertEquals(uris.get(0).toString(), "http://ning.com/dg.xml");
+ Assert.assertEquals(uris.get(1).toString(), "http://ning.com/viking.xml");
}
- @Test(enabled = true)
- public void testLoad() throws MalformedURLException, IOException, SAXException, InvalidConfigException, JAXBException, TransformerException, URISyntaxException, ServiceException {
+ @Test(groups = "fast")
+ public void testLoad() throws IOException, SAXException, InvalidConfigException, JAXBException, TransformerException, URISyntaxException, ServiceException {
final VersionedCatalog c = loader.load(Resources.getResource("versionedCatalog").toString());
- assertEquals(3, c.size());
+ Assert.assertEquals(c.size(), 3);
final Iterator<StandaloneCatalog> it = c.iterator();
DateTime dt = new DateTime("2011-01-01T00:00:00+00:00");
- assertEquals(dt.toDate(), it.next().getEffectiveDate());
+ Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
dt = new DateTime("2011-02-02T00:00:00+00:00");
- assertEquals(dt.toDate(), it.next().getEffectiveDate());
+ Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
dt = new DateTime("2011-03-03T00:00:00+00:00");
- assertEquals(dt.toDate(), it.next().getEffectiveDate());
+ Assert.assertEquals(it.next().getEffectiveDate(), dt.toDate());
}
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/io/TestXMLReader.java b/catalog/src/test/java/com/ning/billing/catalog/io/TestXMLReader.java
index b03f18b..8d91c8e 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/io/TestXMLReader.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/io/TestXMLReader.java
@@ -16,18 +16,22 @@
package com.ning.billing.catalog.io;
+import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.io.Resources;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.StandaloneCatalog;
import com.ning.billing.util.config.XMLLoader;
-public class TestXMLReader {
-
- @Test(enabled = true)
- public void testCatalogLoad() throws Exception {
- XMLLoader.getObjectFromString(Resources.getResource("WeaponsHire.xml").toExternalForm(), StandaloneCatalog.class);
- XMLLoader.getObjectFromString(Resources.getResource("WeaponsHireSmall.xml").toExternalForm(), StandaloneCatalog.class);
+public class TestXMLReader extends CatalogTestSuite {
+ @Test(groups = "fast")
+ public void testCatalogLoad() {
+ try {
+ XMLLoader.getObjectFromString(Resources.getResource("WeaponsHire.xml").toExternalForm(), StandaloneCatalog.class);
+ XMLLoader.getObjectFromString(Resources.getResource("WeaponsHireSmall.xml").toExternalForm(), StandaloneCatalog.class);
+ } catch (Exception e) {
+ Assert.fail(e.toString());
+ }
}
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/MockCatalogModule.java b/catalog/src/test/java/com/ning/billing/catalog/MockCatalogModule.java
index 4af0136..30435bb 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/MockCatalogModule.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/MockCatalogModule.java
@@ -16,24 +16,20 @@
package com.ning.billing.catalog;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.catalog.api.Catalog;
import com.ning.billing.catalog.api.CatalogService;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
public class MockCatalogModule extends AbstractModule {
-
@Override
protected void configure() {
- CatalogService catalogService = BrainDeadProxyFactory.createBrainDeadProxyFor(CatalogService.class);
- ((ZombieControl) catalogService).addResult("getCurrentCatalog", new MockCatalog());
-
- catalogService = BrainDeadProxyFactory.createBrainDeadProxyFor(CatalogService.class);
- final Catalog catalog = BrainDeadProxyFactory.createBrainDeadProxyFor(Catalog.class);
-
- ((ZombieControl) catalogService).addResult("getFullCatalog", catalog);
+ final Catalog catalog = Mockito.mock(Catalog.class);
+ final CatalogService catalogService = Mockito.mock(CatalogService.class);
+ Mockito.when(catalogService.getCurrentCatalog()).thenReturn(new MockCatalog());
+ Mockito.when(catalogService.getFullCatalog()).thenReturn(catalog);
bind(CatalogService.class).toInstance(catalogService);
}
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCase.java b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCase.java
index 5ae3793..50c1186 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCase.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCase.java
@@ -23,6 +23,7 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.ErrorCode;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.DefaultPriceList;
import com.ning.billing.catalog.DefaultProduct;
import com.ning.billing.catalog.MockCatalog;
@@ -33,13 +34,8 @@ import com.ning.billing.catalog.api.PlanSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
import com.ning.billing.catalog.api.ProductCategory;
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNull;
-
-public class TestCase {
-
+public class TestCase extends CatalogTestSuite {
protected class CaseResult extends Case<Result> {
-
@XmlElement(required = true)
private final Result policy;
@@ -107,14 +103,13 @@ public class TestCase {
}
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testBasic() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -129,14 +124,13 @@ public class TestCase {
assertionException(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, "dipsy", cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardProduct() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr = new CaseResult(
null,
ProductCategory.BASE,
@@ -152,14 +146,13 @@ public class TestCase {
assertionException(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, "dipsy", cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardProductCategory() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr = new CaseResult(
product,
null,
@@ -175,14 +168,13 @@ public class TestCase {
assertionException(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, "dipsy", cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardBillingPeriod() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -198,14 +190,13 @@ public class TestCase {
assertionException(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, "dipsy", cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardPriceList() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -228,7 +219,6 @@ public class TestCase {
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
-
final CaseResult cr0 = new CaseResult(
product,
ProductCategory.BASE,
@@ -258,17 +248,16 @@ public class TestCase {
Result.LALA);
final Result r1 = Case.getResult(new CaseResult[]{cr0, cr1, cr2, cr3},
- new PlanSpecifier(product.getName(), product.getCategory(), BillingPeriod.MONTHLY, priceList.getName()), cat);
- assertEquals(Result.FOO, r1);
+ new PlanSpecifier(product.getName(), product.getCategory(), BillingPeriod.MONTHLY, priceList.getName()), cat);
+ Assert.assertEquals(r1, Result.FOO);
final Result r2 = Case.getResult(new CaseResult[]{cr0, cr1, cr2},
- new PlanSpecifier(product.getName(), product.getCategory(), BillingPeriod.ANNUAL, priceList.getName()), cat);
- assertEquals(Result.DIPSY, r2);
+ new PlanSpecifier(product.getName(), product.getCategory(), BillingPeriod.ANNUAL, priceList.getName()), cat);
+ Assert.assertEquals(r2, Result.DIPSY);
}
-
protected void assertionNull(final CaseResult cr, final String productName, final ProductCategory productCategory, final BillingPeriod bp, final String priceListName, final StandaloneCatalog cat) throws CatalogApiException {
- assertNull(cr.getResult(new PlanSpecifier(productName, productCategory, bp, priceListName), cat));
+ Assert.assertNull(cr.getResult(new PlanSpecifier(productName, productCategory, bp, priceListName), cat));
}
protected void assertionException(final CaseResult cr, final String productName, final ProductCategory productCategory, final BillingPeriod bp, final String priceListName, final StandaloneCatalog cat) {
@@ -281,8 +270,6 @@ public class TestCase {
}
protected void assertion(final Result result, final CaseResult cr, final String productName, final ProductCategory productCategory, final BillingPeriod bp, final String priceListName, final StandaloneCatalog cat) throws CatalogApiException {
- assertEquals(result, cr.getResult(new PlanSpecifier(productName, productCategory, bp, priceListName), cat));
+ Assert.assertEquals(result, cr.getResult(new PlanSpecifier(productName, productCategory, bp, priceListName), cat));
}
-
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCaseChange.java b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCaseChange.java
index a52b02c..e29d713 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCaseChange.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCaseChange.java
@@ -22,6 +22,7 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.ErrorCode;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.DefaultPriceList;
import com.ning.billing.catalog.DefaultProduct;
import com.ning.billing.catalog.MockCatalog;
@@ -34,12 +35,8 @@ import com.ning.billing.catalog.api.PlanSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
import com.ning.billing.catalog.api.ProductCategory;
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNull;
-
-public class TestCaseChange {
+public class TestCaseChange extends CatalogTestSuite {
protected static class CaseChangeResult extends CaseChange<Result> {
-
@XmlElement(required = true)
private final Result result;
@@ -68,7 +65,7 @@ public class TestCaseChange {
}
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testBasic() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -78,7 +75,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -158,7 +154,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardFromProduct() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -168,7 +164,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
null, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -241,7 +236,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardToProduct() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -251,7 +246,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, null,
ProductCategory.BASE, ProductCategory.BASE,
@@ -331,7 +325,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardFromProductCategory() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -341,7 +335,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
null, ProductCategory.BASE,
@@ -421,7 +414,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardToProductCategory() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -431,7 +424,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, null,
@@ -511,7 +503,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardFromBillingPeriod() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -521,7 +513,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -601,8 +592,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
-
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardToBillingPeriod() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -612,7 +602,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -692,7 +681,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardFromPriceList() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -702,7 +691,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -782,7 +770,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardToPriceList() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -792,7 +780,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -872,7 +859,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildcardPlanPhase() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -882,7 +869,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -962,8 +948,7 @@ public class TestCaseChange {
PhaseType.TRIAL, cat);
}
-
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testOrder() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
@@ -973,7 +958,6 @@ public class TestCaseChange {
final DefaultProduct product2 = cat.getCurrentProducts()[2];
final DefaultPriceList priceList2 = cat.getPriceLists().getChildPriceLists()[1];
-
final CaseChangeResult cr0 = new CaseChangeResult(
product1, product2,
ProductCategory.BASE, ProductCategory.BASE,
@@ -1015,20 +999,18 @@ public class TestCaseChange {
Result.LALA);
final Result r1 = CaseChange.getResult(new CaseChangeResult[]{cr0, cr1, cr2, cr3, cr4},
- new PlanPhaseSpecifier(product1.getName(), product1.getCategory(), BillingPeriod.MONTHLY, priceList1.getName(), PhaseType.EVERGREEN),
- new PlanSpecifier(product2.getName(), product2.getCategory(), BillingPeriod.MONTHLY, priceList2.getName()), cat);
+ new PlanPhaseSpecifier(product1.getName(), product1.getCategory(), BillingPeriod.MONTHLY, priceList1.getName(), PhaseType.EVERGREEN),
+ new PlanSpecifier(product2.getName(), product2.getCategory(), BillingPeriod.MONTHLY, priceList2.getName()), cat);
- assertEquals(Result.FOO, r1);
+ Assert.assertEquals(r1, Result.FOO);
final Result r2 = CaseChange.getResult(new CaseChangeResult[]{cr0, cr1, cr2, cr3, cr4},
- new PlanPhaseSpecifier(product1.getName(), product1.getCategory(), BillingPeriod.MONTHLY, priceList1.getName(), PhaseType.EVERGREEN),
- new PlanSpecifier(product2.getName(), product2.getCategory(), BillingPeriod.ANNUAL, priceList2.getName()), cat);
-
- assertEquals(Result.DIPSY, r2);
+ new PlanPhaseSpecifier(product1.getName(), product1.getCategory(), BillingPeriod.MONTHLY, priceList1.getName(), PhaseType.EVERGREEN),
+ new PlanSpecifier(product2.getName(), product2.getCategory(), BillingPeriod.ANNUAL, priceList2.getName()), cat);
+ Assert.assertEquals(r2, Result.DIPSY);
}
-
protected void assertionNull(final CaseChangeResult cr,
final String fromProductName, final String toProductName,
final ProductCategory fromProductCategory, final ProductCategory toProductCategory,
@@ -1036,8 +1018,8 @@ public class TestCaseChange {
final String fromPriceListName, final String toPriceListName,
final PhaseType phaseType, final StandaloneCatalog cat) {
try {
- assertNull(cr.getResult(new PlanPhaseSpecifier(fromProductName, fromProductCategory, fromBp, fromPriceListName, phaseType),
- new PlanSpecifier(toProductName, toProductCategory, toBp, toPriceListName), cat));
+ Assert.assertNull(cr.getResult(new PlanPhaseSpecifier(fromProductName, fromProductCategory, fromBp, fromPriceListName, phaseType),
+ new PlanSpecifier(toProductName, toProductCategory, toBp, toPriceListName), cat));
} catch (CatalogApiException e) {
Assert.fail("", e);
}
@@ -1065,11 +1047,10 @@ public class TestCaseChange {
final String fromPriceListName, final String toPriceListName,
final PhaseType phaseType, final StandaloneCatalog cat) {
try {
- assertEquals(result, cr.getResult(new PlanPhaseSpecifier(fromProductName, fromProductCategory, fromBp, fromPriceListName, phaseType),
- new PlanSpecifier(toProductName, toProductCategory, toBp, toPriceListName), cat));
+ Assert.assertEquals(result, cr.getResult(new PlanPhaseSpecifier(fromProductName, fromProductCategory, fromBp, fromPriceListName, phaseType),
+ new PlanSpecifier(toProductName, toProductCategory, toBp, toPriceListName), cat));
} catch (CatalogApiException e) {
Assert.fail("", e);
}
}
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCasePhase.java b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCasePhase.java
index 26dfc5c..e7ae6a8 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/rules/TestCasePhase.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/rules/TestCasePhase.java
@@ -22,6 +22,7 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.ErrorCode;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.DefaultPriceList;
import com.ning.billing.catalog.DefaultProduct;
import com.ning.billing.catalog.MockCatalog;
@@ -32,9 +33,8 @@ import com.ning.billing.catalog.api.PhaseType;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.ProductCategory;
-public class TestCasePhase {
+public class TestCasePhase extends CatalogTestSuite {
protected class CaseResult extends CasePhase<Result> {
-
@XmlElement(required = true)
private final Result policy;
@@ -55,14 +55,13 @@ public class TestCasePhase {
}
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testBasic() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -79,14 +78,13 @@ public class TestCasePhase {
assertionNull(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardProduct() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
null,
ProductCategory.BASE,
@@ -103,14 +101,13 @@ public class TestCasePhase {
assertionNull(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardProductCategory() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
product,
null,
@@ -127,14 +124,13 @@ public class TestCasePhase {
assertionNull(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardBillingPeriod() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -151,14 +147,13 @@ public class TestCasePhase {
assertionNull(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardPriceList() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -175,14 +170,13 @@ public class TestCasePhase {
assertionNull(cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testWildCardPhaseType() {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr = new CaseResult(
product,
ProductCategory.BASE,
@@ -199,14 +193,13 @@ public class TestCasePhase {
assertion(Result.FOO, cr, product.getName(), ProductCategory.BASE, BillingPeriod.MONTHLY, priceList.getName(), PhaseType.TRIAL, cat);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testOrder() throws CatalogApiException {
final MockCatalog cat = new MockCatalog();
final DefaultProduct product = cat.getCurrentProducts()[0];
final DefaultPriceList priceList = cat.getPriceLists().getDefaultPricelist();
-
final CaseResult cr0 = new CaseResult(
product,
ProductCategory.BASE,
@@ -248,18 +241,17 @@ public class TestCasePhase {
Result.LALA);
final Result r1 = CasePhase.getResult(new CaseResult[]{cr0, cr1, cr2, cr3, cr4},
- new PlanPhaseSpecifier(product.getName(), product.getCategory(), BillingPeriod.MONTHLY, priceList.getName(), PhaseType.EVERGREEN), cat);
+ new PlanPhaseSpecifier(product.getName(), product.getCategory(), BillingPeriod.MONTHLY, priceList.getName(), PhaseType.EVERGREEN), cat);
Assert.assertEquals(Result.FOO, r1);
final Result r2 = CasePhase.getResult(new CaseResult[]{cr0, cr1, cr2, cr3, cr4},
- new PlanPhaseSpecifier(product.getName(), product.getCategory(), BillingPeriod.ANNUAL, priceList.getName(), PhaseType.EVERGREEN), cat);
+ new PlanPhaseSpecifier(product.getName(), product.getCategory(), BillingPeriod.ANNUAL, priceList.getName(), PhaseType.EVERGREEN), cat);
Assert.assertEquals(Result.DIPSY, r2);
}
-
protected void assertionNull(final CaseResult cr, final String productName, final ProductCategory productCategory, final BillingPeriod bp, final String priceListName, final PhaseType phaseType, final StandaloneCatalog cat) {
try {
Assert.assertNull(cr.getResult(new PlanPhaseSpecifier(productName, productCategory, bp, priceListName, phaseType), cat));
@@ -268,7 +260,6 @@ public class TestCasePhase {
}
}
-
protected void assertionException(final CaseResult cr, final String productName, final ProductCategory productCategory, final BillingPeriod bp, final String priceListName, final PhaseType phaseType, final StandaloneCatalog cat) {
try {
Assert.assertNull(cr.getResult(new PlanPhaseSpecifier(productName, productCategory, bp, priceListName, phaseType), cat));
@@ -285,6 +276,4 @@ public class TestCasePhase {
Assert.fail("", e);
}
}
-
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/rules/TestLoadRules.java b/catalog/src/test/java/com/ning/billing/catalog/rules/TestLoadRules.java
index 0e8b04e..27cf7d1 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/rules/TestLoadRules.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/rules/TestLoadRules.java
@@ -16,11 +16,13 @@
package com.ning.billing.catalog.rules;
-import java.io.File;
+import java.net.URI;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.google.common.io.Resources;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.StandaloneCatalog;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.PlanAlignmentCreate;
@@ -28,22 +30,22 @@ import com.ning.billing.catalog.api.PlanSpecifier;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.util.config.XMLLoader;
-public class TestLoadRules {
-
- @Test
+public class TestLoadRules extends CatalogTestSuite {
+ @Test(groups = "fast")
public void test() throws Exception {
- final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(new File("src/test/resources/WeaponsHireSmall.xml").toURI(), StandaloneCatalog.class);
+ final URI uri = new URI(Resources.getResource("WeaponsHireSmall.xml").toExternalForm());
+ final StandaloneCatalog catalog = XMLLoader.getObjectFromUri(uri, StandaloneCatalog.class);
Assert.assertNotNull(catalog);
final PlanRules rules = catalog.getPlanRules();
final PlanSpecifier specifier = new PlanSpecifier("Laser-Scope", ProductCategory.ADD_ON, BillingPeriod.MONTHLY,
- "DEFAULT");
+ "DEFAULT");
final PlanAlignmentCreate alignment = rules.getPlanCreateAlignment(specifier, catalog);
Assert.assertEquals(alignment, PlanAlignmentCreate.START_OF_SUBSCRIPTION);
final PlanSpecifier specifier2 = new PlanSpecifier("Extra-Ammo", ProductCategory.ADD_ON, BillingPeriod.MONTHLY,
- "DEFAULT");
+ "DEFAULT");
final PlanAlignmentCreate alignment2 = rules.getPlanCreateAlignment(specifier2, catalog);
Assert.assertEquals(alignment2, PlanAlignmentCreate.START_OF_BUNDLE);
diff --git a/catalog/src/test/java/com/ning/billing/catalog/rules/TestPlanRules.java b/catalog/src/test/java/com/ning/billing/catalog/rules/TestPlanRules.java
index bc876d3..2795dc1 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/rules/TestPlanRules.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/rules/TestPlanRules.java
@@ -22,6 +22,7 @@ import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
+import com.ning.billing.catalog.CatalogTestSuite;
import com.ning.billing.catalog.DefaultPriceList;
import com.ning.billing.catalog.DefaultProduct;
import com.ning.billing.catalog.MockCatalog;
@@ -36,12 +37,11 @@ import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.PlanSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
-public class TestPlanRules {
- Logger log = LoggerFactory.getLogger(TestPlanRules.class);
-
+public class TestPlanRules extends CatalogTestSuite {
+ private final Logger log = LoggerFactory.getLogger(TestPlanRules.class);
private MockCatalog cat = null;
- @BeforeTest
+ @BeforeTest(groups = "fast")
public void setup() {
cat = new MockCatalog();
@@ -57,7 +57,7 @@ public class TestPlanRules {
setPriceListCase(new CasePriceList[]{casePriceList});
}
- @Test
+ @Test(groups = "fast")
public void testCannotChangeToSamePlan() throws CatalogApiException {
final DefaultProduct product1 = cat.getCurrentProducts()[0];
final DefaultPriceList priceList1 = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
@@ -73,10 +73,9 @@ public class TestPlanRules {
} catch (CatalogApiException e) {
Assert.fail("", e);
}
-
}
- @Test
+ @Test(groups = "fast")
public void testExistingPriceListIsKept() throws CatalogApiException {
final DefaultProduct product1 = cat.getCurrentProducts()[0];
final DefaultPriceList priceList1 = cat.findCurrentPriceList(PriceListSet.DEFAULT_PRICELIST_NAME);
@@ -97,11 +96,9 @@ public class TestPlanRules {
Assert.assertEquals(result.getPolicy(), ActionPolicy.END_OF_TERM);
Assert.assertEquals(result.getAlignment(), PlanAlignmentChange.START_OF_SUBSCRIPTION);
Assert.assertEquals(result.getNewPriceList(), priceList1);
-
}
-
- @Test
+ @Test(groups = "fast")
public void testBaseCase() throws CatalogApiException {
final DefaultProduct product1 = cat.getCurrentProducts()[0];
final DefaultProduct product2 = cat.getCurrentProducts()[1];
@@ -124,8 +121,5 @@ public class TestPlanRules {
Assert.assertEquals(result.getPolicy(), ActionPolicy.END_OF_TERM);
Assert.assertEquals(result.getAlignment(), PlanAlignmentChange.START_OF_SUBSCRIPTION);
Assert.assertEquals(result.getNewPriceList(), priceList2);
-
}
-
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestCatalogService.java b/catalog/src/test/java/com/ning/billing/catalog/TestCatalogService.java
index 38c21e2..3fa6949 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestCatalogService.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestCatalogService.java
@@ -24,9 +24,8 @@ import com.ning.billing.config.CatalogConfig;
import com.ning.billing.lifecycle.KillbillService.ServiceException;
import com.ning.billing.util.clock.DefaultClock;
-public class TestCatalogService {
-
- @Test
+public class TestCatalogService extends CatalogTestSuite {
+ @Test(groups = "fast")
public void testCatalogServiceDirectory() throws ServiceException {
final DefaultCatalogService service = new DefaultCatalogService(new CatalogConfig() {
@Override
@@ -40,7 +39,7 @@ public class TestCatalogService {
Assert.assertEquals(service.getFullCatalog().getCatalogName(), "WeaponsHireSmall");
}
- @Test
+ @Test(groups = "fast")
public void testCatalogServiceFile() throws ServiceException {
final DefaultCatalogService service = new DefaultCatalogService(new CatalogConfig() {
@Override
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestInternationalPrice.java b/catalog/src/test/java/com/ning/billing/catalog/TestInternationalPrice.java
index 62fbe6c..f543071 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestInternationalPrice.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestInternationalPrice.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.catalog;
import java.math.BigDecimal;
@@ -28,10 +29,10 @@ import com.ning.billing.catalog.api.CatalogApiException;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.util.config.ValidationErrors;
-public class TestInternationalPrice {
+public class TestInternationalPrice extends CatalogTestSuite {
private static final Logger log = LoggerFactory.getLogger(TestInternationalPrice.class);
- @Test
+ @Test(groups = "fast")
public void testZeroValue() throws URISyntaxException, CatalogApiException {
final StandaloneCatalog c = new MockCatalog();
c.setSupportedCurrencies(new Currency[]{Currency.GBP, Currency.EUR, Currency.USD, Currency.BRL, Currency.MXN});
@@ -59,10 +60,9 @@ public class TestInternationalPrice {
Assert.assertEquals(p1.getPrice(Currency.USD), new BigDecimal(1));
Assert.assertEquals(p1.getPrice(Currency.BRL), new BigDecimal(1));
Assert.assertEquals(p1.getPrice(Currency.MXN), new BigDecimal(1));
-
}
- @Test
+ @Test(groups = "fast")
public void testPriceInitialization() throws URISyntaxException, CatalogApiException {
final StandaloneCatalog c = new MockCatalog();
c.setSupportedCurrencies(new Currency[]{Currency.GBP, Currency.EUR, Currency.USD, Currency.BRL, Currency.MXN});
@@ -71,7 +71,7 @@ public class TestInternationalPrice {
Assert.assertEquals(c.getCurrentPlans()[0].getFinalPhase().getRecurringPrice().getPrice(Currency.GBP), new BigDecimal(0));
}
- @Test
+ @Test(groups = "fast")
public void testNegativeValuePrices() {
final StandaloneCatalog c = new MockCatalog();
c.setSupportedCurrencies(new Currency[]{Currency.GBP, Currency.EUR, Currency.USD, Currency.BRL, Currency.MXN});
@@ -89,6 +89,4 @@ public class TestInternationalPrice {
errors.log(log);
Assert.assertEquals(errors.size(), 3);
}
-
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestPlan.java b/catalog/src/test/java/com/ning/billing/catalog/TestPlan.java
index 2aad0a6..cf2987e 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestPlan.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestPlan.java
@@ -27,12 +27,11 @@ import org.testng.annotations.Test;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.util.config.ValidationErrors;
-public class TestPlan {
+public class TestPlan extends CatalogTestSuite {
private static final Logger log = LoggerFactory.getLogger(TestPlan.class);
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testDateValidation() {
-
final StandaloneCatalog c = new MockCatalog();
c.setSupportedCurrencies(new Currency[]{Currency.GBP, Currency.EUR, Currency.USD, Currency.BRL, Currency.MXN});
final DefaultPlan p1 = MockPlan.createBicycleTrialEvergreen1USD();
@@ -40,10 +39,9 @@ public class TestPlan {
final ValidationErrors errors = p1.validate(c, new ValidationErrors());
Assert.assertEquals(errors.size(), 1);
errors.log(log);
-
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testDataCalc() {
final DefaultPlan p0 = MockPlan.createBicycleTrialEvergreen1USD();
@@ -55,6 +53,5 @@ public class TestPlan {
Assert.assertEquals(p0.dateOfFirstRecurringNonZeroCharge(requestedDate).compareTo(requestedDate.plusDays(30)), 0);
Assert.assertEquals(p1.dateOfFirstRecurringNonZeroCharge(requestedDate).compareTo(requestedDate.plusDays(100)), 0);
Assert.assertEquals(p2.dateOfFirstRecurringNonZeroCharge(requestedDate).compareTo(requestedDate.plusDays(0)), 0);
-
}
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestPlanPhase.java b/catalog/src/test/java/com/ning/billing/catalog/TestPlanPhase.java
index ee3f11e..600a620 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestPlanPhase.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestPlanPhase.java
@@ -26,10 +26,10 @@ import com.ning.billing.catalog.api.CatalogApiException;
import com.ning.billing.catalog.api.PhaseType;
import com.ning.billing.util.config.ValidationErrors;
-public class TestPlanPhase {
- Logger log = LoggerFactory.getLogger(TestPlanPhase.class);
+public class TestPlanPhase extends CatalogTestSuite {
+ private final Logger log = LoggerFactory.getLogger(TestPlanPhase.class);
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testValidation() {
log.info("Testing Plan Phase Validation");
@@ -42,15 +42,15 @@ public class TestPlanPhase {
pp = MockPlanPhase.createUSDMonthlyEvergreen("1.00", null).setBillCycleDuration(BillingPeriod.NO_BILLING_PERIOD).setPlan(MockPlan.createBicycleNoTrialEvergreen1USD());// new MockPlanPhase().setBillCycleDuration(BillingPeriod.NO_BILLING_PERIOD).setRecurringPrice(new MockInternationalPrice());
errors = pp.validate(new MockCatalog(), new ValidationErrors());
errors.log(log);
- Assert.assertEquals(errors.size(), 1);
+ Assert.assertEquals(errors.size(), 2);
pp = MockPlanPhase.createUSDMonthlyEvergreen(null, null).setBillCycleDuration(BillingPeriod.NO_BILLING_PERIOD).setPlan(MockPlan.createBicycleNoTrialEvergreen1USD());//new MockPlanPhase().setRecurringPrice(null).setFixedPrice(null).setBillCycleDuration(BillingPeriod.NO_BILLING_PERIOD);
errors = pp.validate(new MockCatalog(), new ValidationErrors());
errors.log(log);
- Assert.assertEquals(errors.size(), 1);
+ Assert.assertEquals(errors.size(), 2);
}
- @Test
+ @Test(groups = "fast")
public void testPhaseNames() throws CatalogApiException {
final String planName = "Foo";
final String planNameExt = planName + "-";
@@ -71,12 +71,9 @@ public class TestPlanPhase {
Assert.assertEquals(ppnFixedTerm, planNameExt + "fixedterm");
Assert.assertEquals(ppnDiscount, planNameExt + "discount");
-
Assert.assertEquals(DefaultPlanPhase.planName(ppnDiscount), planName);
Assert.assertEquals(DefaultPlanPhase.planName(ppnTrial), planName);
Assert.assertEquals(DefaultPlanPhase.planName(ppnEvergreen), planName);
Assert.assertEquals(DefaultPlanPhase.planName(ppnFixedTerm), planName);
-
-
}
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestPriceListSet.java b/catalog/src/test/java/com/ning/billing/catalog/TestPriceListSet.java
index 107283d..2f54295 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestPriceListSet.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestPriceListSet.java
@@ -30,8 +30,8 @@ import static com.ning.billing.catalog.api.BillingPeriod.MONTHLY;
import static com.ning.billing.catalog.api.PhaseType.DISCOUNT;
import static com.ning.billing.catalog.api.PhaseType.EVERGREEN;
-public class TestPriceListSet {
- @Test(enabled = true)
+public class TestPriceListSet extends CatalogTestSuite {
+ @Test(groups = "fast")
public void testOverriding() throws CatalogApiException {
final DefaultProduct foo = new DefaultProduct("Foo", ProductCategory.BASE);
final DefaultProduct bar = new DefaultProduct("Bar", ProductCategory.BASE);
@@ -57,6 +57,7 @@ public class TestPriceListSet {
Assert.assertEquals(set.getPlanFrom("child", foo, BillingPeriod.MONTHLY).getFinalPhase().getPhaseType(), PhaseType.EVERGREEN);
}
+ @Test(groups = "fast")
public void testForNullBillingPeriod() throws CatalogApiException {
final DefaultProduct foo = new DefaultProduct("Foo", ProductCategory.BASE);
final DefaultProduct bar = new DefaultProduct("Bar", ProductCategory.BASE);
@@ -82,5 +83,4 @@ public class TestPriceListSet {
Assert.assertEquals(set.getPlanFrom(PriceListSet.DEFAULT_PRICELIST_NAME, foo, BillingPeriod.ANNUAL).getFinalPhase().getPhaseType(), PhaseType.EVERGREEN);
Assert.assertEquals(set.getPlanFrom(PriceListSet.DEFAULT_PRICELIST_NAME, foo, BillingPeriod.MONTHLY).getFinalPhase().getPhaseType(), PhaseType.EVERGREEN);
}
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestStandaloneCatalog.java b/catalog/src/test/java/com/ning/billing/catalog/TestStandaloneCatalog.java
index edca7f1..3f5cca3 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestStandaloneCatalog.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestStandaloneCatalog.java
@@ -22,9 +22,8 @@ import org.testng.annotations.Test;
import com.ning.billing.catalog.api.CatalogApiException;
import com.ning.billing.catalog.api.PhaseType;
-public class TestStandaloneCatalog {
-
- @Test
+public class TestStandaloneCatalog extends CatalogTestSuite {
+ @Test(groups = "fast")
public void testFindPhase() throws CatalogApiException {
final DefaultPlanPhase phaseTrial1 = new MockPlanPhase().setPhaseType(PhaseType.TRIAL);
final DefaultPlanPhase phaseTrial2 = new MockPlanPhase().setPhaseType(PhaseType.TRIAL);
@@ -44,9 +43,5 @@ public class TestStandaloneCatalog {
Assert.assertEquals(cat.findCurrentPhase("TestPlan2-discount"), phaseDiscount2);
Assert.assertEquals(cat.findCurrentPhase("TestPlan1-trial"), phaseTrial1);
Assert.assertEquals(cat.findCurrentPhase("TestPlan2-trial"), phaseTrial2);
-
-
}
-
-
}
diff --git a/catalog/src/test/java/com/ning/billing/catalog/TestVersionedCatalog.java b/catalog/src/test/java/com/ning/billing/catalog/TestVersionedCatalog.java
index a972fd5..2f0f873 100644
--- a/catalog/src/test/java/com/ning/billing/catalog/TestVersionedCatalog.java
+++ b/catalog/src/test/java/com/ning/billing/catalog/TestVersionedCatalog.java
@@ -13,13 +13,13 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.catalog;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.math.BigDecimal;
-import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Date;
@@ -41,26 +41,23 @@ import com.ning.billing.catalog.io.VersionedCatalogLoader;
import com.ning.billing.lifecycle.KillbillService.ServiceException;
import com.ning.billing.util.clock.DefaultClock;
-import static org.testng.AssertJUnit.assertEquals;
-
-public class TestVersionedCatalog {
+public class TestVersionedCatalog extends CatalogTestSuite {
private static final Logger log = LoggerFactory.getLogger(TestVersionedCatalog.class);
private final VersionedCatalogLoader loader = new VersionedCatalogLoader(new DefaultClock());
private VersionedCatalog vc;
- @BeforeClass(groups = {"fast"})
+ @BeforeClass(groups = "fast")
public void setUp() throws ServiceException {
vc = loader.load(Resources.getResource("versionedCatalog").toString());
}
- @Test(groups = {"fast"}, enabled = true)
- public void testAddCatalog() throws MalformedURLException, IOException, SAXException, InvalidConfigException, JAXBException, TransformerException, URISyntaxException, ServiceException, CatalogApiException {
+ @Test(groups = "fast")
+ public void testAddCatalog() throws IOException, SAXException, InvalidConfigException, JAXBException, TransformerException, URISyntaxException, ServiceException, CatalogApiException {
vc.add(new StandaloneCatalog(new Date()));
- assertEquals(4, vc.size());
+ Assert.assertEquals(vc.size(), 4);
}
-
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testFindPlanWithDates() throws Exception {
final DateTime dt0 = new DateTime("2010-01-01T00:00:00+00:00");
final DateTime dt1 = new DateTime("2011-01-01T00:01:00+00:00");
@@ -99,7 +96,7 @@ public class TestVersionedCatalog {
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testErrorOnDateTooEarly() {
final DateTime dt0 = new DateTime("1977-01-01T00:00:00+00:00");
try {
entitlement/pom.xml 7(+6 -1)
diff --git a/entitlement/pom.xml b/entitlement/pom.xml
index 9c5d3d2..fea6680 100644
--- a/entitlement/pom.xml
+++ b/entitlement/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-entitlement</artifactId>
@@ -87,6 +87,11 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/PlanAligner.java b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/PlanAligner.java
index d31452d..3593fea 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/PlanAligner.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/PlanAligner.java
@@ -16,6 +16,7 @@
package com.ning.billing.entitlement.alignment;
+import javax.annotation.Nullable;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@@ -43,11 +44,10 @@ import com.ning.billing.entitlement.exceptions.EntitlementError;
import com.ning.billing.util.clock.DefaultClock;
/**
- * PlanAligner offers specific APIs to return the correct {@code TimedPhase} when creating, changing Plan or to compute next Phase on current Plan.
- * <p/>
+ * PlanAligner offers specific APIs to return the correct {@code TimedPhase} when creating, changing Plan or to compute
+ * next Phase on current Plan.
*/
public class PlanAligner {
-
private final CatalogService catalogService;
@Inject
@@ -62,22 +62,29 @@ public class PlanAligner {
/**
* Returns the current and next phase for the subscription in creation
- * <p/>
*
- * @param subscription the subscription in creation
+ * @param subscription the subscription in creation (only the start date and the bundle start date are looked at)
* @param plan the current Plan
* @param initialPhase the initialPhase on which we should create that subscription. can be null
* @param priceList the priceList
- * @param effectiveDate the effective creation date
- * @return
- * @throws CatalogApiException
- * @throws EntitlementUserApiException
+ * @param requestedDate the requested date (only used to load the catalog)
+ * @param effectiveDate the effective creation date (driven by the catalog policy, i.e. when the creation occurs)
+ * @return the current and next phases
+ * @throws CatalogApiException for catalog errors
+ * @throws EntitlementUserApiException for entitlement errors
*/
public TimedPhase[] getCurrentAndNextTimedPhaseOnCreate(final SubscriptionData subscription,
- final Plan plan, final PhaseType initialPhase, final String priceList, final DateTime requestedDate, final DateTime effectiveDate)
- throws CatalogApiException, EntitlementUserApiException {
+ final Plan plan,
+ final PhaseType initialPhase,
+ final String priceList,
+ final DateTime requestedDate,
+ final DateTime effectiveDate) throws CatalogApiException, EntitlementUserApiException {
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(subscription.getStartDate(),
- subscription.getBundleStartDate(), plan, initialPhase, priceList, requestedDate);
+ subscription.getBundleStartDate(),
+ plan,
+ initialPhase,
+ priceList,
+ requestedDate);
final TimedPhase[] result = new TimedPhase[2];
result[0] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.CURRENT);
result[1] = getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
@@ -86,52 +93,56 @@ public class PlanAligner {
/**
* Returns current Phase for that Plan change
- * <p/>
*
- * @param subscription the subscription in creation
+ * @param subscription the subscription in change (only start date, bundle start date, current phase, plan and pricelist
+ * are looked at)
* @param plan the current Plan
* @param priceList the priceList on which we should change that subscription.
- * @param effectiveDate the effective change date
- * @return
- * @throws CatalogApiException
- * @throws EntitlementUserApiException
+ * @param requestedDate the requested date
+ * @param effectiveDate the effective change date (driven by the catalog policy, i.e. when the change occurs)
+ * @return the current phase
+ * @throws CatalogApiException for catalog errors
+ * @throws EntitlementUserApiException for entitlement errors
*/
public TimedPhase getCurrentTimedPhaseOnChange(final SubscriptionData subscription,
- final Plan plan, final String priceList, final DateTime requestedDate, final DateTime effectiveDate)
- throws CatalogApiException, EntitlementUserApiException {
+ final Plan plan,
+ final String priceList,
+ final DateTime requestedDate,
+ final DateTime effectiveDate) throws CatalogApiException, EntitlementUserApiException {
return getTimedPhaseOnChange(subscription, plan, priceList, requestedDate, effectiveDate, WhichPhase.CURRENT);
}
/**
* Returns next Phase for that Plan change
- * <p/>
*
- * @param subscription the subscription in creation
+ * @param subscription the subscription in change (only start date, bundle start date, current phase, plan and pricelist
+ * are looked at)
* @param plan the current Plan
* @param priceList the priceList on which we should change that subscription.
- * @param effectiveDate the effective change date
- * @return
- * @throws CatalogApiException
- * @throws EntitlementUserApiException
+ * @param requestedDate the requested date
+ * @param effectiveDate the effective change date (driven by the catalog policy, i.e. when the change occurs)
+ * @return the next phase
+ * @throws CatalogApiException for catalog errors
+ * @throws EntitlementUserApiException for entitlement errors
*/
public TimedPhase getNextTimedPhaseOnChange(final SubscriptionData subscription,
- final Plan plan, final String priceList, final DateTime requestedDate, final DateTime effectiveDate)
- throws CatalogApiException, EntitlementUserApiException {
+ final Plan plan,
+ final String priceList,
+ final DateTime requestedDate,
+ final DateTime effectiveDate) throws CatalogApiException, EntitlementUserApiException {
return getTimedPhaseOnChange(subscription, plan, priceList, requestedDate, effectiveDate, WhichPhase.NEXT);
}
-
/**
* Returns next Phase for that Subscription at a point in time
- * <p/>
*
* @param subscription the subscription for which we need to compute the next Phase event
+ * @param requestedDate the requested date
* @param effectiveDate the date at which we look to compute that event. effective needs to be after last Plan change or initial Plan
- * @return The PhaseEvent at the correct point in time
+ * @return the next phase
*/
public TimedPhase getNextTimedPhase(final SubscriptionData subscription, final DateTime requestedDate, final DateTime effectiveDate) {
try {
-
final SubscriptionTransitionData lastPlanTransition = subscription.getInitialTransitionForCurrentPlan();
if (effectiveDate.isBefore(lastPlanTransition.getEffectiveTransitionTime())) {
throw new EntitlementError(String.format("Cannot specify an effectiveDate prior to last Plan Change, subscription = %s, effectiveDate = %s",
@@ -139,18 +150,18 @@ public class PlanAligner {
}
switch (lastPlanTransition.getTransitionType()) {
- // If we never had any Plan change, borrow the logics for createPlan alignment
+ // If we never had any Plan change, borrow the logic for createPlan alignment
case MIGRATE_ENTITLEMENT:
case CREATE:
case RE_CREATE:
final List<TimedPhase> timedPhases = getTimedPhaseOnCreate(subscription.getStartDate(),
- subscription.getBundleStartDate(),
- lastPlanTransition.getNextPlan(),
- lastPlanTransition.getNextPhase().getPhaseType(),
- lastPlanTransition.getNextPriceList().getName(),
- requestedDate);
+ subscription.getBundleStartDate(),
+ lastPlanTransition.getNextPlan(),
+ lastPlanTransition.getNextPhase().getPhaseType(),
+ lastPlanTransition.getNextPriceList().getName(),
+ requestedDate);
return getTimedPhase(timedPhases, effectiveDate, WhichPhase.NEXT);
- // If we went through Plan changes, borrow the logics for changePlan alignement
+ // If we went through Plan changes, borrow the logic for changePlan alignment
case CHANGE:
return getTimedPhaseOnChange(subscription.getStartDate(),
subscription.getBundleStartDate(),
@@ -163,7 +174,7 @@ public class PlanAligner {
effectiveDate,
WhichPhase.NEXT);
default:
- throw new EntitlementError(String.format("Unexpectd initial transition %s for current plan %s on subscription %s",
+ throw new EntitlementError(String.format("Unexpected initial transition %s for current plan %s on subscription %s",
lastPlanTransition.getTransitionType(), subscription.getCurrentPlan(), subscription.getId()));
}
} catch (Exception /* EntitlementUserApiException, CatalogApiException */ e) {
@@ -171,22 +182,23 @@ public class PlanAligner {
}
}
-
private List<TimedPhase> getTimedPhaseOnCreate(final DateTime subscriptionStartDate,
final DateTime bundleStartDate,
- final Plan plan, final PhaseType initialPhase, final String priceList, final DateTime requestedDate)
+ final Plan plan,
+ final PhaseType initialPhase,
+ final String priceList,
+ final DateTime requestedDate)
throws CatalogApiException, EntitlementUserApiException {
-
final Catalog catalog = catalogService.getFullCatalog();
final PlanSpecifier planSpecifier = new PlanSpecifier(plan.getProduct().getName(),
- plan.getProduct().getCategory(),
- plan.getBillingPeriod(),
- priceList);
+ plan.getProduct().getCategory(),
+ plan.getBillingPeriod(),
+ priceList);
- DateTime planStartDate = null;
- final PlanAlignmentCreate alignement = catalog.planCreateAlignment(planSpecifier, requestedDate);
- switch (alignement) {
+ final DateTime planStartDate;
+ final PlanAlignmentCreate alignment = catalog.planCreateAlignment(planSpecifier, requestedDate);
+ switch (alignment) {
case START_OF_SUBSCRIPTION:
planStartDate = subscriptionStartDate;
break;
@@ -194,14 +206,18 @@ public class PlanAligner {
planStartDate = bundleStartDate;
break;
default:
- throw new EntitlementError(String.format("Unknwon PlanAlignmentCreate %s", alignement));
+ throw new EntitlementError(String.format("Unknown PlanAlignmentCreate %s", alignment));
}
+
return getPhaseAlignments(plan, initialPhase, planStartDate);
}
private TimedPhase getTimedPhaseOnChange(final SubscriptionData subscription,
- final Plan nextPlan, final String nextPriceList, final DateTime requestedDate, final DateTime effectiveDate, final WhichPhase which)
- throws CatalogApiException, EntitlementUserApiException {
+ final Plan nextPlan,
+ final String nextPriceList,
+ final DateTime requestedDate,
+ final DateTime effectiveDate,
+ final WhichPhase which) throws CatalogApiException, EntitlementUserApiException {
return getTimedPhaseOnChange(subscription.getStartDate(),
subscription.getBundleStartDate(),
subscription.getCurrentPhase(),
@@ -214,29 +230,30 @@ public class PlanAligner {
which);
}
-
private TimedPhase getTimedPhaseOnChange(final DateTime subscriptionStartDate,
final DateTime bundleStartDate,
final PlanPhase currentPhase,
final Plan currentPlan,
final String currentPriceList,
- final Plan nextPlan, final String priceList, final DateTime requestedDate, final DateTime effectiveDate, final WhichPhase which)
- throws CatalogApiException, EntitlementUserApiException {
-
+ final Plan nextPlan,
+ final String priceList,
+ final DateTime requestedDate,
+ final DateTime effectiveDate,
+ final WhichPhase which) throws CatalogApiException, EntitlementUserApiException {
final Catalog catalog = catalogService.getFullCatalog();
final ProductCategory currentCategory = currentPlan.getProduct().getCategory();
final PlanPhaseSpecifier fromPlanPhaseSpecifier = new PlanPhaseSpecifier(currentPlan.getProduct().getName(),
- currentCategory,
- currentPlan.getBillingPeriod(),
- currentPriceList,
- currentPhase.getPhaseType());
+ currentCategory,
+ currentPlan.getBillingPeriod(),
+ currentPriceList,
+ currentPhase.getPhaseType());
final PlanSpecifier toPlanSpecifier = new PlanSpecifier(nextPlan.getProduct().getName(),
- nextPlan.getProduct().getCategory(),
- nextPlan.getBillingPeriod(),
- priceList);
+ nextPlan.getProduct().getCategory(),
+ nextPlan.getBillingPeriod(),
+ priceList);
- DateTime planStartDate = null;
+ final DateTime planStartDate;
final PlanAlignmentChange alignment = catalog.planChangeAlignment(fromPlanPhaseSpecifier, toPlanSpecifier, requestedDate);
switch (alignment) {
case START_OF_SUBSCRIPTION:
@@ -251,22 +268,21 @@ public class PlanAligner {
case CHANGE_OF_PRICELIST:
throw new EntitlementError(String.format("Not implemented yet %s", alignment));
default:
- throw new EntitlementError(String.format("Unknwon PlanAlignmentChange %s", alignment));
+ throw new EntitlementError(String.format("Unknown PlanAlignmentChange %s", alignment));
}
+
final List<TimedPhase> timedPhases = getPhaseAlignments(nextPlan, null, planStartDate);
return getTimedPhase(timedPhases, effectiveDate, which);
}
-
- private List<TimedPhase> getPhaseAlignments(final Plan plan, final PhaseType initialPhase, final DateTime initialPhaseStartDate)
- throws EntitlementUserApiException {
+ private List<TimedPhase> getPhaseAlignments(final Plan plan, @Nullable final PhaseType initialPhase, final DateTime initialPhaseStartDate) throws EntitlementUserApiException {
if (plan == null) {
return Collections.emptyList();
}
final List<TimedPhase> result = new LinkedList<TimedPhase>();
DateTime curPhaseStart = (initialPhase == null) ? initialPhaseStartDate : null;
- DateTime nextPhaseStart = null;
+ DateTime nextPhaseStart;
for (final PlanPhase cur : plan.getAllPhases()) {
// For create we can specify the phase so skip any phase until we reach initialPhase
if (curPhaseStart == null) {
@@ -289,9 +305,11 @@ public class PlanAligner {
curPhaseStart = nextPhaseStart;
}
}
+
if (initialPhase != null && curPhaseStart == null) {
throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_BAD_PHASE, initialPhase);
}
+
return result;
}
@@ -306,6 +324,7 @@ public class PlanAligner {
}
cur = phase;
}
+
switch (which) {
case CURRENT:
return cur;
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedMigration.java b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedMigration.java
index c692ca5..0c32b57 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedMigration.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedMigration.java
@@ -24,19 +24,15 @@ import com.ning.billing.entitlement.events.EntitlementEvent.EventType;
import com.ning.billing.entitlement.events.user.ApiEventType;
public class TimedMigration {
-
private final DateTime eventTime;
private final EventType eventType;
private final ApiEventType apiEventType;
-
private final Plan plan;
private final PlanPhase phase;
private final String priceList;
-
- public TimedMigration(final DateTime eventTime, final EventType eventType,
- final ApiEventType apiEventType, final Plan plan, final PlanPhase phase, final String priceList) {
- super();
+ public TimedMigration(final DateTime eventTime, final EventType eventType, final ApiEventType apiEventType,
+ final Plan plan, final PlanPhase phase, final String priceList) {
this.eventTime = eventTime;
this.eventType = eventType;
this.apiEventType = apiEventType;
@@ -53,7 +49,6 @@ public class TimedMigration {
return eventType;
}
-
public ApiEventType getApiEventType() {
return apiEventType;
}
@@ -69,4 +64,62 @@ public class TimedMigration {
public String getPriceList() {
return priceList;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("TimedMigration");
+ sb.append("{apiEventType=").append(apiEventType);
+ sb.append(", eventTime=").append(eventTime);
+ sb.append(", eventType=").append(eventType);
+ sb.append(", plan=").append(plan);
+ sb.append(", phase=").append(phase);
+ sb.append(", priceList='").append(priceList).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final TimedMigration that = (TimedMigration) o;
+
+ if (apiEventType != that.apiEventType) {
+ return false;
+ }
+ if (eventTime != null ? !eventTime.equals(that.eventTime) : that.eventTime != null) {
+ return false;
+ }
+ if (eventType != that.eventType) {
+ return false;
+ }
+ if (phase != null ? !phase.equals(that.phase) : that.phase != null) {
+ return false;
+ }
+ if (plan != null ? !plan.equals(that.plan) : that.plan != null) {
+ return false;
+ }
+ if (priceList != null ? !priceList.equals(that.priceList) : that.priceList != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = eventTime != null ? eventTime.hashCode() : 0;
+ result = 31 * result + (eventType != null ? eventType.hashCode() : 0);
+ result = 31 * result + (apiEventType != null ? apiEventType.hashCode() : 0);
+ result = 31 * result + (plan != null ? plan.hashCode() : 0);
+ result = 31 * result + (phase != null ? phase.hashCode() : 0);
+ result = 31 * result + (priceList != null ? priceList.hashCode() : 0);
+ return result;
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedPhase.java b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedPhase.java
index fb7bc1b..d79e940 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedPhase.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/alignment/TimedPhase.java
@@ -20,14 +20,11 @@ import org.joda.time.DateTime;
import com.ning.billing.catalog.api.PlanPhase;
-
public final class TimedPhase {
-
private final PlanPhase phase;
private final DateTime startPhase;
public TimedPhase(final PlanPhase phase, final DateTime startPhase) {
- super();
this.phase = phase;
this.startPhase = startPhase;
}
@@ -39,5 +36,43 @@ public final class TimedPhase {
public DateTime getStartPhase() {
return startPhase;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("TimedPhase");
+ sb.append("{phase=").append(phase);
+ sb.append(", startPhase=").append(startPhase);
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final TimedPhase phase1 = (TimedPhase) o;
+
+ if (phase != null ? !phase.equals(phase1.phase) : phase1.phase != null) {
+ return false;
+ }
+ if (startPhase != null ? !startPhase.equals(phase1.startPhase) : phase1.startPhase != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = phase != null ? phase.hashCode() : 0;
+ result = 31 * result + (startPhase != null ? startPhase.hashCode() : 0);
+ return result;
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/migration/DefaultEntitlementMigrationApi.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/migration/DefaultEntitlementMigrationApi.java
index e0f2860..fa79bda 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/migration/DefaultEntitlementMigrationApi.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/migration/DefaultEntitlementMigrationApi.java
@@ -78,7 +78,6 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
private AccountMigrationData createAccountMigrationData(final EntitlementAccountMigration toBeMigrated, final CallContext context)
throws EntitlementMigrationApiException {
-
final UUID accountId = toBeMigrated.getAccountKey();
final DateTime now = clock.getUTCNow();
@@ -89,7 +88,6 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
final SubscriptionBundleData bundleData = new SubscriptionBundleData(curBundle.getBundleKey(), accountId, clock.getUTCNow());
final List<SubscriptionMigrationData> bundleSubscriptionData = new LinkedList<AccountMigrationData.SubscriptionMigrationData>();
-
final List<EntitlementSubscriptionMigration> sortedSubscriptions = Lists.newArrayList(curBundle.getSubscriptions());
// Make sure we have first BASE or STANDALONE, then ADDON and for each category order by CED
Collections.sort(sortedSubscriptions, new Comparator<EntitlementSubscriptionMigration>() {
@@ -99,10 +97,10 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
if (o1.getCategory().equals(o2.getCategory())) {
return o1.getSubscriptionCases()[0].getEffectiveDate().compareTo(o2.getSubscriptionCases()[0].getEffectiveDate());
} else {
- if (!o1.getCategory().name().equalsIgnoreCase("ADD_ON")) {
+ if (!o1.getCategory().name().equalsIgnoreCase("ADD_ON")) {
return -1;
} else if (o1.getCategory().name().equalsIgnoreCase("ADD_ON")) {
- return 1;
+ return 1;
} else {
return 0;
}
@@ -127,24 +125,23 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
final BundleMigrationData bundleMigrationData = new BundleMigrationData(bundleData, bundleSubscriptionData);
accountBundleData.add(bundleMigrationData);
}
- final AccountMigrationData accountMigrationData = new AccountMigrationData(accountBundleData);
- return accountMigrationData;
+
+ return new AccountMigrationData(accountBundleData);
}
private SubscriptionMigrationData createInitialSubscription(final UUID bundleId, final ProductCategory productCategory,
final EntitlementSubscriptionMigrationCase[] input, final DateTime now, final DateTime ctd, final CallContext context)
throws EntitlementMigrationApiException {
-
final TimedMigration[] events = migrationAligner.getEventsMigration(input, now);
final DateTime migrationStartDate = events[0].getEventTime();
final List<EntitlementEvent> emptyEvents = Collections.emptyList();
final SubscriptionData subscriptionData = factory.createSubscription(new SubscriptionBuilder()
- .setId(UUID.randomUUID())
- .setBundleId(bundleId)
- .setCategory(productCategory)
- .setBundleStartDate(migrationStartDate)
- .setStartDate(migrationStartDate),
- emptyEvents);
+ .setId(UUID.randomUUID())
+ .setBundleId(bundleId)
+ .setCategory(productCategory)
+ .setBundleStartDate(migrationStartDate)
+ .setStartDate(migrationStartDate),
+ emptyEvents);
return new SubscriptionMigrationData(subscriptionData, toEvents(subscriptionData, now, ctd, events, context));
}
@@ -155,18 +152,16 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
final DateTime migrationStartDate = events[0].getEventTime();
final List<EntitlementEvent> emptyEvents = Collections.emptyList();
final SubscriptionData subscriptionData = factory.createSubscription(new SubscriptionBuilder()
- .setId(UUID.randomUUID())
- .setBundleId(bundleId)
- .setCategory(productCategory)
- .setBundleStartDate(bundleStartDate)
- .setStartDate(migrationStartDate),
- emptyEvents);
+ .setId(UUID.randomUUID())
+ .setBundleId(bundleId)
+ .setCategory(productCategory)
+ .setBundleStartDate(bundleStartDate)
+ .setStartDate(migrationStartDate),
+ emptyEvents);
return new SubscriptionMigrationData(subscriptionData, toEvents(subscriptionData, now, ctd, events, context));
}
private List<EntitlementEvent> toEvents(final SubscriptionData subscriptionData, final DateTime now, final DateTime ctd, final TimedMigration[] migrationEvents, final CallContext context) {
-
-
ApiEventMigrateEntitlement creationEvent = null;
final List<EntitlementEvent> events = new ArrayList<EntitlementEvent>(migrationEvents.length);
for (final TimedMigration cur : migrationEvents) {
@@ -213,9 +208,7 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
}
events.add(new ApiEventMigrateBilling(creationEvent, ctd));
Collections.sort(events, new Comparator<EntitlementEvent>() {
-
int compForApiType(final EntitlementEvent o1, final EntitlementEvent o2, final ApiEventType type) {
-
ApiEventType apiO1 = null;
if (o1.getType() == EventType.API_USER) {
apiO1 = ((ApiEvent) o1).getEventType();
@@ -224,9 +217,9 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
if (o2.getType() == EventType.API_USER) {
apiO2 = ((ApiEvent) o2).getEventType();
}
- if (apiO1 != null && apiO1 == type) {
+ if (apiO1 != null && apiO1.equals(type)) {
return -1;
- } else if (apiO2 != null && apiO2 == type) {
+ } else if (apiO2 != null && apiO2.equals(type)) {
return 1;
} else {
return 0;
@@ -246,6 +239,7 @@ public class DefaultEntitlementMigrationApi implements EntitlementMigrationApi {
return comp;
}
});
+
return events;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/DefaultEntitlementTimelineApi.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/DefaultEntitlementTimelineApi.java
index 3162a75..220c2ad 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/DefaultEntitlementTimelineApi.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/DefaultEntitlementTimelineApi.java
@@ -13,12 +13,12 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@@ -37,6 +37,7 @@ import com.ning.billing.entitlement.api.SubscriptionFactory;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.timeline.SubscriptionTimeline.NewEvent;
import com.ning.billing.entitlement.api.user.DefaultSubscriptionFactory.SubscriptionBuilder;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.entitlement.api.user.SubscriptionBundleData;
@@ -48,20 +49,17 @@ import com.ning.billing.entitlement.glue.DefaultEntitlementModule;
import com.ning.billing.util.callcontext.CallContext;
public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
-
private final EntitlementDao dao;
private final SubscriptionFactory factory;
private final RepairEntitlementLifecycleDao repairDao;
private final CatalogService catalogService;
-
private enum RepairType {
BASE_REPAIR,
ADD_ON_REPAIR,
STANDALONE_REPAIR
}
-
@Inject
public DefaultEntitlementTimelineApi(@Named(DefaultEntitlementModule.REPAIR_NAMED) final SubscriptionFactory factory, final CatalogService catalogService,
@Named(DefaultEntitlementModule.REPAIR_NAMED) final RepairEntitlementLifecycleDao repairDao, final EntitlementDao dao) {
@@ -71,11 +69,8 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
this.factory = factory;
}
-
@Override
- public BundleTimeline getBundleRepair(final UUID bundleId)
- throws EntitlementRepairException {
-
+ public BundleTimeline getBundleRepair(final UUID bundleId) throws EntitlementRepairException {
try {
final SubscriptionBundle bundle = dao.getSubscriptionBundleFromId(bundleId);
if (bundle == null) {
@@ -93,19 +88,14 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
}
}
-
@Override
- public BundleTimeline repairBundle(final BundleTimeline input, final boolean dryRun, final CallContext context)
- throws EntitlementRepairException {
-
+ public BundleTimeline repairBundle(final BundleTimeline input, final boolean dryRun, final CallContext context) throws EntitlementRepairException {
try {
-
final SubscriptionBundle bundle = dao.getSubscriptionBundleFromId(input.getBundleId());
if (bundle == null) {
throw new EntitlementRepairException(ErrorCode.ENT_REPAIR_UNKNOWN_BUNDLE, input.getBundleId());
}
-
// Subscriptions are ordered with BASE subscription first-- if exists
final List<Subscription> subscriptions = dao.getSubscriptions(factory, input.getBundleId());
if (subscriptions.size() == 0) {
@@ -127,8 +117,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
final List<SubscriptionDataRepair> addOnSubscriptionInRepair = new LinkedList<SubscriptionDataRepair>();
final List<SubscriptionDataRepair> inRepair = new LinkedList<SubscriptionDataRepair>();
for (final Subscription cur : subscriptions) {
-
- //
final SubscriptionTimeline curRepair = findAndCreateSubscriptionRepair(cur.getId(), input.getSubscriptions());
if (curRepair != null) {
final SubscriptionDataRepair curInputRepair = ((SubscriptionDataRepair) cur);
@@ -163,7 +151,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
validateFirstNewEvent(curInputRepair, curRepair.getNewEvents().get(0), lastRemainingBPEventTime, lastRemainingEventTime);
}
-
final SubscriptionDataRepair curOutputRepair = createSubscriptionDataRepair(curInputRepair, newBundleStartDate, newSubscriptionStartDate, remaining);
repairDao.initializeRepair(curInputRepair.getId(), remaining);
inRepair.add(curOutputRepair);
@@ -191,7 +178,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
addOnSubscriptionInRepair.add(curOutputRepair);
}
}
-
break;
case ADD_ON_REPAIR:
// We need to set the baseSubscription as it is useful to calculate addon validity
@@ -201,17 +187,14 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
case STANDALONE_REPAIR:
default:
break;
-
}
validateBasePlanRecreate(isBasePlanRecreate, subscriptions, input.getSubscriptions());
validateInputSubscriptionsKnown(subscriptions, input.getSubscriptions());
-
final Collection<NewEvent> newEvents = createOrderedNewEventInput(input.getSubscriptions());
- final Iterator<NewEvent> it = newEvents.iterator();
- while (it.hasNext()) {
- final DefaultNewEvent cur = (DefaultNewEvent) it.next();
+ for (final NewEvent newEvent : newEvents) {
+ final DefaultNewEvent cur = (DefaultNewEvent) newEvent;
final SubscriptionDataRepair curDataRepair = findSubscriptionDataRepair(cur.getSubscriptionId(), inRepair);
if (curDataRepair == null) {
throw new EntitlementRepairException(ErrorCode.ENT_REPAIR_UNKNOWN_SUBSCRIPTION, cur.getSubscriptionId());
@@ -220,7 +203,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
}
if (dryRun) {
-
baseSubscriptionRepair.addFutureAddonCancellation(addOnSubscriptionInRepair, context);
final List<SubscriptionTimeline> repairs = createGetSubscriptionRepairList(subscriptions, convertDataRepair(inRepair));
@@ -236,7 +218,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
}
}
-
private RepairType getRepairType(final Subscription firstSubscription, final boolean gotBaseSubscription) {
if (firstSubscription.getCategory() == ProductCategory.BASE) {
return gotBaseSubscription ? RepairType.BASE_REPAIR : RepairType.ADD_ON_REPAIR;
@@ -247,7 +228,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
private void validateBasePlanRecreate(final boolean isBasePlanRecreate, final List<Subscription> subscriptions, final List<SubscriptionTimeline> input)
throws EntitlementRepairException {
-
if (!isBasePlanRecreate) {
return;
}
@@ -263,10 +243,8 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
}
}
-
private void validateInputSubscriptionsKnown(final List<Subscription> subscriptions, final List<SubscriptionTimeline> input)
throws EntitlementRepairException {
-
for (final SubscriptionTimeline cur : input) {
boolean found = false;
for (final Subscription s : subscriptions) {
@@ -306,14 +284,13 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
newEventSet.add(new DefaultNewEvent(cur.getId(), e.getPlanPhaseSpecifier(), e.getRequestedDate(), e.getSubscriptionTransitionType()));
}
}
+
return newEventSet;
}
-
private List<EntitlementEvent> getRemainingEventsAndValidateDeletedEvents(final SubscriptionDataRepair data, final DateTime firstBPDeletedTime,
final List<SubscriptionTimeline.DeletedEvent> deletedEvents)
throws EntitlementRepairException {
-
if (deletedEvents == null || deletedEvents.size() == 0) {
return data.getEvents();
}
@@ -343,13 +320,13 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
result.add(cur);
}
}
+
if (nbDeleted != deletedEvents.size()) {
for (final SubscriptionTimeline.DeletedEvent d : deletedEvents) {
boolean found = false;
- for (final SubscriptionTransitionData cur : data.getAllTransitions()) {
+ for (final EffectiveSubscriptionEvent cur : data.getAllTransitions()) {
if (cur.getId().equals(d.getEventId())) {
found = true;
- continue;
}
}
if (!found) {
@@ -358,10 +335,10 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
}
}
+
return result;
}
-
private String getViewId(final DateTime lastUpdateBundleDate, final List<Subscription> subscriptions) {
final StringBuilder tmp = new StringBuilder();
long lastOrderedId = -1;
@@ -371,6 +348,7 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
tmp.append(lastOrderedId);
tmp.append("-");
tmp.append(lastUpdateBundleDate.toDate().getTime());
+
return tmp.toString();
}
@@ -396,7 +374,6 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
return externalKey;
}
};
-
}
private List<SubscriptionTimeline> createGetSubscriptionRepairList(final List<Subscription> subscriptions, final List<SubscriptionTimeline> inRepair) throws CatalogApiException {
@@ -407,20 +384,22 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
repairIds.add(cur.getId());
result.add(cur);
}
+
for (final Subscription cur : subscriptions) {
if (!repairIds.contains(cur.getId())) {
result.add(new DefaultSubscriptionTimeline((SubscriptionDataRepair) cur, catalogService.getFullCatalog()));
}
}
+
return result;
}
-
private List<SubscriptionTimeline> convertDataRepair(final List<SubscriptionDataRepair> input) throws CatalogApiException {
final List<SubscriptionTimeline> result = new LinkedList<SubscriptionTimeline>();
for (final SubscriptionDataRepair cur : input) {
result.add(new DefaultSubscriptionTimeline(cur, catalogService.getFullCatalog()));
}
+
return result;
}
@@ -430,10 +409,10 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
return cur;
}
}
+
return null;
}
-
private SubscriptionDataRepair createSubscriptionDataRepair(final SubscriptionData curData, final DateTime newBundleStartDate, final DateTime newSubscriptionStartDate, final List<EntitlementEvent> initialEvents) {
final SubscriptionBuilder builder = new SubscriptionBuilder(curData);
builder.setActiveVersion(curData.getActiveVersion() + 1);
@@ -448,10 +427,9 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
cur.setActiveVersion(builder.getActiveVersion());
}
}
- final SubscriptionDataRepair result = (SubscriptionDataRepair) factory.createSubscription(builder, initialEvents);
- return result;
- }
+ return (SubscriptionDataRepair) factory.createSubscription(builder, initialEvents);
+ }
private SubscriptionTimeline findAndCreateSubscriptionRepair(final UUID target, final List<SubscriptionTimeline> input) {
for (final SubscriptionTimeline cur : input) {
@@ -459,6 +437,7 @@ public class DefaultEntitlementTimelineApi implements EntitlementTimelineApi {
return new DefaultSubscriptionTimeline(cur);
}
}
+
return null;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/RepairSubscriptionFactory.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/RepairSubscriptionFactory.java
index e09989d..f0cafe6 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/RepairSubscriptionFactory.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/RepairSubscriptionFactory.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.List;
@@ -31,7 +32,6 @@ import com.ning.billing.entitlement.glue.DefaultEntitlementModule;
import com.ning.billing.util.clock.Clock;
public class RepairSubscriptionFactory extends DefaultSubscriptionFactory implements SubscriptionFactory {
-
private final AddonUtils addonUtils;
private final EntitlementDao repairDao;
@@ -47,8 +47,8 @@ public class RepairSubscriptionFactory extends DefaultSubscriptionFactory implem
@Override
public SubscriptionData createSubscription(final SubscriptionBuilder builder,
final List<EntitlementEvent> events) {
- final SubscriptionData subscription = new SubscriptionDataRepair(builder, events, apiService, repairDao, clock, addonUtils, catalogService);
- subscription.rebuildTransitions(events, catalogService.getFullCatalog());
+ final SubscriptionData subscription = new SubscriptionDataRepair(builder, events, getApiService(), repairDao, getClock(), addonUtils, getCatalogService());
+ subscription.rebuildTransitions(events, getCatalogService().getFullCatalog());
return subscription;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/SubscriptionDataRepair.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/SubscriptionDataRepair.java
index 85c42a6..66cf27c 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/SubscriptionDataRepair.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/timeline/SubscriptionDataRepair.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collection;
@@ -47,7 +48,6 @@ import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.clock.Clock;
public class SubscriptionDataRepair extends SubscriptionData {
-
private final AddonUtils addonUtils;
private final Clock clock;
private final EntitlementDao repairDao;
@@ -56,8 +56,7 @@ public class SubscriptionDataRepair extends SubscriptionData {
private final List<EntitlementEvent> initialEvents;
// Low level events are ONLY used for Repair APIs
- protected List<EntitlementEvent> events;
-
+ private List<EntitlementEvent> events;
public SubscriptionDataRepair(final SubscriptionBuilder builder, final List<EntitlementEvent> initialEvents, final SubscriptionApiService apiService,
final EntitlementDao dao, final Clock clock, final AddonUtils addonUtils, final CatalogService catalogService) {
@@ -69,7 +68,6 @@ public class SubscriptionDataRepair extends SubscriptionData {
this.initialEvents = initialEvents;
}
-
DateTime getLastUserEventEffectiveDate() {
DateTime res = null;
for (final EntitlementEvent cur : events) {
@@ -116,10 +114,9 @@ public class SubscriptionDataRepair extends SubscriptionData {
}
}
-
public void addFutureAddonCancellation(final List<SubscriptionDataRepair> addOnSubscriptionInRepair, final CallContext context) {
- if (category != ProductCategory.BASE) {
+ if (getCategory() != ProductCategory.BASE) {
return;
}
@@ -136,7 +133,7 @@ public class SubscriptionDataRepair extends SubscriptionData {
private void trickleDownBPEffectForAddon(final List<SubscriptionDataRepair> addOnSubscriptionInRepair, final DateTime effectiveDate, final CallContext context)
throws EntitlementUserApiException {
- if (category != ProductCategory.BASE) {
+ if (getCategory() != ProductCategory.BASE) {
return;
}
@@ -145,7 +142,6 @@ public class SubscriptionDataRepair extends SubscriptionData {
addAddonCancellationIfRequired(addOnSubscriptionInRepair, baseProduct, effectiveDate, context);
}
-
private void addAddonCancellationIfRequired(final List<SubscriptionDataRepair> addOnSubscriptionInRepair, final Product baseProduct, final DateTime effectiveDate, final CallContext context) {
final DateTime now = clock.getUTCNow();
@@ -162,14 +158,14 @@ public class SubscriptionDataRepair extends SubscriptionData {
!addonUtils.isAddonAvailable(baseProduct, addonCurrentPlan)) {
final EntitlementEvent cancelEvent = new ApiEventCancel(new ApiEventBuilder()
- .setSubscriptionId(cur.getId())
- .setActiveVersion(cur.getActiveVersion())
- .setProcessedDate(now)
- .setEffectiveDate(effectiveDate)
- .setRequestedDate(now)
- .setUserToken(context.getUserToken())
- .setFromDisk(true));
- repairDao.cancelSubscription(cur.getId(), cancelEvent, context, 0);
+ .setSubscriptionId(cur.getId())
+ .setActiveVersion(cur.getActiveVersion())
+ .setProcessedDate(now)
+ .setEffectiveDate(effectiveDate)
+ .setRequestedDate(now)
+ .setUserToken(context.getUserToken())
+ .setFromDisk(true));
+ repairDao.cancelSubscription(cur, cancelEvent, context, 0);
cur.rebuildTransitions(repairDao.getEventsForSubscription(cur.getId()), catalogService.getFullCatalog());
}
}
@@ -177,7 +173,7 @@ public class SubscriptionDataRepair extends SubscriptionData {
private void checkAddonRights(final SubscriptionDataRepair baseSubscription)
throws EntitlementUserApiException, CatalogApiException {
- if (category == ProductCategory.ADD_ON) {
+ if (getCategory() == ProductCategory.ADD_ON) {
addonUtils.checkAddonCreationRights(baseSubscription, getCurrentPlan());
}
}
@@ -195,14 +191,12 @@ public class SubscriptionDataRepair extends SubscriptionData {
return initialEvents;
}
-
public Collection<EntitlementEvent> getNewEvents() {
- final Collection<EntitlementEvent> newEvents = Collections2.filter(events, new Predicate<EntitlementEvent>() {
+ return Collections2.filter(events, new Predicate<EntitlementEvent>() {
@Override
public boolean apply(final EntitlementEvent input) {
return !initialEvents.contains(input);
}
});
- return newEvents;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEffectiveSubscriptionEvent.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEffectiveSubscriptionEvent.java
new file mode 100644
index 0000000..f8d66af
--- /dev/null
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEffectiveSubscriptionEvent.java
@@ -0,0 +1,55 @@
+/*
+ * 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.entitlement.api.user;
+
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.ning.billing.entitlement.api.SubscriptionTransitionType;
+
+public class DefaultEffectiveSubscriptionEvent extends DefaultSubscriptionEvent implements EffectiveSubscriptionEvent {
+ public DefaultEffectiveSubscriptionEvent(final SubscriptionTransitionData in, final DateTime startDate) {
+ super(in, startDate);
+ }
+
+ @JsonCreator
+ public DefaultEffectiveSubscriptionEvent(@JsonProperty("eventId") final UUID eventId,
+ @JsonProperty("subscriptionId") final UUID subscriptionId,
+ @JsonProperty("bundleId") final UUID bundleId,
+ @JsonProperty("requestedTransitionTime") final DateTime requestedTransitionTime,
+ @JsonProperty("effectiveTransitionTime") final DateTime effectiveTransitionTime,
+ @JsonProperty("previousState") final Subscription.SubscriptionState previousState,
+ @JsonProperty("previousPlan") final String previousPlan,
+ @JsonProperty("previousPhase") final String previousPhase,
+ @JsonProperty("previousPriceList") final String previousPriceList,
+ @JsonProperty("nextState") final Subscription.SubscriptionState nextState,
+ @JsonProperty("nextPlan") final String nextPlan,
+ @JsonProperty("nextPhase") final String nextPhase,
+ @JsonProperty("nextPriceList") final String nextPriceList,
+ @JsonProperty("totalOrdering") final Long totalOrdering,
+ @JsonProperty("userToken") final UUID userToken,
+ @JsonProperty("transitionType") final SubscriptionTransitionType transitionType,
+ @JsonProperty("remainingEventsForUserOperation") final Integer remainingEventsForUserOperation,
+ @JsonProperty("startDate") final DateTime startDate) {
+ super(eventId, subscriptionId, bundleId, requestedTransitionTime, effectiveTransitionTime, previousState, previousPlan,
+ previousPhase, previousPriceList, nextState, nextPlan, nextPhase, nextPriceList, totalOrdering, userToken,
+ transitionType, remainingEventsForUserOperation, startDate);
+ }
+}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEntitlementUserApi.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEntitlementUserApi.java
index 2b26c87..ce96066 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEntitlementUserApi.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultEntitlementUserApi.java
@@ -63,7 +63,6 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
this.subscriptionFactory = subscriptionFactory;
}
-
@Override
public SubscriptionBundle getBundleFromId(final UUID id) throws EntitlementUserApiException {
final SubscriptionBundle result = dao.getSubscriptionBundleFromId(id);
@@ -115,7 +114,6 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
return result;
}
-
public SubscriptionBundle createBundleForAccount(final UUID accountId, final String bundleName, final CallContext context)
throws EntitlementUserApiException {
final SubscriptionBundleData bundle = new SubscriptionBundleData(bundleName, accountId, clock.getUTCNow());
@@ -123,12 +121,12 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
}
@Override
- public Subscription createSubscription(final UUID bundleId, final PlanPhaseSpecifier spec, DateTime requestedDate,
+ public Subscription createSubscription(final UUID bundleId, final PlanPhaseSpecifier spec, final DateTime requestedDateWithMs,
final CallContext context) throws EntitlementUserApiException {
try {
final String realPriceList = (spec.getPriceListName() == null) ? PriceListSet.DEFAULT_PRICELIST_NAME : spec.getPriceListName();
final DateTime now = clock.getUTCNow();
- requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
+ final DateTime requestedDate = (requestedDateWithMs != null) ? DefaultClock.truncateMs(requestedDateWithMs) : now;
if (requestedDate.isAfter(now)) {
throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE, requestedDate.toString());
}
@@ -185,21 +183,18 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
plan.getProduct().getCategory().toString()));
}
- final SubscriptionData subscription = apiService.createPlan(new SubscriptionBuilder()
- .setId(UUID.randomUUID())
- .setBundleId(bundleId)
- .setCategory(plan.getProduct().getCategory())
- .setBundleStartDate(bundleStartDate)
- .setStartDate(effectiveDate),
- plan, spec.getPhaseType(), realPriceList, requestedDate, effectiveDate, now, context);
-
- return subscription;
+ return apiService.createPlan(new SubscriptionBuilder()
+ .setId(UUID.randomUUID())
+ .setBundleId(bundleId)
+ .setCategory(plan.getProduct().getCategory())
+ .setBundleStartDate(bundleStartDate)
+ .setStartDate(effectiveDate),
+ plan, spec.getPhaseType(), realPriceList, requestedDate, effectiveDate, now, context);
} catch (CatalogApiException e) {
throw new EntitlementUserApiException(e);
}
}
-
@Override
public DateTime getNextBillingDate(final UUID accountId) {
final List<SubscriptionBundle> bundles = getBundlesForAccount(accountId);
@@ -217,7 +212,6 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
return result;
}
-
@Override
public List<SubscriptionStatusDryRun> getDryRunChangePlanStatus(final UUID subscriptionId, final String baseProductName, final DateTime requestedDate)
throws EntitlementUserApiException {
@@ -247,9 +241,10 @@ public class DefaultEntitlementUserApi implements EntitlementUserApi {
reason = DryRunChangeReason.AO_NOT_AVAILABLE_IN_NEW_PLAN;
}
final SubscriptionStatusDryRun status = new DefaultSubscriptionStatusDryRun(cur.getId(),
- cur.getCurrentPlan().getProduct().getName(), cur.getCurrentPhase().getPhaseType(),
- cur.getCurrentPlan().getBillingPeriod(),
- cur.getCurrentPriceList().getName(), reason);
+ cur.getCurrentPlan().getProduct().getName(),
+ cur.getCurrentPhase().getPhaseType(),
+ cur.getCurrentPlan().getBillingPeriod(),
+ cur.getCurrentPriceList().getName(), reason);
result.add(status);
}
return result;
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultRequestedSubscriptionEvent.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultRequestedSubscriptionEvent.java
new file mode 100644
index 0000000..38b6b98
--- /dev/null
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultRequestedSubscriptionEvent.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2010-2012 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.entitlement.api.user;
+
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.ning.billing.entitlement.api.SubscriptionTransitionType;
+import com.ning.billing.entitlement.events.EntitlementEvent;
+
+public class DefaultRequestedSubscriptionEvent extends DefaultSubscriptionEvent implements RequestedSubscriptionEvent {
+ public DefaultRequestedSubscriptionEvent(final SubscriptionTransitionData in, final DateTime startDate) {
+ super(in, startDate);
+ }
+
+ @JsonCreator
+ public DefaultRequestedSubscriptionEvent(@JsonProperty("eventId") final UUID eventId,
+ @JsonProperty("subscriptionId") final UUID subscriptionId,
+ @JsonProperty("bundleId") final UUID bundleId,
+ @JsonProperty("requestedTransitionTime") final DateTime requestedTransitionTime,
+ @JsonProperty("effectiveTransitionTime") final DateTime effectiveTransitionTime,
+ @JsonProperty("previousState") final Subscription.SubscriptionState previousState,
+ @JsonProperty("previousPlan") final String previousPlan,
+ @JsonProperty("previousPhase") final String previousPhase,
+ @JsonProperty("previousPriceList") final String previousPriceList,
+ @JsonProperty("nextState") final Subscription.SubscriptionState nextState,
+ @JsonProperty("nextPlan") final String nextPlan,
+ @JsonProperty("nextPhase") final String nextPhase,
+ @JsonProperty("nextPriceList") final String nextPriceList,
+ @JsonProperty("totalOrdering") final Long totalOrdering,
+ @JsonProperty("userToken") final UUID userToken,
+ @JsonProperty("transitionType") final SubscriptionTransitionType transitionType,
+ @JsonProperty("remainingEventsForUserOperation") final Integer remainingEventsForUserOperation,
+ @JsonProperty("startDate") final DateTime startDate) {
+ super(eventId, subscriptionId, bundleId, requestedTransitionTime, effectiveTransitionTime, previousState, previousPlan,
+ previousPhase, previousPriceList, nextState, nextPlan, nextPhase, nextPriceList, totalOrdering, userToken,
+ transitionType, remainingEventsForUserOperation, startDate);
+ }
+
+ public DefaultRequestedSubscriptionEvent(final SubscriptionData subscription, final EntitlementEvent nextEvent) {
+ this(nextEvent.getId(), nextEvent.getSubscriptionId(), subscription.getBundleId(), nextEvent.getRequestedDate(), nextEvent.getEffectiveDate(),
+ null, null, null, null, null, null, null, null, nextEvent.getTotalOrdering(), null, null, 0, null);
+ }
+}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionApiService.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionApiService.java
index 327edb4..99e3e58 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionApiService.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionApiService.java
@@ -58,7 +58,6 @@ import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.DefaultClock;
public class DefaultSubscriptionApiService implements SubscriptionApiService {
-
private final Clock clock;
private final EntitlementDao dao;
private final CatalogService catalogService;
@@ -74,25 +73,22 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
public SubscriptionData createPlan(final SubscriptionBuilder builder, final Plan plan, final PhaseType initialPhase,
final String realPriceList, final DateTime requestedDate, final DateTime effectiveDate, final DateTime processedDate,
- final CallContext context)
- throws EntitlementUserApiException {
+ final CallContext context) throws EntitlementUserApiException {
final SubscriptionData subscription = new SubscriptionData(builder, this, clock);
-
createFromSubscription(subscription, plan, initialPhase, realPriceList, requestedDate, effectiveDate, processedDate, false, context);
return subscription;
}
-
- public boolean recreatePlan(final SubscriptionData subscription, final PlanPhaseSpecifier spec, DateTime requestedDate, final CallContext context)
+ public boolean recreatePlan(final SubscriptionData subscription, final PlanPhaseSpecifier spec, final DateTime requestedDateWithMs, final CallContext context)
throws EntitlementUserApiException {
-
final SubscriptionState currentState = subscription.getState();
if (currentState != null && currentState != SubscriptionState.CANCELLED) {
throw new EntitlementUserApiException(ErrorCode.ENT_RECREATE_BAD_STATE, subscription.getId(), currentState);
}
+
final DateTime now = clock.getUTCNow();
- requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
+ final DateTime requestedDate = (requestedDateWithMs != null) ? DefaultClock.truncateMs(requestedDateWithMs) : now;
validateRequestedDate(subscription, now, requestedDate);
try {
@@ -116,10 +112,7 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
private void createFromSubscription(final SubscriptionData subscription, final Plan plan, final PhaseType initialPhase,
final String realPriceList, final DateTime requestedDate, final DateTime effectiveDate, final DateTime processedDate,
- final boolean reCreate, final CallContext context)
- throws EntitlementUserApiException {
-
-
+ final boolean reCreate, final CallContext context) throws EntitlementUserApiException {
try {
final TimedPhase[] curAndNextPhases = planAligner.getCurrentAndNextTimedPhaseOnCreate(subscription, plan, initialPhase, realPriceList, requestedDate, effectiveDate);
@@ -146,7 +139,7 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
events.add(nextPhaseEvent);
}
if (reCreate) {
- dao.recreateSubscription(subscription.getId(), events, context);
+ dao.recreateSubscription(subscription, events, context);
} else {
dao.createSubscription(subscription, events, context);
}
@@ -156,9 +149,7 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
}
}
- public boolean cancel(final SubscriptionData subscription, DateTime requestedDate, final boolean eot, final CallContext context)
- throws EntitlementUserApiException {
-
+ public boolean cancel(final SubscriptionData subscription, final DateTime requestedDateWithMs, final boolean eot, final CallContext context) throws EntitlementUserApiException {
try {
final SubscriptionState currentState = subscription.getState();
if (currentState != SubscriptionState.ACTIVE) {
@@ -166,29 +157,29 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
}
final DateTime now = clock.getUTCNow();
- requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
+ final DateTime requestedDate = (requestedDateWithMs != null) ? DefaultClock.truncateMs(requestedDateWithMs) : now;
validateRequestedDate(subscription, now, requestedDate);
final Plan currentPlan = subscription.getCurrentPlan();
final PlanPhaseSpecifier planPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(),
- currentPlan.getProduct().getCategory(),
- subscription.getCurrentPlan().getBillingPeriod(),
- subscription.getCurrentPriceList().getName(),
- subscription.getCurrentPhase().getPhaseType());
+ currentPlan.getProduct().getCategory(),
+ subscription.getCurrentPlan().getBillingPeriod(),
+ subscription.getCurrentPriceList().getName(),
+ subscription.getCurrentPhase().getPhaseType());
final ActionPolicy policy = catalogService.getFullCatalog().planCancelPolicy(planPhase, requestedDate);
final DateTime effectiveDate = subscription.getPlanChangeEffectiveDate(policy, requestedDate);
final EntitlementEvent cancelEvent = new ApiEventCancel(new ApiEventBuilder()
- .setSubscriptionId(subscription.getId())
- .setActiveVersion(subscription.getActiveVersion())
- .setProcessedDate(now)
- .setEffectiveDate(effectiveDate)
- .setRequestedDate(requestedDate)
- .setUserToken(context.getUserToken())
- .setFromDisk(true));
-
- dao.cancelSubscription(subscription.getId(), cancelEvent, context, 0);
+ .setSubscriptionId(subscription.getId())
+ .setActiveVersion(subscription.getActiveVersion())
+ .setProcessedDate(now)
+ .setEffectiveDate(effectiveDate)
+ .setRequestedDate(requestedDate)
+ .setUserToken(context.getUserToken())
+ .setFromDisk(true));
+
+ dao.cancelSubscription(subscription, cancelEvent, context, 0);
subscription.rebuildTransitions(dao.getEventsForSubscription(subscription.getId()), catalogService.getFullCatalog());
return (policy == ActionPolicy.IMMEDIATE);
} catch (CatalogApiException e) {
@@ -196,23 +187,20 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
}
}
-
- public boolean uncancel(final SubscriptionData subscription, final CallContext context)
- throws EntitlementUserApiException {
-
+ public boolean uncancel(final SubscriptionData subscription, final CallContext context) throws EntitlementUserApiException {
if (!subscription.isSubscriptionFutureCancelled()) {
throw new EntitlementUserApiException(ErrorCode.ENT_UNCANCEL_BAD_STATE, subscription.getId().toString());
}
final DateTime now = clock.getUTCNow();
final EntitlementEvent uncancelEvent = new ApiEventUncancel(new ApiEventBuilder()
- .setSubscriptionId(subscription.getId())
- .setActiveVersion(subscription.getActiveVersion())
- .setProcessedDate(now)
- .setRequestedDate(now)
- .setEffectiveDate(now)
- .setUserToken(context.getUserToken())
- .setFromDisk(true));
+ .setSubscriptionId(subscription.getId())
+ .setActiveVersion(subscription.getActiveVersion())
+ .setProcessedDate(now)
+ .setRequestedDate(now)
+ .setEffectiveDate(now)
+ .setUserToken(context.getUserToken())
+ .setFromDisk(true));
final List<EntitlementEvent> uncancelEvents = new ArrayList<EntitlementEvent>();
uncancelEvents.add(uncancelEvent);
@@ -224,20 +212,18 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
if (nextPhaseEvent != null) {
uncancelEvents.add(nextPhaseEvent);
}
- dao.uncancelSubscription(subscription.getId(), uncancelEvents, context);
+
+ dao.uncancelSubscription(subscription, uncancelEvents, context);
subscription.rebuildTransitions(dao.getEventsForSubscription(subscription.getId()), catalogService.getFullCatalog());
+
return true;
}
public boolean changePlan(final SubscriptionData subscription, final String productName, final BillingPeriod term,
- final String priceList, DateTime requestedDate, final CallContext context)
-
- throws EntitlementUserApiException {
-
+ final String priceList, final DateTime requestedDateWithMs, final CallContext context) throws EntitlementUserApiException {
try {
-
final DateTime now = clock.getUTCNow();
- requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
+ final DateTime requestedDate = (requestedDateWithMs != null) ? DefaultClock.truncateMs(requestedDateWithMs) : now;
validateRequestedDate(subscription, now, requestedDate);
final PriceList currentPriceList = subscription.getCurrentPriceList();
@@ -256,13 +242,13 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
final Product destProduct = catalogService.getFullCatalog().findProduct(productName, requestedDate);
final Plan currentPlan = subscription.getCurrentPlan();
final PlanPhaseSpecifier fromPlanPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(),
- currentPlan.getProduct().getCategory(),
- currentPlan.getBillingPeriod(),
- currentPriceList.getName(), subscription.getCurrentPhase().getPhaseType());
+ currentPlan.getProduct().getCategory(),
+ currentPlan.getBillingPeriod(),
+ currentPriceList.getName(), subscription.getCurrentPhase().getPhaseType());
final PlanSpecifier toPlanPhase = new PlanSpecifier(productName,
- destProduct.getCategory(),
- term,
- priceList);
+ destProduct.getCategory(),
+ term,
+ priceList);
planChangeResult = catalogService.getFullCatalog().planChange(fromPlanPhase, toPlanPhase, requestedDate);
} catch (CatalogApiException e) {
@@ -278,16 +264,16 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
final TimedPhase currentTimedPhase = planAligner.getCurrentTimedPhaseOnChange(subscription, newPlan, newPriceList.getName(), requestedDate, effectiveDate);
final EntitlementEvent changeEvent = new ApiEventChange(new ApiEventBuilder()
- .setSubscriptionId(subscription.getId())
- .setEventPlan(newPlan.getName())
- .setEventPlanPhase(currentTimedPhase.getPhase().getName())
- .setEventPriceList(newPriceList.getName())
- .setActiveVersion(subscription.getActiveVersion())
- .setProcessedDate(now)
- .setEffectiveDate(effectiveDate)
- .setRequestedDate(requestedDate)
- .setUserToken(context.getUserToken())
- .setFromDisk(true));
+ .setSubscriptionId(subscription.getId())
+ .setEventPlan(newPlan.getName())
+ .setEventPlanPhase(currentTimedPhase.getPhase().getName())
+ .setEventPriceList(newPriceList.getName())
+ .setActiveVersion(subscription.getActiveVersion())
+ .setProcessedDate(now)
+ .setEffectiveDate(effectiveDate)
+ .setRequestedDate(requestedDate)
+ .setUserToken(context.getUserToken())
+ .setFromDisk(true));
final TimedPhase nextTimedPhase = planAligner.getNextTimedPhaseOnChange(subscription, newPlan, newPriceList.getName(), requestedDate, effectiveDate);
final PhaseEvent nextPhaseEvent = (nextTimedPhase != null) ?
@@ -299,7 +285,7 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
changeEvents.add(nextPhaseEvent);
}
changeEvents.add(changeEvent);
- dao.changePlan(subscription.getId(), changeEvents, context);
+ dao.changePlan(subscription, changeEvents, context);
subscription.rebuildTransitions(dao.getEventsForSubscription(subscription.getId()), catalogService.getFullCatalog());
return (policy == ActionPolicy.IMMEDIATE);
} catch (CatalogApiException e) {
@@ -314,12 +300,10 @@ public class DefaultSubscriptionApiService implements SubscriptionApiService {
throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_FUTURE_DATE, requestedDate.toString());
}
- final SubscriptionEvent previousTransition = subscription.getPreviousTransition();
+ final EffectiveSubscriptionEvent previousTransition = subscription.getPreviousTransition();
if (previousTransition != null && previousTransition.getEffectiveTransitionTime().isAfter(requestedDate)) {
throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE,
requestedDate.toString(), previousTransition.getEffectiveTransitionTime());
}
}
-
-
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionEvent.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionEvent.java
index f28ddb7..7c119cc 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionEvent.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionEvent.java
@@ -1,5 +1,5 @@
-/*
- * Copyright 2010-2011 Ning, Inc.
+/*
+ * Copyright 2010-2012 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
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.user;
import java.util.UUID;
@@ -23,28 +24,25 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
-import com.ning.billing.entitlement.api.user.Subscription.SubscriptionState;
-
-public class DefaultSubscriptionEvent implements SubscriptionEvent {
+public abstract class DefaultSubscriptionEvent implements SubscriptionEvent {
private final Long totalOrdering;
private final UUID subscriptionId;
private final UUID bundleId;
private final UUID eventId;
private final DateTime requestedTransitionTime;
private final DateTime effectiveTransitionTime;
- private final SubscriptionState previousState;
+ private final Subscription.SubscriptionState previousState;
private final String previousPriceList;
private final String previousPlan;
private final String previousPhase;
- private final SubscriptionState nextState;
+ private final Subscription.SubscriptionState nextState;
private final String nextPriceList;
private final String nextPlan;
private final String nextPhase;
private final Integer remainingEventsForUserOperation;
private final UUID userToken;
private final SubscriptionTransitionType transitionType;
-
private final DateTime startDate;
public DefaultSubscriptionEvent(final SubscriptionTransitionData in, final DateTime startDate) {
@@ -74,11 +72,11 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
@JsonProperty("bundleId") final UUID bundleId,
@JsonProperty("requestedTransitionTime") final DateTime requestedTransitionTime,
@JsonProperty("effectiveTransitionTime") final DateTime effectiveTransitionTime,
- @JsonProperty("previousState") final SubscriptionState previousState,
+ @JsonProperty("previousState") final Subscription.SubscriptionState previousState,
@JsonProperty("previousPlan") final String previousPlan,
@JsonProperty("previousPhase") final String previousPhase,
@JsonProperty("previousPriceList") final String previousPriceList,
- @JsonProperty("nextState") final SubscriptionState nextState,
+ @JsonProperty("nextState") final Subscription.SubscriptionState nextState,
@JsonProperty("nextPlan") final String nextPlan,
@JsonProperty("nextPhase") final String nextPhase,
@JsonProperty("nextPriceList") final String nextPriceList,
@@ -87,7 +85,6 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
@JsonProperty("transitionType") final SubscriptionTransitionType transitionType,
@JsonProperty("remainingEventsForUserOperation") final Integer remainingEventsForUserOperation,
@JsonProperty("startDate") final DateTime startDate) {
- super();
this.eventId = eventId;
this.subscriptionId = subscriptionId;
this.bundleId = bundleId;
@@ -130,9 +127,8 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
return bundleId;
}
-
@Override
- public SubscriptionState getPreviousState() {
+ public Subscription.SubscriptionState getPreviousState() {
return previousState;
}
@@ -157,11 +153,10 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
}
@Override
- public SubscriptionState getNextState() {
+ public Subscription.SubscriptionState getNextState() {
return nextState;
}
-
@Override
public String getPreviousPriceList() {
return previousPriceList;
@@ -182,7 +177,6 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
return remainingEventsForUserOperation;
}
-
@Override
public DateTime getRequestedTransitionTime() {
return requestedTransitionTime;
@@ -209,197 +203,121 @@ public class DefaultSubscriptionEvent implements SubscriptionEvent {
return startDate;
}
-
@Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((bundleId == null) ? 0 : bundleId.hashCode());
- result = prime
- * result
- + ((effectiveTransitionTime == null) ? 0
- : effectiveTransitionTime.hashCode());
- result = prime * result + ((eventId == null) ? 0 : eventId.hashCode());
- result = prime * result
- + ((nextPhase == null) ? 0 : nextPhase.hashCode());
- result = prime * result
- + ((nextPlan == null) ? 0 : nextPlan.hashCode());
- result = prime * result
- + ((nextPriceList == null) ? 0 : nextPriceList.hashCode());
- result = prime * result
- + ((nextState == null) ? 0 : nextState.hashCode());
- result = prime * result
- + ((previousPhase == null) ? 0 : previousPhase.hashCode());
- result = prime * result
- + ((previousPlan == null) ? 0 : previousPlan.hashCode());
- result = prime
- * result
- + ((previousPriceList == null) ? 0 : previousPriceList
- .hashCode());
- result = prime * result
- + ((previousState == null) ? 0 : previousState.hashCode());
- result = prime
- * result
- + ((remainingEventsForUserOperation == null) ? 0
- : remainingEventsForUserOperation.hashCode());
- result = prime
- * result
- + ((requestedTransitionTime == null) ? 0
- : requestedTransitionTime.hashCode());
- result = prime * result
- + ((subscriptionId == null) ? 0 : subscriptionId.hashCode());
- result = prime * result
- + ((totalOrdering == null) ? 0 : totalOrdering.hashCode());
- result = prime * result
- + ((transitionType == null) ? 0 : transitionType.hashCode());
- result = prime * result
- + ((userToken == null) ? 0 : userToken.hashCode());
- return result;
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(getClass().getSimpleName());
+ sb.append("{bundleId=").append(bundleId);
+ sb.append(", totalOrdering=").append(totalOrdering);
+ sb.append(", subscriptionId=").append(subscriptionId);
+ sb.append(", eventId=").append(eventId);
+ sb.append(", requestedTransitionTime=").append(requestedTransitionTime);
+ sb.append(", effectiveTransitionTime=").append(effectiveTransitionTime);
+ sb.append(", previousState=").append(previousState);
+ sb.append(", previousPriceList='").append(previousPriceList).append('\'');
+ sb.append(", previousPlan='").append(previousPlan).append('\'');
+ sb.append(", previousPhase='").append(previousPhase).append('\'');
+ sb.append(", nextState=").append(nextState);
+ sb.append(", nextPriceList='").append(nextPriceList).append('\'');
+ sb.append(", nextPlan='").append(nextPlan).append('\'');
+ sb.append(", nextPhase='").append(nextPhase).append('\'');
+ sb.append(", remainingEventsForUserOperation=").append(remainingEventsForUserOperation);
+ sb.append(", userToken=").append(userToken);
+ sb.append(", transitionType=").append(transitionType);
+ sb.append(", startDate=").append(startDate);
+ sb.append('}');
+ return sb.toString();
}
@Override
- public boolean equals(final Object obj) {
- if (this == obj) {
+ public boolean equals(final Object o) {
+ if (this == o) {
return true;
}
- if (obj == null) {
+ if (o == null || getClass() != o.getClass()) {
return false;
}
- if (getClass() != obj.getClass()) {
+
+ final DefaultSubscriptionEvent that = (DefaultSubscriptionEvent) o;
+
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
return false;
}
- final DefaultSubscriptionEvent other = (DefaultSubscriptionEvent) obj;
- if (bundleId == null) {
- if (other.bundleId != null) {
- return false;
- }
- } else if (!bundleId.equals(other.bundleId)) {
+ if (effectiveTransitionTime != null ? effectiveTransitionTime.compareTo(that.effectiveTransitionTime) != 0 : that.effectiveTransitionTime != null) {
return false;
}
- if (effectiveTransitionTime == null) {
- if (other.effectiveTransitionTime != null) {
- return false;
- }
- } else if (effectiveTransitionTime
- .compareTo(other.effectiveTransitionTime) != 0) {
+ if (eventId != null ? !eventId.equals(that.eventId) : that.eventId != null) {
return false;
}
- if (eventId == null) {
- if (other.eventId != null) {
- return false;
- }
- } else if (!eventId.equals(other.eventId)) {
+ if (nextPhase != null ? !nextPhase.equals(that.nextPhase) : that.nextPhase != null) {
return false;
}
- if (nextPhase == null) {
- if (other.nextPhase != null) {
- return false;
- }
- } else if (!nextPhase.equals(other.nextPhase)) {
+ if (nextPlan != null ? !nextPlan.equals(that.nextPlan) : that.nextPlan != null) {
return false;
}
- if (nextPlan == null) {
- if (other.nextPlan != null) {
- return false;
- }
- } else if (!nextPlan.equals(other.nextPlan)) {
+ if (nextPriceList != null ? !nextPriceList.equals(that.nextPriceList) : that.nextPriceList != null) {
return false;
}
- if (nextPriceList == null) {
- if (other.nextPriceList != null) {
- return false;
- }
- } else if (!nextPriceList.equals(other.nextPriceList)) {
+ if (nextState != that.nextState) {
return false;
}
- if (nextState != other.nextState) {
+ if (previousPhase != null ? !previousPhase.equals(that.previousPhase) : that.previousPhase != null) {
return false;
}
- if (previousPhase == null) {
- if (other.previousPhase != null) {
- return false;
- }
- } else if (!previousPhase.equals(other.previousPhase)) {
+ if (previousPlan != null ? !previousPlan.equals(that.previousPlan) : that.previousPlan != null) {
return false;
}
- if (previousPlan == null) {
- if (other.previousPlan != null) {
- return false;
- }
- } else if (!previousPlan.equals(other.previousPlan)) {
+ if (previousPriceList != null ? !previousPriceList.equals(that.previousPriceList) : that.previousPriceList != null) {
return false;
}
- if (previousPriceList == null) {
- if (other.previousPriceList != null) {
- return false;
- }
- } else if (!previousPriceList.equals(other.previousPriceList)) {
+ if (previousState != that.previousState) {
return false;
}
- if (previousState != other.previousState) {
+ if (remainingEventsForUserOperation != null ? !remainingEventsForUserOperation.equals(that.remainingEventsForUserOperation) : that.remainingEventsForUserOperation != null) {
return false;
}
- if (remainingEventsForUserOperation == null) {
- if (other.remainingEventsForUserOperation != null) {
- return false;
- }
- } else if (!remainingEventsForUserOperation
- .equals(other.remainingEventsForUserOperation)) {
+ if (requestedTransitionTime != null ? requestedTransitionTime.compareTo(that.requestedTransitionTime) != 0 : that.requestedTransitionTime != null) {
return false;
}
- if (requestedTransitionTime == null) {
- if (other.requestedTransitionTime != null) {
- return false;
- }
- } else if (requestedTransitionTime
- .compareTo(other.requestedTransitionTime) != 0) {
+ if (startDate != null ? startDate.compareTo(that.startDate) != 0 : that.startDate != null) {
return false;
}
- if (subscriptionId == null) {
- if (other.subscriptionId != null) {
- return false;
- }
- } else if (!subscriptionId.equals(other.subscriptionId)) {
+ if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
return false;
}
- if (totalOrdering == null) {
- if (other.totalOrdering != null) {
- return false;
- }
- } else if (!totalOrdering.equals(other.totalOrdering)) {
+ if (totalOrdering != null ? !totalOrdering.equals(that.totalOrdering) : that.totalOrdering != null) {
return false;
}
- if (transitionType != other.transitionType) {
+ if (transitionType != that.transitionType) {
return false;
}
- if (userToken == null) {
- if (other.userToken != null) {
- return false;
- }
- } else if (!userToken.equals(other.userToken)) {
+ if (userToken != null ? !userToken.equals(that.userToken) : that.userToken != null) {
return false;
}
+
return true;
}
@Override
- public String toString() {
- return "DefaultSubscriptionEvent [transitionType=" + transitionType
- + ", effectiveTransitionTime=" + effectiveTransitionTime
- + ", totalOrdering=" + totalOrdering
- + ", subscriptionId=" + subscriptionId + ", bundleId="
- + bundleId + ", eventId=" + eventId
- + ", requestedTransitionTime=" + requestedTransitionTime
- + ", previousState=" + previousState + ", previousPriceList="
- + previousPriceList + ", previousPlan=" + previousPlan
- + ", previousPhase=" + previousPhase + ", nextState="
- + nextState + ", nextPriceList=" + nextPriceList
- + ", nextPlan=" + nextPlan + ", nextPhase=" + nextPhase
- + ", remainingEventsForUserOperation="
- + remainingEventsForUserOperation + ", userToken=" + userToken
- + ", startDate=" + startDate + "]";
-
+ public int hashCode() {
+ int result = totalOrdering != null ? totalOrdering.hashCode() : 0;
+ result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (eventId != null ? eventId.hashCode() : 0);
+ result = 31 * result + (requestedTransitionTime != null ? requestedTransitionTime.hashCode() : 0);
+ result = 31 * result + (effectiveTransitionTime != null ? effectiveTransitionTime.hashCode() : 0);
+ result = 31 * result + (previousState != null ? previousState.hashCode() : 0);
+ result = 31 * result + (previousPriceList != null ? previousPriceList.hashCode() : 0);
+ result = 31 * result + (previousPlan != null ? previousPlan.hashCode() : 0);
+ result = 31 * result + (previousPhase != null ? previousPhase.hashCode() : 0);
+ result = 31 * result + (nextState != null ? nextState.hashCode() : 0);
+ result = 31 * result + (nextPriceList != null ? nextPriceList.hashCode() : 0);
+ result = 31 * result + (nextPlan != null ? nextPlan.hashCode() : 0);
+ result = 31 * result + (nextPhase != null ? nextPhase.hashCode() : 0);
+ result = 31 * result + (remainingEventsForUserOperation != null ? remainingEventsForUserOperation.hashCode() : 0);
+ result = 31 * result + (userToken != null ? userToken.hashCode() : 0);
+ result = 31 * result + (transitionType != null ? transitionType.hashCode() : 0);
+ result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
+ return result;
}
-
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionFactory.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionFactory.java
index bb2188f..8bd7471 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionFactory.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/DefaultSubscriptionFactory.java
@@ -32,10 +32,9 @@ import com.ning.billing.entitlement.exceptions.EntitlementError;
import com.ning.billing.util.clock.Clock;
public class DefaultSubscriptionFactory implements SubscriptionFactory {
-
- protected final SubscriptionApiService apiService;
- protected final Clock clock;
- protected final CatalogService catalogService;
+ private final SubscriptionApiService apiService;
+ private final Clock clock;
+ private final CatalogService catalogService;
@Inject
public DefaultSubscriptionFactory(final SubscriptionApiService apiService, final Clock clock, final CatalogService catalogService) {
@@ -44,7 +43,6 @@ public class DefaultSubscriptionFactory implements SubscriptionFactory {
this.catalogService = catalogService;
}
-
public SubscriptionData createSubscription(final SubscriptionBuilder builder, final List<EntitlementEvent> events) {
final SubscriptionData subscription = new SubscriptionData(builder, apiService, clock);
if (events.size() > 0) {
@@ -53,9 +51,7 @@ public class DefaultSubscriptionFactory implements SubscriptionFactory {
return subscription;
}
-
public static class SubscriptionBuilder {
-
private UUID id;
private UUID bundleId;
private DateTime startDate;
@@ -80,7 +76,6 @@ public class DefaultSubscriptionFactory implements SubscriptionFactory {
this.paidThroughDate = original.getPaidThroughDate();
}
-
public SubscriptionBuilder setId(final UUID id) {
this.id = id;
return this;
@@ -169,5 +164,15 @@ public class DefaultSubscriptionFactory implements SubscriptionFactory {
}
}
+ public SubscriptionApiService getApiService() {
+ return apiService;
+ }
+
+ public CatalogService getCatalogService() {
+ return catalogService;
+ }
+ public Clock getClock() {
+ return clock;
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundleData.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundleData.java
index be076ba..ede9ec0 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundleData.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionBundleData.java
@@ -16,6 +16,7 @@
package com.ning.billing.entitlement.api.user;
+import javax.annotation.Nullable;
import java.util.UUID;
import org.joda.time.DateTime;
@@ -24,28 +25,24 @@ import com.ning.billing.junction.api.BlockingState;
import com.ning.billing.overdue.OverdueState;
public class SubscriptionBundleData implements SubscriptionBundle {
-
private final UUID id;
private final String key;
private final UUID accountId;
- private final DateTime startDate;
private final DateTime lastSysTimeUpdate;
private final OverdueState<SubscriptionBundle> overdueState;
public SubscriptionBundleData(final String name, final UUID accountId, final DateTime startDate) {
- this(UUID.randomUUID(), name, accountId, startDate, startDate);
+ this(UUID.randomUUID(), name, accountId, startDate);
}
- public SubscriptionBundleData(final UUID id, final String key, final UUID accountId, final DateTime startDate, final DateTime lastSysUpdate) {
- this(id, key, accountId, startDate, lastSysUpdate, null);
+ public SubscriptionBundleData(final UUID id, final String key, final UUID accountId, final DateTime lastSysUpdate) {
+ this(id, key, accountId, lastSysUpdate, null);
}
- public SubscriptionBundleData(final UUID id, final String key, final UUID accountId, final DateTime startDate, final DateTime lastSysUpdate, final OverdueState<SubscriptionBundle> overdueState) {
- super();
+ public SubscriptionBundleData(final UUID id, final String key, final UUID accountId, final DateTime lastSysUpdate, @Nullable final OverdueState<SubscriptionBundle> overdueState) {
this.id = id;
this.key = key;
this.accountId = accountId;
- this.startDate = startDate;
this.lastSysTimeUpdate = lastSysUpdate;
this.overdueState = overdueState;
}
@@ -65,12 +62,6 @@ public class SubscriptionBundleData implements SubscriptionBundle {
return accountId;
}
- // STEPH do we need it ? and should we return that and when is that populated/updated?
- @Override
- public DateTime getStartDate() {
- return startDate;
- }
-
public DateTime getLastSysUpdateTime() {
return lastSysTimeUpdate;
}
@@ -84,4 +75,57 @@ public class SubscriptionBundleData implements SubscriptionBundle {
public BlockingState getBlockingState() {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("SubscriptionBundleData");
+ sb.append("{accountId=").append(accountId);
+ sb.append(", id=").append(id);
+ sb.append(", key='").append(key).append('\'');
+ sb.append(", lastSysTimeUpdate=").append(lastSysTimeUpdate);
+ sb.append(", overdueState=").append(overdueState);
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final SubscriptionBundleData that = (SubscriptionBundleData) o;
+
+ if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
+ return false;
+ }
+ if (id != null ? !id.equals(that.id) : that.id != null) {
+ return false;
+ }
+ if (key != null ? !key.equals(that.key) : that.key != null) {
+ return false;
+ }
+ if (lastSysTimeUpdate != null ? !lastSysTimeUpdate.equals(that.lastSysTimeUpdate) : that.lastSysTimeUpdate != null) {
+ return false;
+ }
+ if (overdueState != null ? !overdueState.equals(that.overdueState) : that.overdueState != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id != null ? id.hashCode() : 0;
+ result = 31 * result + (key != null ? key.hashCode() : 0);
+ result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
+ result = 31 * result + (lastSysTimeUpdate != null ? lastSysTimeUpdate.hashCode() : 0);
+ result = 31 * result + (overdueState != null ? overdueState.hashCode() : 0);
+ return result;
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
index e162011..58fe83c 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
@@ -54,35 +54,33 @@ import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.entity.EntityBase;
public class SubscriptionData extends EntityBase implements Subscription {
-
private static final Logger log = LoggerFactory.getLogger(SubscriptionData.class);
+ private final Clock clock;
+ private final SubscriptionApiService apiService;
- protected final Clock clock;
- protected final SubscriptionApiService apiService;
//
// Final subscription fields
//
- protected final UUID bundleId;
- protected final DateTime startDate;
- protected final DateTime bundleStartDate;
- protected final ProductCategory category;
+ private final UUID bundleId;
+ private final DateTime startDate;
+ private final DateTime bundleStartDate;
+ private final ProductCategory category;
//
// Those can be modified through non User APIs, and a new Subscription
// object would be created
//
- protected final long activeVersion;
- protected final DateTime chargedThroughDate;
- protected final DateTime paidThroughDate;
-
+ private final long activeVersion;
+ private final DateTime chargedThroughDate;
+ private final DateTime paidThroughDate;
//
// User APIs (create, change, cancel,...) will recompute those each time,
// so the user holding that subscription object get the correct state when
// the call completes
//
- protected LinkedList<SubscriptionTransitionData> transitions;
+ private LinkedList<SubscriptionTransitionData> transitions;
// Transient object never returned at the API
public SubscriptionData(final SubscriptionBuilder builder) {
@@ -140,7 +138,7 @@ public class SubscriptionData extends EntityBase implements Subscription {
@Override
public DateTime getEndDate() {
- final SubscriptionEvent latestTransition = getPreviousTransition();
+ final EffectiveSubscriptionEvent latestTransition = getPreviousTransition();
if (latestTransition.getNextState() == SubscriptionState.CANCELLED) {
return latestTransition.getEffectiveTransitionTime();
}
@@ -148,6 +146,24 @@ public class SubscriptionData extends EntityBase implements Subscription {
}
@Override
+ public DateTime getFutureEndDate() {
+ if (transitions == null) {
+ return null;
+ }
+ final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(
+ clock, transitions, Order.ASC_FROM_PAST, Kind.ENTITLEMENT,
+ Visibility.ALL, TimeLimit.FUTURE_ONLY);
+ while (it.hasNext()) {
+ final SubscriptionTransitionData cur = it.next();
+ if (cur.getTransitionType() == SubscriptionTransitionType.CANCEL) {
+ return cur.getEffectiveTransitionTime();
+ }
+ }
+ return null;
+ }
+
+
+ @Override
public boolean cancel(final DateTime requestedDate, final boolean eot,
final CallContext context) throws EntitlementUserApiException {
return apiService.cancel(this, requestedDate, eot, context);
@@ -174,12 +190,12 @@ public class SubscriptionData extends EntityBase implements Subscription {
}
@Override
- public SubscriptionEvent getPendingTransition() {
+ public EffectiveSubscriptionEvent getPendingTransition() {
final SubscriptionTransitionData data = getPendingTransitionData();
if (data == null) {
return null;
}
- return new DefaultSubscriptionEvent(data, startDate);
+ return new DefaultEffectiveSubscriptionEvent(data, startDate);
}
@Override
@@ -198,12 +214,12 @@ public class SubscriptionData extends EntityBase implements Subscription {
}
@Override
- public SubscriptionEvent getPreviousTransition() {
+ public EffectiveSubscriptionEvent getPreviousTransition() {
final SubscriptionTransitionData data = getPreviousTransitionData();
if (data == null) {
return null;
}
- return new DefaultSubscriptionEvent(data, startDate);
+ return new DefaultEffectiveSubscriptionEvent(data, startDate);
}
protected SubscriptionTransitionData getPreviousTransitionData() {
@@ -266,30 +282,30 @@ public class SubscriptionData extends EntityBase implements Subscription {
return true;
}
- public List<SubscriptionEvent> getBillingTransitions() {
+ @Override
+ public List<EffectiveSubscriptionEvent> getBillingTransitions() {
if (transitions == null) {
return Collections.emptyList();
}
- final List<SubscriptionEvent> result = new ArrayList<SubscriptionEvent>();
+ final List<EffectiveSubscriptionEvent> result = new ArrayList<EffectiveSubscriptionEvent>();
final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(
clock, transitions, Order.ASC_FROM_PAST, Kind.BILLING,
Visibility.ALL, TimeLimit.ALL);
while (it.hasNext()) {
- result.add(new DefaultSubscriptionEvent(it.next(), startDate));
+ result.add(new DefaultEffectiveSubscriptionEvent(it.next(), startDate));
}
return result;
}
-
- public SubscriptionEvent getTransitionFromEvent(final EntitlementEvent event, final int seqId) {
+ public EffectiveSubscriptionEvent getTransitionFromEvent(final EntitlementEvent event, final int seqId) {
if (transitions == null || event == null) {
return null;
}
for (final SubscriptionTransitionData cur : transitions) {
if (cur.getId().equals(event.getId())) {
final SubscriptionTransitionData withSeq = new SubscriptionTransitionData(cur, seqId);
- return new DefaultSubscriptionEvent(withSeq, startDate);
+ return new DefaultEffectiveSubscriptionEvent(withSeq, startDate);
}
}
return null;
@@ -306,20 +322,33 @@ public class SubscriptionData extends EntityBase implements Subscription {
return activeVersion;
}
+ @Override
+ public List<EffectiveSubscriptionEvent> getAllTransitions() {
+ if (transitions == null) {
+ return Collections.emptyList();
+ }
+
+ final List<EffectiveSubscriptionEvent> result = new ArrayList<EffectiveSubscriptionEvent>();
+ final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(clock, transitions, Order.ASC_FROM_PAST, Kind.ALL, Visibility.ALL, TimeLimit.ALL);
+ while (it.hasNext()) {
+ result.add(new DefaultEffectiveSubscriptionEvent(it.next(), startDate));
+ }
- public List<SubscriptionTransitionData> getAllTransitions() {
- return transitions;
+ return result;
}
public SubscriptionTransitionData getInitialTransitionForCurrentPlan() {
if (transitions == null) {
- throw new EntitlementError(String.format(
- "No transitions for subscription %s", getId()));
+ throw new EntitlementError(String.format("No transitions for subscription %s", getId()));
}
- final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(
- clock, transitions, Order.DESC_FROM_FUTURE, Kind.ENTITLEMENT,
- Visibility.ALL, TimeLimit.PAST_OR_PRESENT_ONLY);
+ final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(clock,
+ transitions,
+ Order.DESC_FROM_FUTURE,
+ Kind.ENTITLEMENT,
+ Visibility.ALL,
+ TimeLimit.PAST_OR_PRESENT_ONLY);
+
while (it.hasNext()) {
final SubscriptionTransitionData cur = it.next();
if (cur.getTransitionType() == SubscriptionTransitionType.CREATE
@@ -329,25 +358,13 @@ public class SubscriptionData extends EntityBase implements Subscription {
return cur;
}
}
- throw new EntitlementError(String.format(
- "Failed to find InitialTransitionForCurrentPlan id = %s",
- getId().toString()));
+
+ throw new EntitlementError(String.format("Failed to find InitialTransitionForCurrentPlan id = %s", getId()));
}
+
public boolean isSubscriptionFutureCancelled() {
- if (transitions == null) {
- return false;
- }
- final SubscriptionTransitionDataIterator it = new SubscriptionTransitionDataIterator(
- clock, transitions, Order.ASC_FROM_PAST, Kind.ENTITLEMENT,
- Visibility.ALL, TimeLimit.FUTURE_ONLY);
- while (it.hasNext()) {
- final SubscriptionTransitionData cur = it.next();
- if (cur.getTransitionType() == SubscriptionTransitionType.CANCEL) {
- return true;
- }
- }
- return false;
+ return getFutureEndDate() != null;
}
public DateTime getPlanChangeEffectiveDate(final ActionPolicy policy,
@@ -482,10 +499,9 @@ public class SubscriptionData extends EntityBase implements Subscription {
nextPhase = (nextPhaseName != null) ? catalog.findPhase(nextPhaseName, cur.getRequestedDate(), getStartDate()) : null;
nextPriceList = (nextPriceListName != null) ? catalog.findPriceList(nextPriceListName, cur.getRequestedDate()) : null;
} catch (CatalogApiException e) {
- log.error(String.format(
- "Failed to build transition for subscription %s", id),
- e);
+ log.error(String.format("Failed to build transition for subscription %s", id), e);
}
+
final SubscriptionTransitionData transition = new SubscriptionTransitionData(
cur.getId(), id, bundleId, cur.getType(), apiEventType,
cur.getRequestedDate(), cur.getEffectiveDate(),
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvents.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvents.java
index 31d664d..dae1ddf 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvents.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionEvents.java
@@ -17,21 +17,19 @@
package com.ning.billing.entitlement.api.user;
import java.util.LinkedList;
+import java.util.List;
import java.util.UUID;
import com.ning.billing.entitlement.events.EntitlementEvent;
public class SubscriptionEvents {
-
public static final long INITIAL_VERSION = 1;
- private final LinkedList<EntitlementEvent> events;
+ private final List<EntitlementEvent> events;
private long activeVersion;
- public SubscriptionEvents(final UUID subscriptionId) {
- super();
- final UUID subscriptionId1 = subscriptionId;
+ public SubscriptionEvents() {
this.events = new LinkedList<EntitlementEvent>();
this.activeVersion = INITIAL_VERSION;
}
@@ -40,22 +38,21 @@ public class SubscriptionEvents {
events.add(ev);
}
- public LinkedList<EntitlementEvent> getCurrentView() {
+ public List<EntitlementEvent> getCurrentView() {
return getViewForVersion(activeVersion);
}
- public LinkedList<EntitlementEvent> getViewForVersion(final long version) {
-
+ public List<EntitlementEvent> getViewForVersion(final long version) {
final LinkedList<EntitlementEvent> result = new LinkedList<EntitlementEvent>();
for (final EntitlementEvent cur : events) {
if (cur.getActiveVersion() == version) {
result.add(cur);
}
}
+
return result;
}
-
public long getActiveVersion() {
return activeVersion;
}
@@ -63,4 +60,42 @@ public class SubscriptionEvents {
public void setActiveVersion(final long activeVersion) {
this.activeVersion = activeVersion;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("SubscriptionEvents");
+ sb.append("{activeVersion=").append(activeVersion);
+ sb.append(", events=").append(events);
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final SubscriptionEvents that = (SubscriptionEvents) o;
+
+ if (activeVersion != that.activeVersion) {
+ return false;
+ }
+ if (events != null ? !events.equals(that.events) : that.events != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = events != null ? events.hashCode() : 0;
+ result = 31 * result + (int) (activeVersion ^ (activeVersion >>> 32));
+ return result;
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionTransitionData.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionTransitionData.java
index ac54ea3..d3707fa 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionTransitionData.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionTransitionData.java
@@ -30,8 +30,6 @@ import com.ning.billing.entitlement.events.user.ApiEventType;
import com.ning.billing.entitlement.exceptions.EntitlementError;
public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
-
-
private final Long totalOrdering;
private final UUID subscriptionId;
private final UUID bundleId;
@@ -52,7 +50,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
private final Integer remainingEventsForUserOperation;
private final UUID userToken;
-
public SubscriptionTransitionData(final UUID eventId,
final UUID subscriptionId,
final UUID bundleId,
@@ -71,7 +68,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
final Long totalOrdering,
final UUID userToken,
final Boolean isFromDisk) {
- super();
this.eventId = eventId;
this.subscriptionId = subscriptionId;
this.bundleId = bundleId;
@@ -116,7 +112,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
this.remainingEventsForUserOperation = remainingEventsForUserOperation;
}
-
public UUID getId() {
return eventId;
}
@@ -153,7 +148,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
return nextState;
}
-
public PriceList getPreviousPriceList() {
return previousPriceList;
}
@@ -170,7 +164,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
return remainingEventsForUserOperation;
}
-
public SubscriptionTransitionType getTransitionType() {
return toSubscriptionTransitionType(eventType, apiEventType);
}
@@ -194,7 +187,6 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
return effectiveTransitionTime;
}
-
public Long getTotalOrdering() {
return totalOrdering;
}
@@ -211,21 +203,126 @@ public class SubscriptionTransitionData /* implements SubscriptionEvent */ {
return eventType;
}
-
@Override
public String toString() {
- return "SubscriptionTransition [eventId=" + eventId
- + ", subscriptionId=" + subscriptionId
- + ", eventType=" + eventType + ", apiEventType="
- + apiEventType + ", requestedTransitionTime=" + requestedTransitionTime
- + ", effectiveTransitionTime=" + effectiveTransitionTime
- + ", previousState=" + previousState + ", previousPlan="
- + ((previousPlan != null) ? previousPlan.getName() : null)
- + ", previousPhase=" + ((previousPhase != null) ? previousPhase.getName() : null)
- + ", previousPriceList " + previousPriceList
- + ", nextState=" + nextState
- + ", nextPlan=" + ((nextPlan != null) ? nextPlan.getName() : null)
- + ", nextPriceList " + nextPriceList
- + ", nextPhase=" + ((nextPhase != null) ? nextPhase.getName() : null) + "]";
+ final StringBuilder sb = new StringBuilder();
+ sb.append("SubscriptionTransitionData");
+ sb.append("{apiEventType=").append(apiEventType);
+ sb.append(", totalOrdering=").append(totalOrdering);
+ sb.append(", subscriptionId=").append(subscriptionId);
+ sb.append(", bundleId=").append(bundleId);
+ sb.append(", eventId=").append(eventId);
+ sb.append(", eventType=").append(eventType);
+ sb.append(", requestedTransitionTime=").append(requestedTransitionTime);
+ sb.append(", effectiveTransitionTime=").append(effectiveTransitionTime);
+ sb.append(", previousState=").append(previousState);
+ sb.append(", previousPriceList=").append(previousPriceList);
+ sb.append(", previousPlan=").append(previousPlan);
+ sb.append(", previousPhase=").append(previousPhase);
+ sb.append(", nextState=").append(nextState);
+ sb.append(", nextPriceList=").append(nextPriceList);
+ sb.append(", nextPlan=").append(nextPlan);
+ sb.append(", nextPhase=").append(nextPhase);
+ sb.append(", isFromDisk=").append(isFromDisk);
+ sb.append(", remainingEventsForUserOperation=").append(remainingEventsForUserOperation);
+ sb.append(", userToken=").append(userToken);
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final SubscriptionTransitionData that = (SubscriptionTransitionData) o;
+
+ if (apiEventType != that.apiEventType) {
+ return false;
+ }
+ if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
+ return false;
+ }
+ if (effectiveTransitionTime != null ? effectiveTransitionTime.compareTo(that.effectiveTransitionTime) != 0 : that.effectiveTransitionTime != null) {
+ return false;
+ }
+ if (eventId != null ? !eventId.equals(that.eventId) : that.eventId != null) {
+ return false;
+ }
+ if (eventType != that.eventType) {
+ return false;
+ }
+ if (isFromDisk != null ? !isFromDisk.equals(that.isFromDisk) : that.isFromDisk != null) {
+ return false;
+ }
+ if (nextPhase != null ? !nextPhase.equals(that.nextPhase) : that.nextPhase != null) {
+ return false;
+ }
+ if (nextPlan != null ? !nextPlan.equals(that.nextPlan) : that.nextPlan != null) {
+ return false;
+ }
+ if (nextPriceList != null ? !nextPriceList.equals(that.nextPriceList) : that.nextPriceList != null) {
+ return false;
+ }
+ if (nextState != that.nextState) {
+ return false;
+ }
+ if (previousPhase != null ? !previousPhase.equals(that.previousPhase) : that.previousPhase != null) {
+ return false;
+ }
+ if (previousPlan != null ? !previousPlan.equals(that.previousPlan) : that.previousPlan != null) {
+ return false;
+ }
+ if (previousPriceList != null ? !previousPriceList.equals(that.previousPriceList) : that.previousPriceList != null) {
+ return false;
+ }
+ if (previousState != that.previousState) {
+ return false;
+ }
+ if (remainingEventsForUserOperation != null ? !remainingEventsForUserOperation.equals(that.remainingEventsForUserOperation) : that.remainingEventsForUserOperation != null) {
+ return false;
+ }
+ if (requestedTransitionTime != null ? requestedTransitionTime.compareTo(that.requestedTransitionTime) != 0 : that.requestedTransitionTime != null) {
+ return false;
+ }
+ if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
+ return false;
+ }
+ if (totalOrdering != null ? !totalOrdering.equals(that.totalOrdering) : that.totalOrdering != null) {
+ return false;
+ }
+ if (userToken != null ? !userToken.equals(that.userToken) : that.userToken != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = totalOrdering != null ? totalOrdering.hashCode() : 0;
+ result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
+ result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
+ result = 31 * result + (eventId != null ? eventId.hashCode() : 0);
+ result = 31 * result + (eventType != null ? eventType.hashCode() : 0);
+ result = 31 * result + (apiEventType != null ? apiEventType.hashCode() : 0);
+ result = 31 * result + (requestedTransitionTime != null ? requestedTransitionTime.hashCode() : 0);
+ result = 31 * result + (effectiveTransitionTime != null ? effectiveTransitionTime.hashCode() : 0);
+ result = 31 * result + (previousState != null ? previousState.hashCode() : 0);
+ result = 31 * result + (previousPriceList != null ? previousPriceList.hashCode() : 0);
+ result = 31 * result + (previousPlan != null ? previousPlan.hashCode() : 0);
+ result = 31 * result + (previousPhase != null ? previousPhase.hashCode() : 0);
+ result = 31 * result + (nextState != null ? nextState.hashCode() : 0);
+ result = 31 * result + (nextPriceList != null ? nextPriceList.hashCode() : 0);
+ result = 31 * result + (nextPlan != null ? nextPlan.hashCode() : 0);
+ result = 31 * result + (nextPhase != null ? nextPhase.hashCode() : 0);
+ result = 31 * result + (isFromDisk != null ? isFromDisk.hashCode() : 0);
+ result = 31 * result + (remainingEventsForUserOperation != null ? remainingEventsForUserOperation.hashCode() : 0);
+ result = 31 * result + (userToken != null ? userToken.hashCode() : 0);
+ return result;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/addon/AddonUtils.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/addon/AddonUtils.java
index 44079d8..fd86f63 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/addon/AddonUtils.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/addon/AddonUtils.java
@@ -17,8 +17,6 @@
package com.ning.billing.entitlement.engine.addon;
import org.joda.time.DateTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
@@ -32,9 +30,6 @@ import com.ning.billing.entitlement.api.user.SubscriptionData;
import com.ning.billing.entitlement.exceptions.EntitlementError;
public class AddonUtils {
-
- private static final Logger logger = LoggerFactory.getLogger(AddonUtils.class);
-
private final CatalogService catalogService;
@Inject
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/core/Engine.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/core/Engine.java
index a4a926e..57b21d3 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/core/Engine.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/core/Engine.java
@@ -16,15 +16,11 @@
package com.ning.billing.entitlement.engine.core;
-
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;
-
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,8 +65,6 @@ import com.ning.billing.util.notificationq.NotificationQueueService.Notification
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
public class Engine implements EventListener, EntitlementService {
-
-
public static final String NOTIFICATION_QUEUE_NAME = "subscription-events";
public static final String ENTITLEMENT_SERVICE_NAME = "entitlement-service";
@@ -81,21 +75,20 @@ public class Engine implements EventListener, EntitlementService {
private final PlanAligner planAligner;
private final AddonUtils addonUtils;
private final Bus eventBus;
-
private final EntitlementConfig config;
private final NotificationQueueService notificationQueueService;
private final CallContextFactory factory;
private final SubscriptionFactory subscriptionFactory;
+
private NotificationQueue subscriptionEventQueue;
@Inject
public Engine(final Clock clock, final EntitlementDao dao, final PlanAligner planAligner,
- final EntitlementConfig config,
- final AddonUtils addonUtils, final Bus eventBus,
- final NotificationQueueService notificationQueueService,
- final SubscriptionFactory subscriptionFactory,
- final CallContextFactory factory) {
- super();
+ final EntitlementConfig config,
+ final AddonUtils addonUtils, final Bus eventBus,
+ final NotificationQueueService notificationQueueService,
+ final SubscriptionFactory subscriptionFactory,
+ final CallContextFactory factory) {
this.clock = clock;
this.dao = dao;
this.planAligner = planAligner;
@@ -114,32 +107,29 @@ public class Engine implements EventListener, EntitlementService {
@LifecycleHandlerType(LifecycleLevel.INIT_SERVICE)
public void initialize() {
-
try {
- subscriptionEventQueue = notificationQueueService.createNotificationQueue(ENTITLEMENT_SERVICE_NAME,
- NOTIFICATION_QUEUE_NAME,
- new NotificationQueueHandler() {
+ final NotificationQueueHandler queueHandler = new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey inputKey, final DateTime eventDateTime) {
-
- if (! (inputKey instanceof EntitlementNotificationKey)) {
+ if (!(inputKey instanceof EntitlementNotificationKey)) {
log.error("Entitlement service received an unexpected event type {}" + inputKey.getClass().getName());
return;
}
- EntitlementNotificationKey key = (EntitlementNotificationKey) inputKey;
-
- final EntitlementEvent event = dao.getEventById(key.getEventId());
+
+ final EntitlementNotificationKey key = (EntitlementNotificationKey) inputKey;
+ final EntitlementEvent event = dao.getEventById(key.getEventId());
if (event == null) {
log.warn("Failed to extract event for notification key {}", inputKey);
return;
}
+
final UUID userToken = (event.getType() == EventType.API_USER) ? ((ApiEvent) event).getUserToken() : null;
final CallContext context = factory.createCallContext("SubscriptionEventQueue", CallOrigin.INTERNAL, UserType.SYSTEM, userToken);
processEventReady(event, key.getSeqId(), context);
}
- },
- new NotificationConfig() {
+ };
+ final NotificationConfig notificationConfig = new NotificationConfig() {
@Override
public long getSleepTimeMs() {
return config.getSleepTimeMs();
@@ -149,8 +139,12 @@ public class Engine implements EventListener, EntitlementService {
public boolean isNotificationProcessingOff() {
return config.isNotificationProcessingOff();
}
- }
- );
+ };
+
+ subscriptionEventQueue = notificationQueueService.createNotificationQueue(ENTITLEMENT_SERVICE_NAME,
+ NOTIFICATION_QUEUE_NAME,
+ queueHandler,
+ notificationConfig);
} catch (NotificationQueueAlreadyExists e) {
throw new RuntimeException(e);
}
@@ -169,12 +163,12 @@ public class Engine implements EventListener, EntitlementService {
}
}
-
@Override
public void processEventReady(final EntitlementEvent event, final int seqId, final CallContext context) {
if (!event.isActive()) {
return;
}
+
final SubscriptionData subscription = (SubscriptionData) dao.getSubscriptionFromId(subscriptionFactory, event.getSubscriptionId());
if (subscription == null) {
log.warn("Failed to retrieve subscription for id %s", event.getSubscriptionId());
@@ -192,10 +186,10 @@ public class Engine implements EventListener, EntitlementService {
int theRealSeqId = seqId;
if (event.getType() == EventType.PHASE) {
onPhaseEvent(subscription, context);
- } else if (event.getType() == EventType.API_USER &&
- subscription.getCategory() == ProductCategory.BASE) {
+ } else if (event.getType() == EventType.API_USER && subscription.getCategory() == ProductCategory.BASE) {
theRealSeqId = onBasePlanEvent(subscription, (ApiEvent) event, context);
}
+
try {
eventBus.post(subscription.getTransitionFromEvent(event, theRealSeqId));
} catch (EventBusException e) {
@@ -203,41 +197,36 @@ public class Engine implements EventListener, EntitlementService {
}
}
-
private void onPhaseEvent(final SubscriptionData subscription, final CallContext context) {
try {
final DateTime now = clock.getUTCNow();
final TimedPhase nextTimedPhase = planAligner.getNextTimedPhase(subscription, now, now);
final PhaseEvent nextPhaseEvent = (nextTimedPhase != null) ?
PhaseEventData.createNextPhaseEvent(nextTimedPhase.getPhase().getName(), subscription, now, nextTimedPhase.getStartPhase()) :
- null;
- if (nextPhaseEvent != null) {
- dao.createNextPhaseEvent(subscription.getId(), nextPhaseEvent, context);
- }
+ null;
+ if (nextPhaseEvent != null) {
+ dao.createNextPhaseEvent(subscription, nextPhaseEvent, context);
+ }
} catch (EntitlementError e) {
log.error(String.format("Failed to insert next phase for subscription %s", subscription.getId()), e);
}
}
private int onBasePlanEvent(final SubscriptionData baseSubscription, final ApiEvent event, final CallContext context) {
-
final DateTime now = clock.getUTCNow();
-
- final Product baseProduct = (baseSubscription.getState() == SubscriptionState.CANCELLED) ?
- null : baseSubscription.getCurrentPlan().getProduct();
+ final Product baseProduct = (baseSubscription.getState() == SubscriptionState.CANCELLED) ? null : baseSubscription.getCurrentPlan().getProduct();
final List<Subscription> subscriptions = dao.getSubscriptions(subscriptionFactory, baseSubscription.getBundleId());
-
final Map<UUID, EntitlementEvent> addOnCancellations = new HashMap<UUID, EntitlementEvent>();
-
- final Iterator<Subscription> it = subscriptions.iterator();
- while (it.hasNext()) {
- final SubscriptionData cur = (SubscriptionData) it.next();
+ final Map<UUID, SubscriptionData> addOnCancellationSubscriptions = new HashMap<UUID, SubscriptionData>();
+ for (final Subscription subscription : subscriptions) {
+ final SubscriptionData cur = (SubscriptionData) subscription;
if (cur.getState() == SubscriptionState.CANCELLED ||
cur.getCategory() != ProductCategory.ADD_ON) {
continue;
}
+
final Plan addonCurrentPlan = cur.getCurrentPlan();
if (baseProduct == null ||
addonUtils.isAddonIncluded(baseProduct, addonCurrentPlan) ||
@@ -246,23 +235,26 @@ public class Engine implements EventListener, EntitlementService {
// Perform AO cancellation using the effectiveDate of the BP
//
final EntitlementEvent cancelEvent = new ApiEventCancel(new ApiEventBuilder()
- .setSubscriptionId(cur.getId())
- .setActiveVersion(cur.getActiveVersion())
- .setProcessedDate(now)
- .setEffectiveDate(event.getEffectiveDate())
- .setRequestedDate(now)
- .setUserToken(context.getUserToken())
- .setFromDisk(true));
+ .setSubscriptionId(cur.getId())
+ .setActiveVersion(cur.getActiveVersion())
+ .setProcessedDate(now)
+ .setEffectiveDate(event.getEffectiveDate())
+ .setRequestedDate(now)
+ .setUserToken(context.getUserToken())
+ .setFromDisk(true));
addOnCancellations.put(cur.getId(), cancelEvent);
+ addOnCancellationSubscriptions.put(cur.getId(), cur);
}
}
+
final int addOnSize = addOnCancellations.size();
int cancelSeq = addOnSize - 1;
for (final UUID key : addOnCancellations.keySet()) {
- dao.cancelSubscription(key, addOnCancellations.get(key), context, cancelSeq);
+ dao.cancelSubscription(addOnCancellationSubscriptions.get(key), addOnCancellations.get(key), context, cancelSeq);
cancelSeq--;
}
+
return addOnSize;
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/AuditedEntitlementDao.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/AuditedEntitlementDao.java
index 38bf0ca..ab0cd11 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/AuditedEntitlementDao.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/AuditedEntitlementDao.java
@@ -17,7 +17,6 @@
package com.ning.billing.entitlement.engine.dao;
import javax.annotation.Nullable;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -41,6 +40,7 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
+import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.Plan;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.SubscriptionFactory;
@@ -50,6 +50,7 @@ import com.ning.billing.entitlement.api.migration.AccountMigrationData.Subscript
import com.ning.billing.entitlement.api.timeline.DefaultRepairEntitlementEvent;
import com.ning.billing.entitlement.api.timeline.RepairEntitlementEvent;
import com.ning.billing.entitlement.api.timeline.SubscriptionDataRepair;
+import com.ning.billing.entitlement.api.user.DefaultRequestedSubscriptionEvent;
import com.ning.billing.entitlement.api.user.DefaultSubscriptionFactory.SubscriptionBuilder;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
@@ -88,12 +89,11 @@ public class AuditedEntitlementDao implements EntitlementDao {
private final NotificationQueueService notificationQueueService;
private final AddonUtils addonUtils;
private final Bus eventBus;
+ private final CatalogService catalogService;
@Inject
- public AuditedEntitlementDao(final IDBI dbi, final Clock clock,
- final AddonUtils addonUtils, final NotificationQueueService notificationQueueService,
- final Bus eventBus) {
-
+ public AuditedEntitlementDao(final IDBI dbi, final Clock clock, final AddonUtils addonUtils,
+ final NotificationQueueService notificationQueueService, final Bus eventBus, final CatalogService catalogService) {
this.clock = clock;
this.subscriptionsDao = dbi.onDemand(SubscriptionSqlDao.class);
this.eventsDao = dbi.onDemand(EntitlementEventSqlDao.class);
@@ -101,6 +101,7 @@ public class AuditedEntitlementDao implements EntitlementDao {
this.notificationQueueService = notificationQueueService;
this.addonUtils = addonUtils;
this.eventBus = eventBus;
+ this.catalogService = catalogService;
}
@Override
@@ -109,8 +110,7 @@ public class AuditedEntitlementDao implements EntitlementDao {
}
@Override
- public List<SubscriptionBundle> getSubscriptionBundleForAccount(
- final UUID accountId) {
+ public List<SubscriptionBundle> getSubscriptionBundleForAccount(final UUID accountId) {
return bundlesDao.getBundleFromAccount(accountId.toString());
}
@@ -179,18 +179,17 @@ public class AuditedEntitlementDao implements EntitlementDao {
if (bundle == null) {
return Collections.emptyList();
}
+
return getSubscriptions(factory, bundle.getId());
}
@Override
public void updateChargedThroughDate(final SubscriptionData subscription, final CallContext context) {
-
final Date ctd = (subscription.getChargedThroughDate() != null) ? subscription.getChargedThroughDate().toDate() : null;
subscriptionsDao.inTransaction(new Transaction<Void, SubscriptionSqlDao>() {
@Override
- public Void inTransaction(final SubscriptionSqlDao transactionalDao,
- final TransactionStatus status) throws Exception {
+ public Void inTransaction(final SubscriptionSqlDao transactionalDao, final TransactionStatus status) throws Exception {
final String subscriptionId = subscription.getId().toString();
transactionalDao.updateChargedThroughDate(subscription.getId().toString(), ctd, context);
final Long subscriptionRecordId = transactionalDao.getRecordId(subscriptionId);
@@ -200,20 +199,22 @@ public class AuditedEntitlementDao implements EntitlementDao {
final BundleSqlDao bundleSqlDao = transactionalDao.become(BundleSqlDao.class);
final String bundleId = subscription.getBundleId().toString();
bundleSqlDao.updateBundleLastSysTime(bundleId, clock.getUTCNow().toDate());
- // SubscriptionBundle bundle = bundleSqlDao.getById(bundleId);
+
final Long recordId = bundleSqlDao.getRecordId(bundleId);
final EntityAudit bundleAudit = new EntityAudit(TableName.BUNDLES, recordId, ChangeType.UPDATE);
bundleSqlDao.insertAuditFromTransaction(bundleAudit, context);
+
return null;
}
});
}
@Override
- public void createNextPhaseEvent(final UUID subscriptionId, final EntitlementEvent nextPhase, final CallContext context) {
+ public void createNextPhaseEvent(final SubscriptionData subscription, final EntitlementEvent nextPhase, final CallContext context) {
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
@Override
public Void inTransaction(final EntitlementEventSqlDao transactional, final TransactionStatus status) throws Exception {
+ final UUID subscriptionId = subscription.getId();
cancelNextPhaseEventFromTransaction(subscriptionId, transactional, context);
transactional.insertEvent(nextPhase, context);
@@ -222,8 +223,12 @@ public class AuditedEntitlementDao implements EntitlementDao {
transactional.insertAuditFromTransaction(audit, context);
recordFutureNotificationFromTransaction(transactional,
- nextPhase.getEffectiveDate(),
- new EntitlementNotificationKey(nextPhase.getId()));
+ nextPhase.getEffectiveDate(),
+ new EntitlementNotificationKey(nextPhase.getId()));
+
+ // Notify the Bus of the requested change
+ notifyBusOfRequestedChange(transactional, subscription, nextPhase);
+
return null;
}
});
@@ -244,17 +249,19 @@ public class AuditedEntitlementDao implements EntitlementDao {
return subscriptionsDao.inTransaction(new Transaction<Map<UUID, List<EntitlementEvent>>, SubscriptionSqlDao>() {
@Override
public Map<UUID, List<EntitlementEvent>> inTransaction(final SubscriptionSqlDao transactional,
- final TransactionStatus status) throws Exception {
+ final TransactionStatus status) throws Exception {
final List<Subscription> subscriptions = transactional.getSubscriptionsFromBundleId(bundleId.toString());
if (subscriptions.size() == 0) {
return Collections.emptyMap();
}
+
final EntitlementEventSqlDao eventsDaoFromSameTransaction = transactional.become(EntitlementEventSqlDao.class);
final Map<UUID, List<EntitlementEvent>> result = new HashMap<UUID, List<EntitlementEvent>>();
for (final Subscription cur : subscriptions) {
final List<EntitlementEvent> events = eventsDaoFromSameTransaction.getEventsForSubscription(cur.getId().toString());
result.put(cur.getId(), events);
}
+
return result;
}
});
@@ -267,16 +274,12 @@ public class AuditedEntitlementDao implements EntitlementDao {
}
@Override
- public void createSubscription(final SubscriptionData subscription,
- final List<EntitlementEvent> initialEvents, final CallContext context) {
-
+ public void createSubscription(final SubscriptionData subscription, final List<EntitlementEvent> initialEvents, final CallContext context) {
subscriptionsDao.inTransaction(new Transaction<Void, SubscriptionSqlDao>() {
-
@Override
- public Void inTransaction(final SubscriptionSqlDao transactional,
- final TransactionStatus status) throws Exception {
-
+ public Void inTransaction(final SubscriptionSqlDao transactional, final TransactionStatus status) throws Exception {
transactional.insertSubscription(subscription, context);
+
final Long subscriptionRecordId = transactional.getRecordId(subscription.getId().toString());
final EntityAudit audit = new EntityAudit(TableName.SUBSCRIPTIONS, subscriptionRecordId, ChangeType.INSERT);
transactional.insertAuditFromTransaction(audit, context);
@@ -290,49 +293,55 @@ public class AuditedEntitlementDao implements EntitlementDao {
final Long recordId = eventsDaoFromSameTransaction.getRecordId(cur.getId().toString());
audits.add(new EntityAudit(TableName.SUBSCRIPTION_EVENTS, recordId, ChangeType.INSERT));
recordFutureNotificationFromTransaction(transactional,
- cur.getEffectiveDate(),
- new EntitlementNotificationKey(cur.getId()));
+ cur.getEffectiveDate(),
+ new EntitlementNotificationKey(cur.getId()));
}
eventsDaoFromSameTransaction.insertAuditFromTransaction(audits, context);
+
+ // Notify the Bus of the latest requested change, if needed
+ if (initialEvents.size() > 0) {
+ notifyBusOfRequestedChange(eventsDaoFromSameTransaction, subscription, initialEvents.get(initialEvents.size() - 1));
+ }
+
return null;
}
});
}
@Override
- public void recreateSubscription(final UUID subscriptionId,
- final List<EntitlementEvent> recreateEvents, final CallContext context) {
-
+ public void recreateSubscription(final SubscriptionData subscription, final List<EntitlementEvent> recreateEvents, final CallContext context) {
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
@Override
public Void inTransaction(final EntitlementEventSqlDao transactional,
- final TransactionStatus status) throws Exception {
-
+ final TransactionStatus status) throws Exception {
final List<EntityAudit> audits = new ArrayList<EntityAudit>();
for (final EntitlementEvent cur : recreateEvents) {
transactional.insertEvent(cur, context);
final Long recordId = transactional.getRecordId(cur.getId().toString());
audits.add(new EntityAudit(TableName.SUBSCRIPTION_EVENTS, recordId, ChangeType.INSERT));
recordFutureNotificationFromTransaction(transactional,
- cur.getEffectiveDate(),
- new EntitlementNotificationKey(cur.getId()));
+ cur.getEffectiveDate(),
+ new EntitlementNotificationKey(cur.getId()));
}
transactional.insertAuditFromTransaction(audits, context);
+
+ // Notify the Bus of the latest requested change
+ notifyBusOfRequestedChange(transactional, subscription, recreateEvents.get(recreateEvents.size() - 1));
+
return null;
}
});
}
@Override
- public void cancelSubscription(final UUID subscriptionId, final EntitlementEvent cancelEvent, final CallContext context, final int seqId) {
-
+ public void cancelSubscription(final SubscriptionData subscription, final EntitlementEvent cancelEvent, final CallContext context, final int seqId) {
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
@Override
- public Void inTransaction(final EntitlementEventSqlDao transactional,
- final TransactionStatus status) throws Exception {
+ public Void inTransaction(final EntitlementEventSqlDao transactional, final TransactionStatus status) throws Exception {
+ final UUID subscriptionId = subscription.getId();
cancelNextCancelEventFromTransaction(subscriptionId, transactional, context);
cancelNextChangeEventFromTransaction(subscriptionId, transactional, context);
cancelNextPhaseEventFromTransaction(subscriptionId, transactional, context);
@@ -344,22 +353,23 @@ public class AuditedEntitlementDao implements EntitlementDao {
transactional.insertAuditFromTransaction(audit, context);
recordFutureNotificationFromTransaction(transactional,
- cancelEvent.getEffectiveDate(),
- new EntitlementNotificationKey(cancelEvent.getId(), seqId));
+ cancelEvent.getEffectiveDate(),
+ new EntitlementNotificationKey(cancelEvent.getId(), seqId));
+
+ // Notify the Bus of the requested change
+ notifyBusOfRequestedChange(transactional, subscription, cancelEvent);
+
return null;
}
});
}
@Override
- public void uncancelSubscription(final UUID subscriptionId, final List<EntitlementEvent> uncancelEvents, final CallContext context) {
-
+ public void uncancelSubscription(final SubscriptionData subscription, final List<EntitlementEvent> uncancelEvents, final CallContext context) {
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
-
@Override
- public Void inTransaction(final EntitlementEventSqlDao transactional,
- final TransactionStatus status) throws Exception {
-
+ public Void inTransaction(final EntitlementEventSqlDao transactional, final TransactionStatus status) throws Exception {
+ final UUID subscriptionId = subscription.getId();
EntitlementEvent cancelledEvent = null;
final Date now = clock.getUTCNow().toDate();
final List<EntitlementEvent> events = transactional.getFutureActiveEventForSubscription(subscriptionId.toString(), now);
@@ -386,22 +396,27 @@ public class AuditedEntitlementDao implements EntitlementDao {
final Long recordId = transactional.getRecordId(cur.getId().toString());
eventAudits.add(new EntityAudit(TableName.SUBSCRIPTION_EVENTS, recordId, ChangeType.INSERT));
recordFutureNotificationFromTransaction(transactional,
- cur.getEffectiveDate(),
- new EntitlementNotificationKey(cur.getId()));
+ cur.getEffectiveDate(),
+ new EntitlementNotificationKey(cur.getId()));
}
transactional.insertAuditFromTransaction(eventAudits, context);
+
+ // Notify the Bus of the latest requested change
+ notifyBusOfRequestedChange(transactional, subscription, uncancelEvents.get(uncancelEvents.size() - 1));
}
+
return null;
}
});
}
@Override
- public void changePlan(final UUID subscriptionId, final List<EntitlementEvent> changeEvents, final CallContext context) {
+ public void changePlan(final SubscriptionData subscription, final List<EntitlementEvent> changeEvents, final CallContext context) {
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
@Override
public Void inTransaction(final EntitlementEventSqlDao transactional, final TransactionStatus status) throws Exception {
+ final UUID subscriptionId = subscription.getId();
cancelNextChangeEventFromTransaction(subscriptionId, transactional, context);
cancelNextPhaseEventFromTransaction(subscriptionId, transactional, context);
@@ -412,11 +427,16 @@ public class AuditedEntitlementDao implements EntitlementDao {
eventAudits.add(new EntityAudit(TableName.SUBSCRIPTION_EVENTS, recordId, ChangeType.INSERT));
recordFutureNotificationFromTransaction(transactional,
- cur.getEffectiveDate(),
- new EntitlementNotificationKey(cur.getId()));
+ cur.getEffectiveDate(),
+ new EntitlementNotificationKey(cur.getId()));
}
transactional.insertAuditFromTransaction(eventAudits, context);
+
+ // Notify the Bus of the latest requested change
+ final EntitlementEvent finalEvent = changeEvents.get(changeEvents.size() - 1);
+ notifyBusOfRequestedChange(transactional, subscription, finalEvent);
+
return null;
}
});
@@ -434,10 +454,8 @@ public class AuditedEntitlementDao implements EntitlementDao {
cancelFutureEventFromTransaction(subscriptionId, dao, EventType.API_USER, ApiEventType.CANCEL, context);
}
- private void cancelFutureEventFromTransaction(final UUID subscriptionId, final EntitlementEventSqlDao dao,
- final EventType type, @Nullable final ApiEventType apiType,
- final CallContext context) {
-
+ private void cancelFutureEventFromTransaction(final UUID subscriptionId, final EntitlementEventSqlDao dao, final EventType type,
+ @Nullable final ApiEventType apiType, final CallContext context) {
EntitlementEvent futureEvent = null;
final Date now = clock.getUTCNow().toDate();
final List<EntitlementEvent> events = dao.getFutureActiveEventForSubscription(subscriptionId.toString(), now);
@@ -445,9 +463,8 @@ public class AuditedEntitlementDao implements EntitlementDao {
if (cur.getType() == type &&
(apiType == null || apiType == ((ApiEvent) cur).getEventType())) {
if (futureEvent != null) {
- throw new EntitlementError(
- String.format("Found multiple future events for type %s for subscriptions %s",
- type, subscriptionId.toString()));
+ throw new EntitlementError(String.format("Found multiple future events for type %s for subscriptions %s",
+ type, subscriptionId.toString()));
}
futureEvent = cur;
}
@@ -466,6 +483,7 @@ public class AuditedEntitlementDao implements EntitlementDao {
if (input == null) {
return null;
}
+
final List<Subscription> bundleInput = new ArrayList<Subscription>();
if (input.getCategory() == ProductCategory.ADD_ON) {
final Subscription baseSubscription = getBaseSubscription(factory, input.getBundleId(), false);
@@ -474,19 +492,22 @@ public class AuditedEntitlementDao implements EntitlementDao {
} else {
bundleInput.add(input);
}
+
final List<Subscription> reloadedSubscriptions = buildBundleSubscriptions(factory, bundleInput);
for (final Subscription cur : reloadedSubscriptions) {
if (cur.getId().equals(input.getId())) {
return cur;
}
}
- throw new EntitlementError(String.format("Unexpected code path in buildSubscription"));
+
+ throw new EntitlementError("Unexpected code path in buildSubscription");
}
private List<Subscription> buildBundleSubscriptions(final SubscriptionFactory factory, final List<Subscription> input) {
if (input == null || input.size() == 0) {
return Collections.emptyList();
}
+
// Make sure BasePlan -- if exists-- is first
Collections.sort(input, new Comparator<Subscription>() {
@Override
@@ -504,67 +525,63 @@ public class AuditedEntitlementDao implements EntitlementDao {
EntitlementEvent futureBaseEvent = null;
final List<Subscription> result = new ArrayList<Subscription>(input.size());
for (final Subscription cur : input) {
-
final List<EntitlementEvent> events = eventsDao.getEventsForSubscription(cur.getId().toString());
Subscription reloaded = factory.createSubscription(new SubscriptionBuilder((SubscriptionData) cur), events);
switch (cur.getCategory()) {
- case BASE:
- final Collection<EntitlementEvent> futureApiEvents = Collections2.filter(events, new Predicate<EntitlementEvent>() {
- @Override
- public boolean apply(final EntitlementEvent input) {
- return (input.getEffectiveDate().isAfter(clock.getUTCNow()) &&
- ((input instanceof ApiEventCancel) || (input instanceof ApiEventChange)));
- }
- });
- futureBaseEvent = (futureApiEvents.size() == 0) ? null : futureApiEvents.iterator().next();
- break;
-
- case ADD_ON:
- final Plan targetAddOnPlan = reloaded.getCurrentPlan();
- final String baseProductName = (futureBaseEvent instanceof ApiEventChange) ?
- ((ApiEventChange) futureBaseEvent).getEventPlan() : null;
-
- final boolean createCancelEvent = (futureBaseEvent != null) &&
- ((futureBaseEvent instanceof ApiEventCancel) ||
- ((!addonUtils.isAddonAvailableFromPlanName(baseProductName, futureBaseEvent.getEffectiveDate(), targetAddOnPlan)) ||
- (addonUtils.isAddonIncludedFromPlanName(baseProductName, futureBaseEvent.getEffectiveDate(), targetAddOnPlan))));
-
- if (createCancelEvent) {
- final DateTime now = clock.getUTCNow();
- final EntitlementEvent addOnCancelEvent = new ApiEventCancel(new ApiEventBuilder()
- .setSubscriptionId(reloaded.getId())
- .setActiveVersion(((SubscriptionData) reloaded).getActiveVersion())
- .setProcessedDate(now)
- .setEffectiveDate(futureBaseEvent.getEffectiveDate())
- .setRequestedDate(now)
- // This event is only there to indicate the ADD_ON is future canceled, but it is not there
- // on disk until the base plan cancellation becomes effective
- .setFromDisk(false));
-
- events.add(addOnCancelEvent);
- // Finally reload subscription with full set of events
- reloaded = factory.createSubscription(new SubscriptionBuilder((SubscriptionData) cur), events);
+ case BASE:
+ final Collection<EntitlementEvent> futureApiEvents = Collections2.filter(events, new Predicate<EntitlementEvent>() {
+ @Override
+ public boolean apply(final EntitlementEvent input) {
+ return (input.getEffectiveDate().isAfter(clock.getUTCNow()) &&
+ ((input instanceof ApiEventCancel) || (input instanceof ApiEventChange)));
}
- break;
- default:
- break;
+ });
+ futureBaseEvent = (futureApiEvents.size() == 0) ? null : futureApiEvents.iterator().next();
+ break;
+
+ case ADD_ON:
+ final Plan targetAddOnPlan = reloaded.getCurrentPlan();
+ final String baseProductName = (futureBaseEvent instanceof ApiEventChange) ?
+ ((ApiEventChange) futureBaseEvent).getEventPlan() : null;
+
+ final boolean createCancelEvent = (futureBaseEvent != null) &&
+ ((futureBaseEvent instanceof ApiEventCancel) ||
+ ((!addonUtils.isAddonAvailableFromPlanName(baseProductName, futureBaseEvent.getEffectiveDate(), targetAddOnPlan)) ||
+ (addonUtils.isAddonIncludedFromPlanName(baseProductName, futureBaseEvent.getEffectiveDate(), targetAddOnPlan))));
+
+ if (createCancelEvent) {
+ final DateTime now = clock.getUTCNow();
+ final EntitlementEvent addOnCancelEvent = new ApiEventCancel(new ApiEventBuilder()
+ .setSubscriptionId(reloaded.getId())
+ .setActiveVersion(((SubscriptionData) reloaded).getActiveVersion())
+ .setProcessedDate(now)
+ .setEffectiveDate(futureBaseEvent.getEffectiveDate())
+ .setRequestedDate(now)
+ // This event is only there to indicate the ADD_ON is future canceled, but it is not there
+ // on disk until the base plan cancellation becomes effective
+ .setFromDisk(false));
+
+ events.add(addOnCancelEvent);
+ // Finally reload subscription with full set of events
+ reloaded = factory.createSubscription(new SubscriptionBuilder((SubscriptionData) cur), events);
+ }
+ break;
+ default:
+ break;
}
result.add(reloaded);
}
+
return result;
}
@Override
public void migrate(final UUID accountId, final AccountMigrationData accountData, final CallContext context) {
-
eventsDao.inTransaction(new Transaction<Void, EntitlementEventSqlDao>() {
-
@Override
- public Void inTransaction(final EntitlementEventSqlDao transactional,
- final TransactionStatus status) throws Exception {
-
+ public Void inTransaction(final EntitlementEventSqlDao transactional, final TransactionStatus status) throws Exception {
final SubscriptionSqlDao transSubDao = transactional.become(SubscriptionSqlDao.class);
final BundleSqlDao transBundleDao = transactional.become(BundleSqlDao.class);
@@ -576,7 +593,6 @@ public class AuditedEntitlementDao implements EntitlementDao {
final SubscriptionBundleData bundleData = curBundle.getData();
for (final SubscriptionMigrationData curSubscription : curBundle.getSubscriptions()) {
-
final SubscriptionData subData = curSubscription.getData();
for (final EntitlementEvent curEvent : curSubscription.getInitialEvents()) {
transactional.insertEvent(curEvent, context);
@@ -584,13 +600,18 @@ public class AuditedEntitlementDao implements EntitlementDao {
audits.add(new EntityAudit(TableName.SUBSCRIPTION_EVENTS, recordId, ChangeType.INSERT));
recordFutureNotificationFromTransaction(transactional,
- curEvent.getEffectiveDate(),
- new EntitlementNotificationKey(curEvent.getId()));
+ curEvent.getEffectiveDate(),
+ new EntitlementNotificationKey(curEvent.getId()));
}
transSubDao.insertSubscription(subData, context);
recordId = transSubDao.getRecordId(subData.getId().toString());
audits.add(new EntityAudit(TableName.SUBSCRIPTIONS, recordId, ChangeType.INSERT));
+
+ // Notify the Bus of the latest requested change
+ final EntitlementEvent finalEvent = curSubscription.getInitialEvents().get(curSubscription.getInitialEvents().size() - 1);
+ notifyBusOfRequestedChange(transactional, subData, finalEvent);
}
+
transBundleDao.insertBundle(bundleData, context);
recordId = transBundleDao.getRecordId(bundleData.getId().toString());
audits.add(new EntityAudit(TableName.BUNDLES, recordId, ChangeType.INSERT));
@@ -604,13 +625,11 @@ public class AuditedEntitlementDao implements EntitlementDao {
});
}
+ @Override
public void repair(final UUID accountId, final UUID bundleId, final List<SubscriptionDataRepair> inRepair, final CallContext context) {
subscriptionsDao.inTransaction(new Transaction<Void, SubscriptionSqlDao>() {
-
@Override
- public Void inTransaction(final SubscriptionSqlDao transactional,
- final TransactionStatus status) throws Exception {
-
+ public Void inTransaction(final SubscriptionSqlDao transactional, final TransactionStatus status) throws Exception {
final EntitlementEventSqlDao transEventDao = transactional.become(EntitlementEventSqlDao.class);
for (final SubscriptionDataRepair cur : inRepair) {
transactional.updateForRepair(cur.getId().toString(), cur.getActiveVersion(), cur.getStartDate().toDate(), cur.getBundleStartDate().toDate(), context);
@@ -621,17 +640,20 @@ public class AuditedEntitlementDao implements EntitlementDao {
transEventDao.insertEvent(event, context);
if (event.getEffectiveDate().isAfter(clock.getUTCNow())) {
recordFutureNotificationFromTransaction(transactional,
- event.getEffectiveDate(),
- new EntitlementNotificationKey(event.getId()));
+ event.getEffectiveDate(),
+ new EntitlementNotificationKey(event.getId()));
}
}
}
+
try {
+ // Note: we don't send a requested change event here, but a repair event
final RepairEntitlementEvent busEvent = new DefaultRepairEntitlementEvent(context.getUserToken(), accountId, bundleId, clock.getUTCNow());
eventBus.postFromTransaction(busEvent, transactional);
} catch (EventBusException e) {
log.warn("Failed to post repair entitlement event for bundle " + bundleId, e);
}
+
return null;
}
});
@@ -644,18 +666,27 @@ public class AuditedEntitlementDao implements EntitlementDao {
return rebuildSubscription ? buildSubscription(factory, cur) : cur;
}
}
+
return null;
}
private void recordFutureNotificationFromTransaction(final Transmogrifier transactionalDao, final DateTime effectiveDate, final NotificationKey notificationKey) {
try {
final NotificationQueue subscriptionEventQueue = notificationQueueService.getNotificationQueue(Engine.ENTITLEMENT_SERVICE_NAME,
- Engine.NOTIFICATION_QUEUE_NAME);
- subscriptionEventQueue.recordFutureNotificationFromTransaction(transactionalDao, effectiveDate, notificationKey);
+ Engine.NOTIFICATION_QUEUE_NAME);
+ subscriptionEventQueue.recordFutureNotificationFromTransaction(transactionalDao, effectiveDate, null, notificationKey);
} catch (NoSuchNotificationQueue e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
+
+ private void notifyBusOfRequestedChange(final EntitlementEventSqlDao transactional, final SubscriptionData subscription, final EntitlementEvent nextEvent) {
+ try {
+ eventBus.postFromTransaction(new DefaultRequestedSubscriptionEvent(subscription, nextEvent), transactional);
+ } catch (EventBusException e) {
+ log.warn("Failed to post requested change event for subscription " + subscription.getId(), e);
+ }
+ }
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/BundleSqlDao.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/BundleSqlDao.java
index 3530c28..b80a18f 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/BundleSqlDao.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/BundleSqlDao.java
@@ -29,7 +29,7 @@ import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
-import org.skife.jdbi.v2.sqlobject.customizers.Mapper;
+import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
import org.skife.jdbi.v2.sqlobject.mixins.CloseMe;
import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
@@ -45,11 +45,10 @@ import com.ning.billing.util.dao.BinderBase;
import com.ning.billing.util.dao.MapperBase;
import com.ning.billing.util.entity.dao.EntitySqlDao;
-
@ExternalizedSqlViaStringTemplate3()
+@RegisterMapper(BundleSqlDao.ISubscriptionBundleSqlMapper.class)
public interface BundleSqlDao extends Transactional<BundleSqlDao>, EntitySqlDao<SubscriptionBundle>,
- AuditSqlDao, CloseMe, Transmogrifier {
-
+ AuditSqlDao, CloseMe, Transmogrifier {
@SqlUpdate
public void insertBundle(@Bind(binder = SubscriptionBundleBinder.class) SubscriptionBundleData bundle,
@CallContextBinder final CallContext context);
@@ -58,22 +57,18 @@ public interface BundleSqlDao extends Transactional<BundleSqlDao>, EntitySqlDao<
public void updateBundleLastSysTime(@Bind("id") String id, @Bind("lastSysUpdateDate") Date lastSysUpdate);
@SqlQuery
- @Mapper(ISubscriptionBundleSqlMapper.class)
public SubscriptionBundle getBundleFromId(@Bind("id") String id);
@SqlQuery
- @Mapper(ISubscriptionBundleSqlMapper.class)
public SubscriptionBundle getBundleFromKey(@Bind("externalKey") String externalKey);
@SqlQuery
- @Mapper(ISubscriptionBundleSqlMapper.class)
public List<SubscriptionBundle> getBundleFromAccount(@Bind("accountId") String accountId);
public static class SubscriptionBundleBinder extends BinderBase implements Binder<Bind, SubscriptionBundleData> {
@Override
public void bind(@SuppressWarnings("rawtypes") final SQLStatement stmt, final Bind bind, final SubscriptionBundleData bundle) {
stmt.bind("id", bundle.getId().toString());
- stmt.bind("startDate", getDate(bundle.getStartDate()));
stmt.bind("externalKey", bundle.getKey());
stmt.bind("accountId", bundle.getAccountId().toString());
stmt.bind("lastSysUpdateDate", getDate(bundle.getLastSysUpdateTime()));
@@ -81,17 +76,13 @@ public interface BundleSqlDao extends Transactional<BundleSqlDao>, EntitySqlDao<
}
public static class ISubscriptionBundleSqlMapper extends MapperBase implements ResultSetMapper<SubscriptionBundle> {
-
@Override
- public SubscriptionBundle map(final int arg, final ResultSet r,
- final StatementContext ctx) throws SQLException {
+ public SubscriptionBundle map(final int arg, final ResultSet r, final StatementContext ctx) throws SQLException {
final UUID id = UUID.fromString(r.getString("id"));
final String key = r.getString("external_key");
final UUID accountId = UUID.fromString(r.getString("account_id"));
- final DateTime startDate = getDate(r, "start_date");
final DateTime lastSysUpdateDate = getDate(r, "last_sys_update_date");
- final SubscriptionBundleData bundle = new SubscriptionBundleData(id, key, accountId, startDate, lastSysUpdateDate);
- return bundle;
+ return new SubscriptionBundleData(id, key, accountId, lastSysUpdateDate);
}
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/EntitlementDao.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/EntitlementDao.java
index 710391b..b85a47a 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/EntitlementDao.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/EntitlementDao.java
@@ -56,7 +56,7 @@ public interface EntitlementDao {
public void updateChargedThroughDate(final SubscriptionData subscription, final CallContext context);
// Event apis
- public void createNextPhaseEvent(final UUID subscriptionId, final EntitlementEvent nextPhase, final CallContext context);
+ public void createNextPhaseEvent(final SubscriptionData subscription, final EntitlementEvent nextPhase, final CallContext context);
public EntitlementEvent getEventById(final UUID eventId);
@@ -69,13 +69,13 @@ public interface EntitlementDao {
// Subscription creation, cancellation, changePlan apis
public void createSubscription(final SubscriptionData subscription, final List<EntitlementEvent> initialEvents, final CallContext context);
- public void recreateSubscription(final UUID subscriptionId, final List<EntitlementEvent> recreateEvents, final CallContext context);
+ public void recreateSubscription(final SubscriptionData subscription, final List<EntitlementEvent> recreateEvents, final CallContext context);
- public void cancelSubscription(final UUID subscriptionId, final EntitlementEvent cancelEvent, final CallContext context, final int cancelSeq);
+ public void cancelSubscription(final SubscriptionData subscription, final EntitlementEvent cancelEvent, final CallContext context, final int cancelSeq);
- public void uncancelSubscription(final UUID subscriptionId, final List<EntitlementEvent> uncancelEvents, final CallContext context);
+ public void uncancelSubscription(final SubscriptionData subscription, final List<EntitlementEvent> uncancelEvents, final CallContext context);
- public void changePlan(final UUID subscriptionId, final List<EntitlementEvent> changeEvents, final CallContext context);
+ public void changePlan(final SubscriptionData subscription, final List<EntitlementEvent> changeEvents, final CallContext context);
public void migrate(final UUID accountId, final AccountMigrationData data, final CallContext context);
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/RepairEntitlementDao.java b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/RepairEntitlementDao.java
index d6f3fe9..ed9cf13 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/RepairEntitlementDao.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/engine/dao/RepairEntitlementDao.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.engine.dao;
import java.util.Collections;
@@ -38,11 +39,11 @@ import com.ning.billing.entitlement.exceptions.EntitlementError;
import com.ning.billing.util.callcontext.CallContext;
public class RepairEntitlementDao implements EntitlementDao, RepairEntitlementLifecycleDao {
+ private static final String NOT_IMPLEMENTED = "Not implemented";
private final ThreadLocal<Map<UUID, SubscriptionRepairEvent>> preThreadsInRepairSubscriptions = new ThreadLocal<Map<UUID, SubscriptionRepairEvent>>();
private static final class SubscriptionRepairEvent {
-
private final Set<EntitlementEvent> events;
public SubscriptionRepairEvent(final List<EntitlementEvent> initialEvents) {
@@ -91,14 +92,15 @@ public class RepairEntitlementDao implements EntitlementDao, RepairEntitlementLi
}
@Override
- public void recreateSubscription(final UUID subscriptionId,
+ public void recreateSubscription(final SubscriptionData subscription,
final List<EntitlementEvent> recreateEvents, final CallContext context) {
- addEvents(subscriptionId, recreateEvents);
+ addEvents(subscription.getId(), recreateEvents);
}
@Override
- public void cancelSubscription(final UUID subscriptionId,
+ public void cancelSubscription(final SubscriptionData subscription,
final EntitlementEvent cancelEvent, final CallContext context, final int cancelSeq) {
+ final UUID subscriptionId = subscription.getId();
final long activeVersion = cancelEvent.getActiveVersion();
addEvents(subscriptionId, Collections.singletonList(cancelEvent));
final SubscriptionRepairEvent target = getRepairSubscriptionEvents(subscriptionId);
@@ -112,11 +114,10 @@ public class RepairEntitlementDao implements EntitlementDao, RepairEntitlementLi
}
}
-
@Override
- public void changePlan(final UUID subscriptionId,
+ public void changePlan(final SubscriptionData subscription,
final List<EntitlementEvent> changeEvents, final CallContext context) {
- addEvents(subscriptionId, changeEvents);
+ addEvents(subscription.getId(), changeEvents);
}
@Override
@@ -136,108 +137,104 @@ public class RepairEntitlementDao implements EntitlementDao, RepairEntitlementLi
map.clear();
}
-
private void addEvents(final UUID subscriptionId, final List<EntitlementEvent> events) {
final SubscriptionRepairEvent target = getRepairSubscriptionEvents(subscriptionId);
target.addEvents(events);
}
-
@Override
- public void uncancelSubscription(final UUID subscriptionId,
+ public void uncancelSubscription(final SubscriptionData subscription,
final List<EntitlementEvent> uncancelEvents, final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public List<SubscriptionBundle> getSubscriptionBundleForAccount(final UUID accountId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public SubscriptionBundle getSubscriptionBundleFromKey(final String bundleKey) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public SubscriptionBundle getSubscriptionBundleFromId(final UUID bundleId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public SubscriptionBundle createSubscriptionBundle(
final SubscriptionBundleData bundle, final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public Subscription getSubscriptionFromId(final SubscriptionFactory factory,
final UUID subscriptionId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public UUID getAccountIdFromSubscriptionId(final UUID subscriptionId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public Subscription getBaseSubscription(final SubscriptionFactory factory,
final UUID bundleId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public List<Subscription> getSubscriptions(final SubscriptionFactory factory,
final UUID bundleId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public List<Subscription> getSubscriptionsForKey(
final SubscriptionFactory factory, final String bundleKey) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public void updateChargedThroughDate(final SubscriptionData subscription,
final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
- public void createNextPhaseEvent(final UUID subscriptionId,
+ public void createNextPhaseEvent(final SubscriptionData subscription,
final EntitlementEvent nextPhase, final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public EntitlementEvent getEventById(final UUID eventId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public Map<UUID, List<EntitlementEvent>> getEventsForBundle(final UUID bundleId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
-
@Override
public List<EntitlementEvent> getPendingEventsForSubscription(
final UUID subscriptionId) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
-
@Override
public void migrate(final UUID accountId, final AccountMigrationData data,
final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
@Override
public void repair(final UUID accountId, final UUID bundleId, final List<SubscriptionDataRepair> inRepair,
final CallContext context) {
- throw new EntitlementError("Not implemented");
+ throw new EntitlementError(NOT_IMPLEMENTED);
}
}
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/events/EventBase.java b/entitlement/src/main/java/com/ning/billing/entitlement/events/EventBase.java
index ed1a0db..92b4526 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/events/EventBase.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/events/EventBase.java
@@ -23,7 +23,6 @@ import org.joda.time.DateTime;
import com.ning.billing.entitlement.events.user.ApiEvent;
public abstract class EventBase implements EntitlementEvent {
-
private final long totalOrdering;
private final UUID uuid;
private final UUID subscriptionId;
@@ -41,30 +40,9 @@ public abstract class EventBase implements EntitlementEvent {
this.requestedDate = builder.getRequestedDate();
this.effectiveDate = builder.getEffectiveDate();
this.processedDate = builder.getProcessedDate();
-
this.activeVersion = builder.getActiveVersion();
this.isActive = builder.isActive();
}
-/*
- public EventBase(UUID subscriptionId, DateTime requestedDate,
- DateTime effectiveDate, DateTime processedDate,
- long activeVersion, boolean isActive) {
- this(UUID.randomUUID(), subscriptionId, requestedDate, effectiveDate, processedDate, activeVersion, isActive);
- }
-
- public EventBase(UUID id, UUID subscriptionId, DateTime requestedDate,
- DateTime effectiveDate, DateTime processedDate,
- long activeVersion, boolean isActive) {
- this.uuid = id;
- this.subscriptionId = subscriptionId;
- this.requestedDate = requestedDate;
- this.effectiveDate = effectiveDate;
- this.processedDate = processedDate;
-
- this.activeVersion = activeVersion;
- this.isActive = isActive;
- }
-*/
@Override
public DateTime getRequestedDate() {
@@ -91,7 +69,6 @@ public abstract class EventBase implements EntitlementEvent {
return totalOrdering;
}
-
@Override
public UUID getId() {
return uuid;
@@ -122,7 +99,6 @@ public abstract class EventBase implements EntitlementEvent {
this.isActive = true;
}
-
//
// Really used for unit tests only as the sql implementation relies on date first and then event insertion
//
@@ -135,7 +111,7 @@ public abstract class EventBase implements EntitlementEvent {
@Override
public int compareTo(final EntitlementEvent other) {
if (other == null) {
- throw new NullPointerException("IEvent is compared to a null instance");
+ throw new IllegalArgumentException("IEvent is compared to a null instance");
}
if (effectiveDate.isBefore(other.getEffectiveDate())) {
@@ -159,7 +135,6 @@ public abstract class EventBase implements EntitlementEvent {
}
}
-
@Override
public boolean equals(final Object other) {
if (!(other instanceof EntitlementEvent)) {
@@ -170,6 +145,4 @@ public abstract class EventBase implements EntitlementEvent {
@Override
public abstract EventType getType();
-
-
}
diff --git a/entitlement/src/main/resources/com/ning/billing/entitlement/ddl.sql b/entitlement/src/main/resources/com/ning/billing/entitlement/ddl.sql
index ae45518..66628e8 100644
--- a/entitlement/src/main/resources/com/ning/billing/entitlement/ddl.sql
+++ b/entitlement/src/main/resources/com/ning/billing/entitlement/ddl.sql
@@ -51,7 +51,6 @@ DROP TABLE IF EXISTS bundles;
CREATE TABLE bundles (
record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
id char(36) NOT NULL,
- start_date datetime, /*NOT NULL*/
external_key varchar(64) NOT NULL,
account_id char(36) NOT NULL,
last_sys_update_date datetime,
diff --git a/entitlement/src/main/resources/com/ning/billing/entitlement/engine/dao/BundleSqlDao.sql.stg b/entitlement/src/main/resources/com/ning/billing/entitlement/engine/dao/BundleSqlDao.sql.stg
index 367330f..1ecf151 100644
--- a/entitlement/src/main/resources/com/ning/billing/entitlement/engine/dao/BundleSqlDao.sql.stg
+++ b/entitlement/src/main/resources/com/ning/billing/entitlement/engine/dao/BundleSqlDao.sql.stg
@@ -2,7 +2,6 @@ group BundleSqlDao;
fields(prefix) ::= <<
<prefix>id,
- <prefix>start_date,
<prefix>external_key,
<prefix>account_id,
<prefix>last_sys_update_date
@@ -10,7 +9,7 @@ fields(prefix) ::= <<
insertBundle() ::= <<
insert into bundles (<fields()>)
- values (:id, :startDate, :externalKey, :accountId, :lastSysUpdateDate);
+ values (:id, :externalKey, :accountId, :lastSysUpdateDate);
>>
updateBundleLastSysTime() ::= <<
@@ -65,4 +64,4 @@ auditFields(prefix) ::= <<
insertAuditFromTransaction() ::= <<
INSERT INTO audit_log(<auditFields()>)
VALUES(:tableName, :recordId, :changeType, :createdDate, :userName, :reasonCode, :comment, :userToken);
->>
\ No newline at end of file
+>>
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestPlanAligner.java b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestPlanAligner.java
new file mode 100644
index 0000000..65df594
--- /dev/null
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestPlanAligner.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2010-2012 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.entitlement.alignment;
+
+import java.util.List;
+import java.util.Map;
+
+import org.joda.time.DateTime;
+import org.skife.config.ConfigSource;
+import org.skife.config.ConfigurationObjectFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.ning.billing.KillbillTestSuite;
+import com.ning.billing.catalog.DefaultCatalogService;
+import com.ning.billing.catalog.api.CatalogApiException;
+import com.ning.billing.catalog.api.PhaseType;
+import com.ning.billing.catalog.api.Plan;
+import com.ning.billing.catalog.api.PriceListSet;
+import com.ning.billing.catalog.io.VersionedCatalogLoader;
+import com.ning.billing.config.CatalogConfig;
+import com.ning.billing.entitlement.api.user.DefaultSubscriptionFactory;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
+import com.ning.billing.entitlement.api.user.SubscriptionData;
+import com.ning.billing.entitlement.events.EntitlementEvent;
+import com.ning.billing.entitlement.events.user.ApiEventBase;
+import com.ning.billing.entitlement.events.user.ApiEventBuilder;
+import com.ning.billing.entitlement.events.user.ApiEventType;
+import com.ning.billing.entitlement.exceptions.EntitlementError;
+import com.ning.billing.util.clock.DefaultClock;
+
+public class TestPlanAligner extends KillbillTestSuite {
+ private static final String priceList = PriceListSet.DEFAULT_PRICELIST_NAME;
+
+ private final DefaultClock clock = new DefaultClock();
+
+ private DefaultCatalogService catalogService;
+ private PlanAligner planAligner;
+
+ @BeforeClass(groups = "fast")
+ public void setUp() throws Exception {
+ final VersionedCatalogLoader versionedCatalogLoader = new VersionedCatalogLoader(clock);
+ final CatalogConfig config = new ConfigurationObjectFactory(new ConfigSource() {
+ final Map<String, String> properties = ImmutableMap.<String, String>of("killbill.catalog.uri", "file:src/test/resources/testInput.xml");
+
+ @Override
+ public String getString(final String propertyName) {
+ return properties.get(propertyName);
+ }
+ }).build(CatalogConfig.class);
+
+ catalogService = new DefaultCatalogService(config, versionedCatalogLoader);
+ planAligner = new PlanAligner(catalogService);
+
+ catalogService.loadCatalog();
+ }
+
+ @Test(groups = "fast")
+ public void testCreationBundleAlignment() throws Exception {
+ final String productName = "pistol-monthly";
+ final PhaseType initialPhase = PhaseType.TRIAL;
+ final SubscriptionData subscriptionData = createSubscriptionStartedInThePast(productName, initialPhase);
+
+ // Make the creation effective now, after the bundle and the subscription started
+ final DateTime effectiveDate = clock.getUTCNow();
+ final TimedPhase[] phases = getTimedPhasesOnCreate(productName, initialPhase, subscriptionData, effectiveDate);
+
+ // All plans but Laser-Scope are START_OF_BUNDLE aligned on creation
+ Assert.assertEquals(phases[0].getStartPhase(), subscriptionData.getBundleStartDate());
+ Assert.assertEquals(phases[1].getStartPhase(), subscriptionData.getBundleStartDate().plusDays(30));
+
+ // Verify the next phase via the other API
+ final TimedPhase nextTimePhase = planAligner.getNextTimedPhase(subscriptionData, effectiveDate, effectiveDate);
+ Assert.assertEquals(nextTimePhase.getStartPhase(), subscriptionData.getBundleStartDate().plusDays(30));
+
+ // Now look at the past, before the bundle started
+ final DateTime effectiveDateInThePast = subscriptionData.getBundleStartDate().minusHours(10);
+ final TimedPhase[] phasesInThePast = getTimedPhasesOnCreate(productName, initialPhase, subscriptionData, effectiveDateInThePast);
+ Assert.assertNull(phasesInThePast[0]);
+ Assert.assertEquals(phasesInThePast[1].getStartPhase(), subscriptionData.getBundleStartDate());
+
+ // Verify the next phase via the other API
+ try {
+ planAligner.getNextTimedPhase(subscriptionData, effectiveDateInThePast, effectiveDateInThePast);
+ Assert.fail("Can't use getNextTimedPhase(): the effective date is before the initial plan");
+ } catch (EntitlementError e) {
+ Assert.assertTrue(true);
+ }
+
+ // Try a change plan now (simulate an IMMEDIATE policy)
+ final String newProductName = "shotgun-monthly";
+ final DateTime effectiveChangeDate = clock.getUTCNow();
+ changeSubscription(effectiveChangeDate, subscriptionData, productName, newProductName, initialPhase);
+
+ // All non rescue plans are START_OF_SUBSCRIPTION aligned on change
+ final TimedPhase newPhase = getNextTimedPhaseOnChange(subscriptionData, newProductName, effectiveChangeDate);
+ Assert.assertEquals(newPhase.getStartPhase(), subscriptionData.getStartDate().plusDays(30),
+ String.format("Start phase: %s, but bundle start date: %s and subscription start date: %s",
+ newPhase.getStartPhase(), subscriptionData.getBundleStartDate(), subscriptionData.getStartDate()));
+ }
+
+ @Test(groups = "fast")
+ public void testCreationSubscriptionAlignment() throws Exception {
+ final String productName = "laser-scope-monthly";
+ final PhaseType initialPhase = PhaseType.DISCOUNT;
+ final SubscriptionData subscriptionData = createSubscriptionStartedInThePast(productName, initialPhase);
+
+ // Look now, after the bundle and the subscription started
+ final DateTime effectiveDate = clock.getUTCNow();
+ final TimedPhase[] phases = getTimedPhasesOnCreate(productName, initialPhase, subscriptionData, effectiveDate);
+
+ // Laser-Scope is START_OF_SUBSCRIPTION aligned on creation
+ Assert.assertEquals(phases[0].getStartPhase(), subscriptionData.getStartDate());
+ Assert.assertEquals(phases[1].getStartPhase(), subscriptionData.getStartDate().plusMonths(1));
+
+ // Verify the next phase via the other API
+ final TimedPhase nextTimePhase = planAligner.getNextTimedPhase(subscriptionData, effectiveDate, effectiveDate);
+ Assert.assertEquals(nextTimePhase.getStartPhase(), subscriptionData.getStartDate().plusMonths(1));
+
+ // Now look at the past, before the subscription started
+ final DateTime effectiveDateInThePast = subscriptionData.getStartDate().minusHours(10);
+ final TimedPhase[] phasesInThePast = getTimedPhasesOnCreate(productName, initialPhase, subscriptionData, effectiveDateInThePast);
+ Assert.assertNull(phasesInThePast[0]);
+ Assert.assertEquals(phasesInThePast[1].getStartPhase(), subscriptionData.getStartDate());
+
+ // Verify the next phase via the other API
+ try {
+ planAligner.getNextTimedPhase(subscriptionData, effectiveDateInThePast, effectiveDateInThePast);
+ Assert.fail("Can't use getNextTimedPhase(): the effective date is before the initial plan");
+ } catch (EntitlementError e) {
+ Assert.assertTrue(true);
+ }
+
+ // Try a change plan (simulate END_OF_TERM policy)
+ final String newProductName = "telescopic-scope-monthly";
+ final DateTime effectiveChangeDate = subscriptionData.getStartDate().plusMonths(1);
+ changeSubscription(effectiveChangeDate, subscriptionData, productName, newProductName, initialPhase);
+
+ // All non rescue plans are START_OF_SUBSCRIPTION aligned on change. Since we're END_OF_TERM here, we'll
+ // never see the discount phase of telescopic-scope-monthly and jump right into evergreen.
+ // But in this test, since we didn't create the future change event from discount to evergreen (see changeSubscription,
+ // the subscription has only two transitions), we'll see null
+ final TimedPhase newPhase = getNextTimedPhaseOnChange(subscriptionData, newProductName, effectiveChangeDate);
+ Assert.assertNull(newPhase);
+ }
+
+ private SubscriptionData createSubscriptionStartedInThePast(final String productName, final PhaseType phaseType) {
+ final DefaultSubscriptionFactory.SubscriptionBuilder builder = new DefaultSubscriptionFactory.SubscriptionBuilder();
+ builder.setBundleStartDate(clock.getUTCNow().minusHours(10));
+ // Make sure to set the dates apart
+ builder.setStartDate(new DateTime(builder.getBundleStartDate().plusHours(5)));
+
+ // Create the transitions
+ final SubscriptionData subscriptionData = new SubscriptionData(builder, null, clock);
+ final EntitlementEvent event = createEntitlementEvent(builder.getStartDate(),
+ productName,
+ phaseType,
+ ApiEventType.CREATE,
+ subscriptionData.getActiveVersion());
+ subscriptionData.rebuildTransitions(ImmutableList.<EntitlementEvent>of(event), catalogService.getFullCatalog());
+
+ Assert.assertEquals(subscriptionData.getAllTransitions().size(), 1);
+ Assert.assertNull(subscriptionData.getAllTransitions().get(0).getPreviousPhase());
+ Assert.assertNotNull(subscriptionData.getAllTransitions().get(0).getNextPhase());
+
+ return subscriptionData;
+ }
+
+ private void changeSubscription(final DateTime effectiveChangeDate,
+ final SubscriptionData subscriptionData,
+ final String previousProductName,
+ final String newProductName,
+ final PhaseType commonPhaseType) {
+ final EntitlementEvent previousEvent = createEntitlementEvent(subscriptionData.getStartDate(),
+ previousProductName,
+ commonPhaseType,
+ ApiEventType.CREATE,
+ subscriptionData.getActiveVersion());
+ final EntitlementEvent event = createEntitlementEvent(effectiveChangeDate,
+ newProductName,
+ commonPhaseType,
+ ApiEventType.CHANGE,
+ subscriptionData.getActiveVersion());
+
+ subscriptionData.rebuildTransitions(ImmutableList.<EntitlementEvent>of(previousEvent, event), catalogService.getFullCatalog());
+
+ final List<EffectiveSubscriptionEvent> newTransitions = subscriptionData.getAllTransitions();
+ Assert.assertEquals(newTransitions.size(), 2);
+ Assert.assertNull(newTransitions.get(0).getPreviousPhase());
+ Assert.assertEquals(newTransitions.get(0).getNextPhase(), newTransitions.get(1).getPreviousPhase());
+ Assert.assertNotNull(newTransitions.get(1).getNextPhase());
+ }
+
+ private EntitlementEvent createEntitlementEvent(final DateTime effectiveDate,
+ final String productName,
+ final PhaseType phaseType,
+ final ApiEventType apiEventType,
+ final long activeVersion) {
+ final ApiEventBuilder eventBuilder = new ApiEventBuilder();
+ eventBuilder.setEffectiveDate(effectiveDate);
+ eventBuilder.setEventPlan(productName);
+ eventBuilder.setEventPlanPhase(productName + "-" + phaseType.toString().toLowerCase());
+ eventBuilder.setEventPriceList(priceList);
+
+ // We don't really use the following but the code path requires it
+ eventBuilder.setRequestedDate(effectiveDate);
+ eventBuilder.setFromDisk(true);
+ eventBuilder.setActiveVersion(activeVersion);
+
+ return new ApiEventBase(eventBuilder.setEventType(apiEventType));
+ }
+
+ private TimedPhase getNextTimedPhaseOnChange(final SubscriptionData subscriptionData,
+ final String newProductName,
+ final DateTime effectiveChangeDate) throws CatalogApiException, EntitlementUserApiException {
+ // The date is used for different catalog versions - we don't care here
+ final Plan newPlan = catalogService.getFullCatalog().findPlan(newProductName, clock.getUTCNow());
+
+ return planAligner.getNextTimedPhaseOnChange(subscriptionData, newPlan, priceList, effectiveChangeDate, effectiveChangeDate);
+ }
+
+ private TimedPhase[] getTimedPhasesOnCreate(final String productName,
+ final PhaseType initialPhase,
+ final SubscriptionData subscriptionData,
+ final DateTime effectiveDate) throws CatalogApiException, EntitlementUserApiException {
+ // The date is used for different catalog versions - we don't care here
+ final Plan plan = catalogService.getFullCatalog().findPlan(productName, clock.getUTCNow());
+
+ // Same here for the requested date
+ final TimedPhase[] phases = planAligner.getCurrentAndNextTimedPhaseOnCreate(subscriptionData, plan, initialPhase, priceList, clock.getUTCNow(), effectiveDate);
+ Assert.assertEquals(phases.length, 2);
+
+ return phases;
+ }
+}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedMigration.java b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedMigration.java
new file mode 100644
index 0000000..6be543d
--- /dev/null
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedMigration.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2010-2012 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.entitlement.alignment;
+
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.ning.billing.KillbillTestSuite;
+import com.ning.billing.catalog.api.Plan;
+import com.ning.billing.catalog.api.PlanPhase;
+import com.ning.billing.entitlement.events.EntitlementEvent;
+import com.ning.billing.entitlement.events.user.ApiEventType;
+
+public class TestTimedMigration extends KillbillTestSuite {
+ @Test(groups = "fast")
+ public void testConstructor() throws Exception {
+ final DateTime eventTime = new DateTime(DateTimeZone.UTC);
+ final EntitlementEvent.EventType eventType = EntitlementEvent.EventType.API_USER;
+ final ApiEventType apiEventType = ApiEventType.CREATE;
+ final Plan plan = Mockito.mock(Plan.class);
+ final PlanPhase phase = Mockito.mock(PlanPhase.class);
+ final String priceList = UUID.randomUUID().toString();
+ final TimedMigration timedMigration = new TimedMigration(eventTime, eventType, apiEventType, plan, phase, priceList);
+ final TimedMigration otherTimedMigration = new TimedMigration(eventTime, eventType, apiEventType, plan, phase, priceList);
+
+ Assert.assertEquals(otherTimedMigration, timedMigration);
+ Assert.assertEquals(timedMigration.getEventTime(), eventTime);
+ Assert.assertEquals(timedMigration.getEventType(), eventType);
+ Assert.assertEquals(timedMigration.getApiEventType(), apiEventType);
+ Assert.assertEquals(timedMigration.getPlan(), plan);
+ Assert.assertEquals(timedMigration.getPhase(), phase);
+ Assert.assertEquals(timedMigration.getPriceList(), priceList);
+ }
+}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedPhase.java b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedPhase.java
new file mode 100644
index 0000000..c75b6c2
--- /dev/null
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/alignment/TestTimedPhase.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2010-2012 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.entitlement.alignment;
+
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.ning.billing.KillbillTestSuite;
+import com.ning.billing.catalog.api.PlanPhase;
+
+public class TestTimedPhase extends KillbillTestSuite {
+ @Test(groups = "fast")
+ public void testConstructor() throws Exception {
+ final PlanPhase planPhase = Mockito.mock(PlanPhase.class);
+ final DateTime startPhase = new DateTime(DateTimeZone.UTC);
+ final TimedPhase timedPhase = new TimedPhase(planPhase, startPhase);
+ final TimedPhase otherTimedPhase = new TimedPhase(planPhase, startPhase);
+
+ Assert.assertEquals(otherTimedPhase, timedPhase);
+ Assert.assertEquals(timedPhase.getPhase(), planPhase);
+ Assert.assertEquals(timedPhase.getStartPhase(), startPhase);
+ }
+}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigration.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigration.java
index 961923f..a15cd77 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigration.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigration.java
@@ -47,11 +47,7 @@ import static org.testng.Assert.assertTrue;
public abstract class TestMigration extends TestApiBase {
public void testSingleBasePlan() {
-
try {
-
- log.info("Starting testSingleBasePlan");
-
final DateTime startDate = clock.getUTCNow().minusMonths(2);
final DateTime beforeMigration = clock.getUTCNow();
final EntitlementAccountMigration toBeMigrated = createAccountWithRegularBasePlan(startDate);
@@ -84,7 +80,6 @@ public abstract class TestMigration extends TestApiBase {
public void testPlanWithAddOn() {
try {
- log.info("Starting testPlanWithAddOn");
final DateTime beforeMigration = clock.getUTCNow();
final DateTime initalBPStart = clock.getUTCNow().minusMonths(3);
final DateTime initalAddonStart = clock.getUTCNow().minusMonths(1).plusDays(7);
@@ -134,7 +129,6 @@ public abstract class TestMigration extends TestApiBase {
public void testSingleBasePlanFutureCancelled() {
try {
- log.info("Starting testSingleBasePlanFutureCancelled");
final DateTime startDate = clock.getUTCNow().minusMonths(1);
final DateTime beforeMigration = clock.getUTCNow();
final EntitlementAccountMigration toBeMigrated = createAccountWithRegularBasePlanFutreCancelled(startDate);
@@ -159,7 +153,6 @@ public abstract class TestMigration extends TestApiBase {
assertEquals(subscription.getCurrentPlan().getName(), "assault-rifle-annual");
assertEquals(subscription.getChargedThroughDate(), startDate.plusYears(1));
-
testListener.pushExpectedEvent(NextEvent.MIGRATE_BILLING);
testListener.pushExpectedEvent(NextEvent.CANCEL);
@@ -176,17 +169,13 @@ public abstract class TestMigration extends TestApiBase {
assertNull(subscription.getCurrentPlan());
assertListenerStatus();
-
} catch (EntitlementMigrationApiException e) {
Assert.fail("", e);
}
}
public void testSingleBasePlanWithPendingPhase() {
-
try {
-
- log.info("Starting testSingleBasePlanWithPendingPhase");
final DateTime trialDate = clock.getUTCNow().minusDays(10);
final EntitlementAccountMigration toBeMigrated = createAccountFuturePendingPhase(trialDate);
@@ -226,16 +215,13 @@ public abstract class TestMigration extends TestApiBase {
assertEquals(subscription.getCurrentPhase().getName(), "assault-rifle-monthly-evergreen");
assertListenerStatus();
-
} catch (EntitlementMigrationApiException e) {
Assert.fail("", e);
}
}
public void testSingleBasePlanWithPendingChange() {
-
try {
- log.info("Starting testSingleBasePlanWithPendingChange");
final DateTime beforeMigration = clock.getUTCNow();
final EntitlementAccountMigration toBeMigrated = createAccountFuturePendingChange();
final DateTime afterMigration = clock.getUTCNow();
@@ -279,25 +265,19 @@ public abstract class TestMigration extends TestApiBase {
}
}
-
private EntitlementAccountMigration createAccountTest(final List<List<EntitlementSubscriptionMigrationCaseWithCTD>> cases) {
-
return new EntitlementAccountMigration() {
-
private final UUID accountId = UUID.randomUUID();
@Override
public EntitlementBundleMigration[] getBundles() {
final List<EntitlementBundleMigration> bundles = new ArrayList<EntitlementBundleMigration>();
final EntitlementBundleMigration bundle0 = new EntitlementBundleMigration() {
-
@Override
public EntitlementSubscriptionMigration[] getSubscriptions() {
-
final EntitlementSubscriptionMigration[] result = new EntitlementSubscriptionMigration[cases.size()];
for (int i = 0; i < cases.size(); i++) {
-
final List<EntitlementSubscriptionMigrationCaseWithCTD> curCases = cases.get(i);
final EntitlementSubscriptionMigration subscription = new EntitlementSubscriptionMigration() {
@Override
@@ -362,7 +342,6 @@ public abstract class TestMigration extends TestApiBase {
null,
null));
-
final List<List<EntitlementSubscriptionMigrationCaseWithCTD>> input = new ArrayList<List<EntitlementSubscriptionMigrationCaseWithCTD>>();
input.add(cases);
input.add(firstAddOnCases);
@@ -393,7 +372,6 @@ public abstract class TestMigration extends TestApiBase {
return createAccountTest(input);
}
-
private EntitlementAccountMigration createAccountFuturePendingPhase(final DateTime trialDate) {
final List<EntitlementSubscriptionMigrationCaseWithCTD> cases = new LinkedList<EntitlementSubscriptionMigrationCaseWithCTD>();
cases.add(new EntitlementSubscriptionMigrationCaseWithCTD(
@@ -429,9 +407,7 @@ public abstract class TestMigration extends TestApiBase {
return createAccountTest(input);
}
-
public static class EntitlementSubscriptionMigrationCaseWithCTD implements EntitlementSubscriptionMigrationCase {
-
private final PlanPhaseSpecifier pps;
private final DateTime effDt;
private final DateTime cancelDt;
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationMemory.java
index 81c12cd..e07e1c1 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationMemory.java
@@ -23,7 +23,6 @@ import com.google.inject.Injector;
import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;
-@Test(groups = "fast")
public class TestMigrationMemory extends TestMigration {
@Override
protected Injector getInjector() {
@@ -31,26 +30,25 @@ public class TestMigrationMemory extends TestMigration {
}
@Override
- @Test(enabled = true, groups = "fast")
+ @Test(groups = "fast")
public void testSingleBasePlan() {
super.testSingleBasePlan();
}
@Override
- @Test(enabled = true, groups = "fast")
+ @Test(groups = "fast")
public void testSingleBasePlanFutureCancelled() {
super.testSingleBasePlanFutureCancelled();
}
@Override
- @Test(enabled = true, groups = "fast")
+ @Test(groups = "fast")
public void testPlanWithAddOn() {
super.testPlanWithAddOn();
}
-
@Override
- @Test(enabled = true, groups = "fast")
+ @Test(groups = "fast")
public void testSingleBasePlanWithPendingPhase() {
super.testSingleBasePlanWithPendingPhase();
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationSql.java
index 82fc7e7..2d0b100 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/migration/TestMigrationSql.java
@@ -30,25 +30,25 @@ public class TestMigrationSql extends TestMigration {
}
@Override
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void testSingleBasePlan() {
super.testSingleBasePlan();
}
@Override
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void testPlanWithAddOn() {
super.testPlanWithAddOn();
}
@Override
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void testSingleBasePlanFutureCancelled() {
super.testSingleBasePlanFutureCancelled();
}
@Override
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void testSingleBasePlanWithPendingPhase() {
super.testSingleBasePlanWithPendingPhase();
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestApiBase.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestApiBase.java
index bfbc817..55115be 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestApiBase.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestApiBase.java
@@ -51,17 +51,17 @@ import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.catalog.api.TimeUnit;
import com.ning.billing.config.EntitlementConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.entitlement.EntitlementTestSuiteWithEmbeddedDB;
import com.ning.billing.entitlement.api.billing.ChargeThruApi;
import com.ning.billing.entitlement.api.migration.EntitlementMigrationApi;
import com.ning.billing.entitlement.api.timeline.EntitlementTimelineApi;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.SubscriptionData;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
import com.ning.billing.entitlement.engine.core.Engine;
import com.ning.billing.entitlement.engine.dao.EntitlementDao;
-import com.ning.billing.entitlement.engine.dao.MockEntitlementDao;
import com.ning.billing.entitlement.engine.dao.MockEntitlementDaoMemory;
import com.ning.billing.entitlement.events.EntitlementEvent;
import com.ning.billing.entitlement.events.phase.PhaseEvent;
@@ -74,14 +74,13 @@ import com.ning.billing.util.callcontext.TestCallContext;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
import com.ning.billing.util.glue.RealImplementation;
-import com.ning.billing.util.io.IOUtils;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
-public abstract class TestApiBase implements TestListenerStatus {
+public abstract class TestApiBase extends EntitlementTestSuiteWithEmbeddedDB implements TestListenerStatus {
protected static final Logger log = LoggerFactory.getLogger(TestApiBase.class);
protected EntitlementService entitlementService;
@@ -114,7 +113,6 @@ public abstract class TestApiBase implements TestListenerStatus {
//
protected DateTime testStartDate = new DateTime(2012, 5, 7, 0, 3, 42, 0);
-
public static void loadSystemPropertiesFromClasspath(final String resource) {
final URL url = TestApiBase.class.getResource(resource);
assertNotNull(url);
@@ -132,15 +130,11 @@ public abstract class TestApiBase implements TestListenerStatus {
public void tearDown() {
try {
((DefaultBusService) busService).stopBus();
- if (helper != null) {
- helper.stopMysql();
- }
} catch (Exception e) {
log.warn("Failed to tearDown test properly ", e);
}
}
-
@Override
public void failed(final String msg) {
this.isListenerFailed = true;
@@ -155,13 +149,11 @@ public abstract class TestApiBase implements TestListenerStatus {
@BeforeClass(alwaysRun = true)
public void setup() throws Exception {
-
loadSystemPropertiesFromClasspath("/entitlement.properties");
final Injector g = getInjector();
entitlementService = g.getInstance(EntitlementService.class);
- final EntitlementUserApi entApi = (EntitlementUserApi) g.getInstance(Key.get(EntitlementUserApi.class, RealImplementation.class));
- entitlementApi = entApi;
+ entitlementApi = g.getInstance(Key.get(EntitlementUserApi.class, RealImplementation.class));
billingApi = g.getInstance(ChargeThruApi.class);
migrationApi = g.getInstance(EntitlementMigrationApi.class);
repairApi = g.getInstance(EntitlementTimelineApi.class);
@@ -175,9 +167,6 @@ public abstract class TestApiBase implements TestListenerStatus {
}
private void init() throws Exception {
-
- setupDao();
-
((DefaultCatalogService) catalogService).loadCatalog();
accountData = getAccountData();
@@ -187,27 +176,19 @@ public abstract class TestApiBase implements TestListenerStatus {
testListener = new TestApiListener(this);
}
- private void setupDao() throws IOException {
- if (helper != null) {
- final String entitlementDdl = IOUtils.toString(TestApiBase.class.getResourceAsStream("/com/ning/billing/entitlement/ddl.sql"));
- final String utilDdl = IOUtils.toString(TestApiBase.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- helper.startMysql();
- helper.initDb(entitlementDdl);
- helper.initDb(utilDdl);
- }
- }
-
private static boolean isSqlTest(final EntitlementDao theDao) {
return (!(theDao instanceof MockEntitlementDaoMemory));
}
@BeforeMethod(alwaysRun = true)
public void setupTest() throws Exception {
-
- log.warn("RESET TEST FRAMEWORK\n\n");
+ log.warn("RESET TEST FRAMEWORK");
// CLEANUP ALL DB TABLES OR IN MEMORY STRUCTURES
- cleanupDao();
+ if (!isSqlTest(dao)) {
+ // The MySQL testing helper will clean the tables between each test
+ ((MockEntitlementDaoMemory) dao).reset();
+ }
// RESET LIST OF EXPECTED EVENTS
if (testListener != null) {
@@ -237,7 +218,6 @@ public abstract class TestApiBase implements TestListenerStatus {
@AfterMethod(alwaysRun = true)
public void cleanupTest() throws Exception {
-
// UNREGISTER TEST LISTENER AND STOP BUS
busService.getBus().unregister(testListener);
busService.getBus().stop();
@@ -245,7 +225,7 @@ public abstract class TestApiBase implements TestListenerStatus {
// STOP NOTIFICATION QUEUE
((Engine) entitlementService).stop();
- log.warn("DONE WITH TEST\n");
+ log.warn("DONE WITH TEST");
}
protected void assertListenerStatus() {
@@ -255,14 +235,6 @@ public abstract class TestApiBase implements TestListenerStatus {
}
}
- private void cleanupDao() {
- if (helper != null) {
- helper.cleanupAllTables();
- } else {
- ((MockEntitlementDao) dao).reset();
- }
- }
-
protected SubscriptionData createSubscription(final String productName, final BillingPeriod term, final String planSet, final DateTime requestedDate)
throws EntitlementUserApiException {
return createSubscriptionWithBundle(bundle.getId(), productName, term, planSet, requestedDate);
@@ -275,7 +247,6 @@ public abstract class TestApiBase implements TestListenerStatus {
protected SubscriptionData createSubscriptionWithBundle(final UUID bundleId, final String productName, final BillingPeriod term, final String planSet, final DateTime requestedDate)
throws EntitlementUserApiException {
-
testListener.pushExpectedEvent(NextEvent.CREATE);
final SubscriptionData subscription = (SubscriptionData) entitlementApi.createSubscription(bundleId,
new PlanPhaseSpecifier(productName, ProductCategory.BASE, term, planSet, null),
@@ -286,7 +257,6 @@ public abstract class TestApiBase implements TestListenerStatus {
}
protected void checkNextPhaseChange(final SubscriptionData subscription, final int expPendingEvents, final DateTime expPhaseChange) {
-
final List<EntitlementEvent> events = dao.getPendingEventsForSubscription(subscription.getId());
assertNotNull(events);
printEvents(events);
@@ -367,7 +337,6 @@ public abstract class TestApiBase implements TestListenerStatus {
return result;
}
-
protected Duration getDurationYear(final int years) {
final Duration result = new Duration() {
@Override
@@ -505,10 +474,9 @@ public abstract class TestApiBase implements TestListenerStatus {
}
}
- protected void printSubscriptionTransitions(final List<SubscriptionEvent> transitions) {
- for (final SubscriptionEvent cur : transitions) {
+ protected void printSubscriptionTransitions(final List<EffectiveSubscriptionEvent> transitions) {
+ for (final EffectiveSubscriptionEvent cur : transitions) {
log.debug("Transition " + cur);
}
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestEventJson.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestEventJson.java
index 978c39b..53c266b 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestEventJson.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestEventJson.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api;
import java.util.UUID;
@@ -21,32 +22,31 @@ import org.joda.time.DateTime;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.entitlement.EntitlementTestSuite;
import com.ning.billing.entitlement.api.timeline.DefaultRepairEntitlementEvent;
import com.ning.billing.entitlement.api.timeline.RepairEntitlementEvent;
-import com.ning.billing.entitlement.api.user.DefaultSubscriptionEvent;
+import com.ning.billing.entitlement.api.user.DefaultEffectiveSubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.Subscription.SubscriptionState;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
import com.ning.billing.util.jackson.ObjectMapper;
-public class TestEventJson {
+public class TestEventJson extends EntitlementTestSuite {
private final ObjectMapper mapper = new ObjectMapper();
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testSubscriptionEvent() throws Exception {
-
- final SubscriptionEvent e = new DefaultSubscriptionEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), new DateTime(), new DateTime(),
- SubscriptionState.ACTIVE, "pro", "TRIAL", "DEFAULT", SubscriptionState.CANCELLED, null, null, null, 3L, UUID.randomUUID(), SubscriptionTransitionType.CANCEL, 0, new DateTime());
+ final EffectiveSubscriptionEvent e = new DefaultEffectiveSubscriptionEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), new DateTime(), new DateTime(),
+ SubscriptionState.ACTIVE, "pro", "TRIAL", "DEFAULT", SubscriptionState.CANCELLED, null, null, null, 3L, UUID.randomUUID(), SubscriptionTransitionType.CANCEL, 0, new DateTime());
final String json = mapper.writeValueAsString(e);
- final Class<?> claz = Class.forName(DefaultSubscriptionEvent.class.getName());
+ final Class<?> claz = Class.forName(DefaultEffectiveSubscriptionEvent.class.getName());
final Object obj = mapper.readValue(json, claz);
Assert.assertTrue(obj.equals(e));
-
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testRepairEntitlementEvent() throws Exception {
final RepairEntitlementEvent e = new DefaultRepairEntitlementEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), new DateTime());
@@ -56,6 +56,4 @@ public class TestEventJson {
final Object obj = mapper.readValue(json, claz);
Assert.assertTrue(obj.equals(e));
}
-
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestApiBaseRepair.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestApiBaseRepair.java
index 292dc37..449d1e7 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestApiBaseRepair.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestApiBaseRepair.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collections;
@@ -39,9 +40,7 @@ import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import static org.testng.Assert.assertEquals;
-
public abstract class TestApiBaseRepair extends TestApiBase {
-
protected static final Logger log = LoggerFactory.getLogger(TestApiBaseRepair.class);
public interface TestWithExceptionCallback {
@@ -59,7 +58,6 @@ public abstract class TestApiBaseRepair extends TestApiBase {
}
}
-
protected SubscriptionTimeline createSubscriptionRepair(final UUID id, final List<DeletedEvent> deletedEvents, final List<NewEvent> newEvents) {
return new SubscriptionTimeline() {
@Override
@@ -111,9 +109,8 @@ public abstract class TestApiBaseRepair extends TestApiBase {
protected ExistingEvent createExistingEventForAssertion(final SubscriptionTransitionType type,
final String productName, final PhaseType phaseType, final ProductCategory category, final String priceListName, final BillingPeriod billingPeriod,
final DateTime effectiveDateTime) {
-
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier(productName, category, billingPeriod, priceListName, phaseType);
- final ExistingEvent ev = new ExistingEvent() {
+ return new ExistingEvent() {
@Override
public SubscriptionTransitionType getSubscriptionTransitionType() {
return type;
@@ -139,7 +136,6 @@ public abstract class TestApiBaseRepair extends TestApiBase {
return effectiveDateTime;
}
};
- return ev;
}
protected SubscriptionTimeline getSubscriptionRepair(final UUID id, final BundleTimeline bundleRepair) {
@@ -148,12 +144,11 @@ public abstract class TestApiBaseRepair extends TestApiBase {
return cur;
}
}
- Assert.fail("Failed to find SubscriptionReapir " + id);
+ Assert.fail("Failed to find SubscriptionRepair " + id);
return null;
}
protected void validateExistingEventForAssertion(final ExistingEvent expected, final ExistingEvent input) {
-
log.info(String.format("Got %s -> Expected %s", input.getPlanPhaseSpecifier().getProductName(), expected.getPlanPhaseSpecifier().getProductName()));
assertEquals(input.getPlanPhaseSpecifier().getProductName(), expected.getPlanPhaseSpecifier().getProductName());
log.info(String.format("Got %s -> Expected %s", input.getPlanPhaseSpecifier().getPhaseType(), expected.getPlanPhaseSpecifier().getPhaseType()));
@@ -178,7 +173,6 @@ public abstract class TestApiBaseRepair extends TestApiBase {
}
protected NewEvent createNewEvent(final SubscriptionTransitionType type, final DateTime requestedDate, final PlanPhaseSpecifier spec) {
-
return new NewEvent() {
@Override
public SubscriptionTransitionType getSubscriptionTransitionType() {
@@ -228,5 +222,4 @@ public abstract class TestApiBaseRepair extends TestApiBase {
}
});
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairBP.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairBP.java
index 6be5022..de7a40d 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairBP.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairBP.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collections;
@@ -53,17 +54,13 @@ import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public class TestRepairBP extends TestApiBaseRepair {
-
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testFetchBundleRepair() throws Exception {
-
- log.info("Starting testFetchBundleRepair");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -126,11 +123,8 @@ public class TestRepairBP extends TestApiBaseRepair {
}
//TODO MDW: Temporary disable need to look at this with Stephane
- @Test(groups = {"slow"}, enabled = false)
+ @Test(groups = "slow", enabled = false)
public void testBPRepairWithCancellationOnstart() throws Exception {
-
- log.info("Starting testBPRepairWithCancellationOnstart");
-
final String baseProduct = "Shotgun";
final DateTime startDate = clock.getUTCNow();
@@ -205,7 +199,6 @@ public class TestRepairBP extends TestApiBaseRepair {
final SubscriptionData realRunBaseSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(baseSubscription.getId());
assertEquals(realRunBaseSubscription.getAllTransitions().size(), 2);
-
assertEquals(realRunBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
assertEquals(realRunBaseSubscription.getBundleId(), bundle.getId());
assertEquals(realRunBaseSubscription.getStartDate(), startDate);
@@ -215,11 +208,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testBPRepairReplaceCreateBeforeTrial() throws Exception {
-
- log.info("Starting testBPRepairReplaceCreateBeforeTrial");
-
final String baseProduct = "Shotgun";
final String newBaseProduct = "Assault-Rifle";
@@ -237,11 +227,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testBPRepairReplaceCreateInTrial() throws Exception {
-
- log.info("Starting testBPRepairReplaceCreateInTrial");
-
final String baseProduct = "Shotgun";
final String newBaseProduct = "Assault-Rifle";
@@ -283,12 +270,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
-
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testBPRepairReplaceCreateAfterTrial() throws Exception {
-
- log.info("Starting testBPRepairReplaceCreateAfterTrial");
-
final String baseProduct = "Shotgun";
final String newBaseProduct = "Assault-Rifle";
@@ -306,12 +289,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
-
private UUID testBPRepairCreate(final boolean inTrial, final DateTime startDate, final int clockShift,
final String baseProduct, final String newBaseProduct, final List<ExistingEvent> expectedEvents) throws Exception {
-
- log.info("Starting testBPRepairCreate");
-
// CREATE BP
final Subscription baseSubscription = createSubscription(baseProduct, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, startDate);
@@ -400,7 +379,6 @@ public class TestRepairBP extends TestApiBaseRepair {
final SubscriptionData realRunBaseSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(baseSubscription.getId());
assertEquals(realRunBaseSubscription.getAllTransitions().size(), 2);
-
assertEquals(realRunBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
assertEquals(realRunBaseSubscription.getBundleId(), bundle.getId());
assertEquals(realRunBaseSubscription.getStartDate(), newCreateTime);
@@ -418,11 +396,8 @@ public class TestRepairBP extends TestApiBaseRepair {
return baseSubscription.getId();
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testBPRepairAddChangeInTrial() throws Exception {
-
- log.info("Starting testBPRepairAddChangeInTrial");
-
final String baseProduct = "Shotgun";
final String newBaseProduct = "Assault-Rifle";
@@ -465,11 +440,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testBPRepairAddChangeAfterTrial() throws Exception {
-
- log.info("Starting testBPRepairAddChangeAfterTrial");
-
final String baseProduct = "Shotgun";
final String newBaseProduct = "Assault-Rifle";
@@ -489,11 +461,8 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
-
private UUID testBPRepairAddChange(final boolean inTrial, final DateTime startDate, final int clockShift,
final String baseProduct, final String newBaseProduct, final List<ExistingEvent> expectedEvents, final int expectedTransitions) throws Exception {
-
-
// CREATE BP
final Subscription baseSubscription = createSubscription(baseProduct, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, startDate);
@@ -559,7 +528,6 @@ public class TestRepairBP extends TestApiBaseRepair {
assertEquals(currentPhase.getPhaseType(), PhaseType.EVERGREEN);
}
-
// SECOND RE-ISSUE CALL-- NON DRY RUN
dryRun = false;
testListener.pushExpectedEvent(NextEvent.REPAIR_BUNDLE);
@@ -580,7 +548,6 @@ public class TestRepairBP extends TestApiBaseRepair {
final SubscriptionData realRunBaseSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(baseSubscription.getId());
assertEquals(realRunBaseSubscription.getAllTransitions().size(), expectedTransitions);
-
assertEquals(realRunBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
assertEquals(realRunBaseSubscription.getBundleId(), bundle.getId());
assertEquals(realRunBaseSubscription.getStartDate(), baseSubscription.getStartDate());
@@ -601,11 +568,8 @@ public class TestRepairBP extends TestApiBaseRepair {
return baseSubscription.getId();
}
- @Test(groups = {"slow"})
- public void testRepairWithFurureCancelEvent() throws Exception {
-
- log.info("Starting testRepairWithFurureCancelEvent");
-
+ @Test(groups = "slow")
+ public void testRepairWithFutureCancelEvent() throws Exception {
final DateTime startDate = clock.getUTCNow();
// CREATE BP
@@ -623,11 +587,9 @@ public class TestRepairBP extends TestApiBaseRepair {
billingApi.setChargedThroughDate(baseSubscription.getId(), newChargedThroughDate, context);
baseSubscription = entitlementApi.getSubscriptionFromId(baseSubscription.getId());
-
final DateTime requestedChange = clock.getUTCNow();
baseSubscription.changePlan("Pistol", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, requestedChange, context);
-
// CHECK CHANGE DID NOT OCCUR YET
Plan currentPlan = baseSubscription.getCurrentPlan();
assertNotNull(currentPlan);
@@ -635,7 +597,6 @@ public class TestRepairBP extends TestApiBaseRepair {
assertEquals(currentPlan.getProduct().getCategory(), ProductCategory.BASE);
assertEquals(currentPlan.getBillingPeriod(), BillingPeriod.MONTHLY);
-
final DateTime repairTime = clock.getUTCNow().minusDays(1);
final BundleTimeline bundleRepair = repairApi.getBundleRepair(bundle.getId());
sortEventsOnBundle(bundleRepair);
@@ -675,13 +636,9 @@ public class TestRepairBP extends TestApiBaseRepair {
assertListenerStatus();
}
-
// Needs real SQL backend to be tested properly
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testENT_REPAIR_VIEW_CHANGED_newEvent() throws Exception {
-
- log.info("Starting testENT_REPAIR_VIEW_CHANGED_newEvent");
-
final TestWithException test = new TestWithException();
final DateTime startDate = clock.getUTCNow();
@@ -715,9 +672,6 @@ public class TestRepairBP extends TestApiBaseRepair {
@Test(groups = "slow")
public void testENT_REPAIR_VIEW_CHANGED_ctd() throws Exception {
-
- log.info("Starting testENT_REPAIR_VIEW_CHANGED_ctd");
-
final TestWithException test = new TestWithException();
final DateTime startDate = clock.getUTCNow();
@@ -748,5 +702,4 @@ public class TestRepairBP extends TestApiBaseRepair {
}
}, ErrorCode.ENT_REPAIR_VIEW_CHANGED);
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithAO.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithAO.java
index 85116a3..7757cec 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithAO.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithAO.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collections;
@@ -48,17 +49,13 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class TestRepairWithAO extends TestApiBaseRepair {
-
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairChangeBPWithAddonIncluded() throws Exception {
-
- log.info("Starting testRepairChangeBPWithAddonIncluded");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -149,7 +146,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
validateExistingEventForAssertion(e, bpRepair.getExistingEvents().get(index++));
}
-
SubscriptionData newAoSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(aoSubscription.getId());
assertEquals(newAoSubscription.getState(), SubscriptionState.ACTIVE);
assertEquals(newAoSubscription.getAllTransitions().size(), 2);
@@ -160,7 +156,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newAoSubscription2.getAllTransitions().size(), 2);
assertEquals(newAoSubscription2.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION);
-
SubscriptionData newBaseSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(baseSubscription.getId());
assertEquals(newBaseSubscription.getState(), SubscriptionState.ACTIVE);
assertEquals(newBaseSubscription.getAllTransitions().size(), 2);
@@ -171,7 +166,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
final BundleTimeline realRunBundleRepair = repairApi.repairBundle(bundleRepair, dryRun, context);
assertTrue(testListener.isCompleted(5000));
-
aoRepair = getSubscriptionRepair(aoSubscription.getId(), realRunBundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
@@ -203,18 +197,14 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newAoSubscription2.getAllTransitions().size(), 2);
assertEquals(newAoSubscription2.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
-
newBaseSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(baseSubscription.getId());
assertEquals(newBaseSubscription.getState(), SubscriptionState.ACTIVE);
assertEquals(newBaseSubscription.getAllTransitions().size(), 3);
assertEquals(newBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairChangeBPWithAddonNonAvailable() throws Exception {
-
- log.info("Starting testRepairChangeBPWithAddonNonAvailable");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -332,11 +322,8 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairCancelBP_EOT_WithAddons() throws Exception {
-
- log.info("Starting testRepairCancelBP_EOT_WithAddons");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -348,7 +335,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(4));
clock.addDeltaFromReality(it.toDurationMillis());
-
final SubscriptionData aoSubscription = createSubscription("Telescopic-Scope", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
// MOVE CLOCK A LITTLE BIT MORE -- AFTER TRIAL
@@ -475,12 +461,8 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
}
-
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairCancelAO() throws Exception {
-
- log.info("Starting testRepairCancelAO");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -508,7 +490,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
SubscriptionTimeline aoRepair = getSubscriptionRepair(aoSubscription.getId(), bundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
-
final List<DeletedEvent> des = new LinkedList<SubscriptionTimeline.DeletedEvent>();
des.add(createDeletedEvent(aoRepair.getExistingEvents().get(1).getEventId()));
final DateTime aoCancelDate = aoSubscription.getStartDate().plusDays(1);
@@ -552,7 +533,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
final BundleTimeline realRunBundleRepair = repairApi.repairBundle(bRepair, dryRun, context);
assertTrue(testListener.isCompleted(5000));
-
aoRepair = getSubscriptionRepair(aoSubscription.getId(), realRunBundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
index = 0;
@@ -571,12 +551,8 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newBaseSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION);
}
-
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairRecreateAO() throws Exception {
-
- log.info("Starting testRepairRecreateAO");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -604,7 +580,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
SubscriptionTimeline aoRepair = getSubscriptionRepair(aoSubscription.getId(), bundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
-
final List<DeletedEvent> des = new LinkedList<SubscriptionTimeline.DeletedEvent>();
des.add(createDeletedEvent(aoRepair.getExistingEvents().get(0).getEventId()));
des.add(createDeletedEvent(aoRepair.getExistingEvents().get(1).getEventId()));
@@ -623,7 +598,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
aoRepair = getSubscriptionRepair(aoSubscription.getId(), dryRunBundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
-
final List<ExistingEvent> expected = new LinkedList<SubscriptionTimeline.ExistingEvent>();
expected.add(createExistingEventForAssertion(SubscriptionTransitionType.CREATE, "Telescopic-Scope", PhaseType.DISCOUNT,
ProductCategory.ADD_ON, PriceListSet.DEFAULT_PRICELIST_NAME, BillingPeriod.MONTHLY, aoRecreateDate));
@@ -668,11 +642,8 @@ public class TestRepairWithAO extends TestApiBaseRepair {
// . Both multi phase
// . Telescopic-Scope (bundle align) and Laser-Scope is Subscription align
//
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testRepairChangeAOOK() throws Exception {
-
- log.info("Starting testRepairChangeAOOK");
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -716,7 +687,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
aoRepair = getSubscriptionRepair(aoSubscription.getId(), dryRunBundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 3);
-
final List<ExistingEvent> expected = new LinkedList<SubscriptionTimeline.ExistingEvent>();
expected.add(createExistingEventForAssertion(SubscriptionTransitionType.CREATE, "Telescopic-Scope", PhaseType.DISCOUNT,
ProductCategory.ADD_ON, PriceListSet.DEFAULT_PRICELIST_NAME, BillingPeriod.MONTHLY, aoSubscription.getStartDate()));
@@ -751,7 +721,6 @@ public class TestRepairWithAO extends TestApiBaseRepair {
assertEquals(newAoSubscription.getState(), SubscriptionState.ACTIVE);
assertEquals(newAoSubscription.getAllTransitions().size(), 3);
-
assertEquals(newAoSubscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION + 1);
assertEquals(newAoSubscription.getBundleId(), bundle.getId());
assertEquals(newAoSubscription.getStartDate(), aoSubscription.getStartDate());
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithError.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithError.java
index 7c61f4f..6c1d506 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithError.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/timeline/TestRepairWithError.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.entitlement.api.timeline;
import java.util.Collections;
@@ -47,7 +48,6 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class TestRepairWithError extends TestApiBaseRepair {
-
private static final String baseProduct = "Shotgun";
private TestWithException test;
private Subscription baseSubscription;
@@ -65,15 +65,11 @@ public class TestRepairWithError extends TestApiBaseRepair {
baseSubscription = createSubscription(baseProduct, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, startDate);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_NEW_EVENT_BEFORE_LAST_BP_REMAINING() throws Exception {
-
- log.info("Starting testENT_REPAIR_NEW_EVENT_BEFORE_LAST_BP_REMAINING");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException {
-
// MOVE AFTER TRIAL
testListener.pushExpectedEvent(NextEvent.PHASE);
@@ -96,11 +92,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_NEW_EVENT_BEFORE_LAST_BP_REMAINING);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_INVALID_DELETE_SET() throws Exception {
-
- log.info("Starting testENT_REPAIR_INVALID_DELETE_SET");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
@@ -133,11 +126,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_INVALID_DELETE_SET);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_NON_EXISTENT_DELETE_EVENT() throws Exception {
-
- log.info("Starting testENT_REPAIR_NON_EXISTENT_DELETE_EVENT");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException {
@@ -156,11 +146,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_NON_EXISTENT_DELETE_EVENT);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_SUB_RECREATE_NOT_EMPTY() throws Exception {
-
- log.info("Starting testENT_REPAIR_SUB_RECREATE_NOT_EMPTY");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException {
@@ -187,11 +174,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_SUB_RECREATE_NOT_EMPTY);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_SUB_EMPTY() throws Exception {
-
- log.info("Starting testENT_REPAIR_SUB_EMPTY");
-
test.withException(new TestWithExceptionCallback() {
@Override
@@ -219,16 +203,11 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_SUB_EMPTY);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_AO_CREATE_BEFORE_BP_START() throws Exception {
-
- log.info("Starting testENT_REPAIR_AO_CREATE_BEFORE_BP_START");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
-
-
// MOVE CLOCK A LITTLE BIT-- STILL IN TRIAL
Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(4));
clock.addDeltaFromReality(it.toDurationMillis());
@@ -248,7 +227,6 @@ public class TestRepairWithError extends TestApiBaseRepair {
final SubscriptionTimeline aoRepair = getSubscriptionRepair(aoSubscription.getId(), bundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
-
final List<DeletedEvent> des = new LinkedList<SubscriptionTimeline.DeletedEvent>();
des.add(createDeletedEvent(aoRepair.getExistingEvents().get(0).getEventId()));
des.add(createDeletedEvent(aoRepair.getExistingEvents().get(1).getEventId()));
@@ -267,16 +245,12 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_AO_CREATE_BEFORE_BP_START);
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_NEW_EVENT_BEFORE_LAST_AO_REMAINING() throws Exception {
-
- log.info("Starting testENT_REPAIR_NEW_EVENT_BEFORE_LAST_AO_REMAINING");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
-
// MOVE CLOCK A LITTLE BIT-- STILL IN TRIAL
Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(4));
clock.addDeltaFromReality(it.toDurationMillis());
@@ -296,7 +270,6 @@ public class TestRepairWithError extends TestApiBaseRepair {
final SubscriptionTimeline aoRepair = getSubscriptionRepair(aoSubscription.getId(), bundleRepair);
assertEquals(aoRepair.getExistingEvents().size(), 2);
-
final List<DeletedEvent> des = new LinkedList<SubscriptionTimeline.DeletedEvent>();
//des.add(createDeletedEvent(aoRepair.getExistingEvents().get(1).getEventId()));
final DateTime aoCancelDate = aoSubscription.getStartDate().plusDays(10);
@@ -313,12 +286,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_NEW_EVENT_BEFORE_LAST_AO_REMAINING);
}
-
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testENT_REPAIR_BP_RECREATE_MISSING_AO() throws Exception {
-
- log.info("Starting testENT_REPAIR_BP_RECREATE_MISSING_AO");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
@@ -357,11 +326,8 @@ public class TestRepairWithError extends TestApiBaseRepair {
//
// CAN'T seem to trigger such case easily, other errors trigger before...
//
- @Test(groups = {"fast"}, enabled = false)
+ @Test(groups = "fast", enabled = false)
public void testENT_REPAIR_BP_RECREATE_MISSING_AO_CREATE() throws Exception {
-
- log.info("Starting testENT_REPAIR_BP_RECREATE_MISSING_AO_CREATE");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
@@ -406,16 +372,12 @@ public class TestRepairWithError extends TestApiBaseRepair {
}, ErrorCode.ENT_REPAIR_BP_RECREATE_MISSING_AO_CREATE);
}
- @Test(groups = {"fast"}, enabled = false)
+ @Test(groups = "fast", enabled = false)
public void testENT_REPAIR_MISSING_AO_DELETE_EVENT() throws Exception {
-
- log.info("Starting testENT_REPAIR_MISSING_AO_DELETE_EVENT");
-
test.withException(new TestWithExceptionCallback() {
@Override
public void doTest() throws EntitlementRepairException, EntitlementUserApiException {
-
/*
// MOVE CLOCK -- JUST BEFORE END OF TRIAL
*
@@ -460,5 +422,4 @@ public class TestRepairWithError extends TestApiBaseRepair {
}
}, ErrorCode.ENT_REPAIR_MISSING_AO_DELETE_EVENT);
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiAddOn.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiAddOn.java
index 68b1978..2571b6f 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiAddOn.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiAddOn.java
@@ -49,17 +49,13 @@ import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public class TestUserApiAddOn extends TestApiBase {
-
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCreateCancelAddon() {
-
- log.info("Starting testCreateCancelAddon");
-
try {
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
@@ -89,13 +85,9 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCancelBPWithAddon() {
-
- log.info("Starting testCancelBPWithAddon");
-
try {
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -154,14 +146,9 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
-
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testChangeBPWithAddonIncluded() {
-
- log.info("Starting testChangeBPWithAddonIncluded");
-
try {
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -221,13 +208,9 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testChangeBPWithAddonNonAvailable() {
-
- log.info("Starting testChangeBPWithAddonNonAvailable");
-
try {
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -286,7 +269,6 @@ public class TestUserApiAddOn extends TestApiBase {
clock.addDeltaFromReality(it.toDurationMillis());
assertTrue(testListener.isCompleted(5000));
-
// REFETCH AO SUBSCRIPTION AND CHECK THIS CANCELLED
aoSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(aoSubscription.getId());
assertEquals(aoSubscription.getState(), SubscriptionState.CANCELLED);
@@ -297,12 +279,8 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
-
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testAddonCreateWithBundleAlign() {
-
- log.info("Starting testAddonCreateWithBundleAlign");
-
try {
final String aoProduct = "Telescopic-Scope";
final BillingPeriod aoTerm = BillingPeriod.MONTHLY;
@@ -310,9 +288,9 @@ public class TestUserApiAddOn extends TestApiBase {
// This is just to double check our test catalog gives us what we want before we start the test
final PlanSpecifier planSpecifier = new PlanSpecifier(aoProduct,
- ProductCategory.ADD_ON,
- aoTerm,
- aoPriceList);
+ ProductCategory.ADD_ON,
+ aoTerm,
+ aoPriceList);
final PlanAlignmentCreate alignement = catalog.planCreateAlignment(planSpecifier, clock.getUTCNow());
assertEquals(alignement, PlanAlignmentCreate.START_OF_BUNDLE);
@@ -324,11 +302,8 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testAddonCreateWithSubscriptionAlign() {
-
- log.info("Starting testAddonCreateWithSubscriptionAlign");
-
try {
final String aoProduct = "Laser-Scope";
final BillingPeriod aoTerm = BillingPeriod.MONTHLY;
@@ -336,9 +311,9 @@ public class TestUserApiAddOn extends TestApiBase {
// This is just to double check our test catalog gives us what we want before we start the test
final PlanSpecifier planSpecifier = new PlanSpecifier(aoProduct,
- ProductCategory.ADD_ON,
- aoTerm,
- aoPriceList);
+ ProductCategory.ADD_ON,
+ aoTerm,
+ aoPriceList);
final PlanAlignmentCreate alignement = catalog.planCreateAlignment(planSpecifier, clock.getUTCNow());
assertEquals(alignement, PlanAlignmentCreate.START_OF_SUBSCRIPTION);
@@ -350,11 +325,8 @@ public class TestUserApiAddOn extends TestApiBase {
}
}
-
private void testAddonCreateInternal(final String aoProduct, final BillingPeriod aoTerm, final String aoPriceList, final PlanAlignmentCreate expAlignement) {
-
try {
-
final String baseProduct = "Shotgun";
final BillingPeriod baseTerm = BillingPeriod.MONTHLY;
final String basePriceList = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -386,7 +358,7 @@ public class TestUserApiAddOn extends TestApiBase {
assertEquals(aoSubscription.getBundleStartDate(), baseSubscription.getBundleStartDate());
// CHECK next AO PHASE EVENT IS INDEED A MONTH AFTER BP STARTED => BUNDLE ALIGNMENT
- SubscriptionEvent aoPendingTranstion = aoSubscription.getPendingTransition();
+ EffectiveSubscriptionEvent aoPendingTranstion = aoSubscription.getPendingTransition();
if (expAlignement == PlanAlignmentCreate.START_OF_BUNDLE) {
assertEquals(aoPendingTranstion.getEffectiveTransitionTime(), baseSubscription.getStartDate().plusMonths(1));
@@ -404,7 +376,6 @@ public class TestUserApiAddOn extends TestApiBase {
clock.addDeltaFromReality(it.toDurationMillis());
assertTrue(testListener.isCompleted(5000));
-
// CHECK EVERYTHING AGAIN
aoSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(aoSubscription.getId());
@@ -418,11 +389,9 @@ public class TestUserApiAddOn extends TestApiBase {
assertNotNull(aoCurrentPhase);
assertEquals(aoCurrentPhase.getPhaseType(), PhaseType.EVERGREEN);
-
aoSubscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(aoSubscription.getId());
aoPendingTranstion = aoSubscription.getPendingTransition();
assertNull(aoPendingTranstion);
-
} catch (EntitlementUserApiException e) {
Assert.fail(e.getMessage());
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancel.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancel.java
index afebb34..af1b2f4 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancel.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancel.java
@@ -37,13 +37,8 @@ import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public abstract class TestUserApiCancel extends TestApiBase {
-
protected void testCancelSubscriptionIMM() {
-
- log.info("Starting testCancelSubscriptionIMM");
-
try {
-
final DateTime init = clock.getUTCNow();
final String prod = "Shotgun";
@@ -76,12 +71,8 @@ public abstract class TestUserApiCancel extends TestApiBase {
}
}
-
protected void testCancelSubscriptionEOTWithChargeThroughDate() throws EntitlementBillingApiException {
- log.info("Starting testCancelSubscriptionEOTWithChargeThroughDate");
-
try {
-
final String prod = "Shotgun";
final BillingPeriod term = BillingPeriod.MONTHLY;
final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -117,6 +108,9 @@ public abstract class TestUserApiCancel extends TestApiBase {
assertFalse(testListener.isCompleted(3000));
testListener.reset();
+ DateTime futureEndDate = subscription.getFutureEndDate();
+ Assert.assertNotNull(futureEndDate);
+
// MOVE TO EOT + RECHECK
testListener.pushExpectedEvent(NextEvent.CANCEL);
it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusMonths(1));
@@ -124,6 +118,8 @@ public abstract class TestUserApiCancel extends TestApiBase {
final DateTime future = clock.getUTCNow();
assertTrue(testListener.isCompleted(5000));
+ assertTrue(futureEndDate.compareTo(subscription.getEndDate()) == 0);
+
final PlanPhase currentPhase = subscription.getCurrentPhase();
assertNull(currentPhase);
checkNextPhaseChange(subscription, 0, null);
@@ -134,13 +130,8 @@ public abstract class TestUserApiCancel extends TestApiBase {
}
}
-
protected void testCancelSubscriptionEOTWithNoChargeThroughDate() {
-
- log.info("Starting testCancelSubscriptionEOTWithNoChargeThroughDate");
-
try {
-
final String prod = "Shotgun";
final BillingPeriod term = BillingPeriod.MONTHLY;
final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -183,11 +174,7 @@ public abstract class TestUserApiCancel extends TestApiBase {
// are as they used to be and we can move forward without hitting cancellation
//
protected void testUncancel() throws EntitlementBillingApiException {
-
- log.info("Starting testUncancel");
-
try {
-
final String prod = "Shotgun";
final BillingPeriod term = BillingPeriod.MONTHLY;
final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME;
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelMemory.java
index 4b3f54a..60d978f 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelMemory.java
@@ -25,33 +25,31 @@ import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;
public class TestUserApiCancelMemory extends TestUserApiCancel {
-
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, new MockEngineModuleMemory());
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCancelSubscriptionIMM() {
super.testCancelSubscriptionIMM();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCancelSubscriptionEOTWithChargeThroughDate() throws EntitlementBillingApiException {
super.testCancelSubscriptionEOTWithChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCancelSubscriptionEOTWithNoChargeThroughDate() {
super.testCancelSubscriptionEOTWithNoChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testUncancel() throws EntitlementBillingApiException {
super.testUncancel();
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelSql.java
index 2bd3299..535add2 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCancelSql.java
@@ -25,14 +25,12 @@ import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
import com.ning.billing.entitlement.glue.MockEngineModuleSql;
public class TestUserApiCancelSql extends TestUserApiCancel {
-
-
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(enabled = false, groups = {"stress"})
+ @Test(enabled = false, groups = {"slow, stress"})
public void stressTest() throws Exception {
final int MAX_STRESS_ITERATIONS = 10;
for (int i = 0; i < MAX_STRESS_ITERATIONS; i++) {
@@ -49,27 +47,26 @@ public class TestUserApiCancelSql extends TestUserApiCancel {
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCancelSubscriptionIMM() {
super.testCancelSubscriptionIMM();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCancelSubscriptionEOTWithChargeThroughDate() throws EntitlementBillingApiException {
super.testCancelSubscriptionEOTWithChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCancelSubscriptionEOTWithNoChargeThroughDate() {
super.testCancelSubscriptionEOTWithNoChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testUncancel() throws EntitlementBillingApiException {
super.testUncancel();
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlan.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlan.java
index 5591238..72573e3 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlan.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlan.java
@@ -43,8 +43,6 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public abstract class TestUserApiChangePlan extends TestApiBase {
-
-
private void checkChangePlan(final SubscriptionData subscription, final String expProduct, final ProductCategory expCategory,
final BillingPeriod expBillingPeriod, final PhaseType expPhase) {
@@ -59,19 +57,13 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
assertEquals(currentPhase.getPhaseType(), expPhase);
}
-
protected void testChangePlanBundleAlignEOTWithNoChargeThroughDate() {
tChangePlanBundleAlignEOTWithNoChargeThroughDate("Shotgun", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, "Pistol", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
}
-
private void tChangePlanBundleAlignEOTWithNoChargeThroughDate(final String fromProd, final BillingPeriod fromTerm, final String fromPlanSet,
final String toProd, final BillingPeriod toTerm, final String toPlanSet) {
-
- log.info("Starting testChangePlanBundleAlignEOTWithNoChargeThroughDate");
-
try {
-
// CREATE
final SubscriptionData subscription = createSubscription(fromProd, fromTerm, fromPlanSet);
@@ -102,25 +94,19 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
}
-
protected void testChangePlanBundleAlignEOTWithChargeThroughDate() throws EntitlementBillingApiException {
- log.info("Starting testChangePlanBundleAlignEOTWithChargeThroughDate");
testChangePlanBundleAlignEOTWithChargeThroughDate("Shotgun", BillingPeriod.ANNUAL, "gunclubDiscount", "Pistol", BillingPeriod.ANNUAL, "gunclubDiscount");
}
private void testChangePlanBundleAlignEOTWithChargeThroughDate(final String fromProd, final BillingPeriod fromTerm, final String fromPlanSet,
final String toProd, final BillingPeriod toTerm, final String toPlanSet) throws EntitlementBillingApiException {
-
-
try {
-
// CREATE
SubscriptionData subscription = createSubscription(fromProd, fromTerm, fromPlanSet);
final PlanPhase trialPhase = subscription.getCurrentPhase();
final DateTime expectedPhaseTrialChange = DefaultClock.addDuration(subscription.getStartDate(), trialPhase.getDuration());
assertEquals(trialPhase.getPhaseType(), PhaseType.TRIAL);
-
// MOVE TO NEXT PHASE
testListener.pushExpectedEvent(NextEvent.PHASE);
Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31));
@@ -129,7 +115,6 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
PlanPhase currentPhase = subscription.getCurrentPhase();
assertEquals(currentPhase.getPhaseType(), PhaseType.DISCOUNT);
-
// SET CTD
final Duration ctd = getDurationMonth(1);
final DateTime newChargedThroughDate = DefaultClock.addDuration(expectedPhaseTrialChange, ctd);
@@ -155,7 +140,6 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
final List<EntitlementEvent> events = dao.getPendingEventsForSubscription(subscription.getId());
assertTrue(events.get(0) instanceof ApiEvent);
-
// MOVE TO EOT
testListener.pushExpectedEvent(NextEvent.CHANGE);
it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusMonths(1));
@@ -172,19 +156,14 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
}
-
protected void testChangePlanBundleAlignIMM() {
tChangePlanBundleAlignIMM("Shotgun", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, "Assault-Rifle", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
}
-
private void tChangePlanBundleAlignIMM(final String fromProd, final BillingPeriod fromTerm, final String fromPlanSet,
final String toProd, final BillingPeriod toTerm, final String toPlanSet) {
- log.info("Starting testChangePlanBundleAlignIMM");
-
try {
-
final SubscriptionData subscription = createSubscription(fromProd, fromTerm, fromPlanSet);
testListener.pushExpectedEvent(NextEvent.CHANGE);
@@ -217,17 +196,13 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
}
-
protected void testChangePlanChangePlanAlignEOTWithChargeThroughDate() throws EntitlementBillingApiException {
- log.info("Starting testChangePlanChangePlanAlignEOTWithChargeThroughDate");
tChangePlanChangePlanAlignEOTWithChargeThroughDate("Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, "Assault-Rifle", BillingPeriod.ANNUAL, "rescue");
}
private void tChangePlanChangePlanAlignEOTWithChargeThroughDate(final String fromProd, final BillingPeriod fromTerm, final String fromPlanSet,
final String toProd, final BillingPeriod toTerm, final String toPlanSet) throws EntitlementBillingApiException {
-
try {
-
DateTime currentTime = clock.getUTCNow();
SubscriptionData subscription = createSubscription(fromProd, fromTerm, fromPlanSet);
@@ -308,8 +283,6 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
protected void testMultipleChangeLastIMM() throws EntitlementBillingApiException {
-
- log.info("Starting testMultipleChangeLastIMM");
try {
SubscriptionData subscription = createSubscription("Assault-Rifle", BillingPeriod.MONTHLY, "gunclubDiscount");
final PlanPhase trialPhase = subscription.getCurrentPhase();
@@ -361,10 +334,7 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
protected void testMultipleChangeLastEOT() throws EntitlementBillingApiException {
-
- log.info("Starting testMultipleChangeLastEOT");
try {
-
SubscriptionData subscription = createSubscription("Assault-Rifle", BillingPeriod.ANNUAL, "gunclubDiscount");
final PlanPhase trialPhase = subscription.getCurrentPhase();
assertEquals(trialPhase.getPhaseType(), PhaseType.TRIAL);
@@ -425,7 +395,6 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
assertNotNull(currentPhase);
assertEquals(currentPhase.getPhaseType(), PhaseType.DISCOUNT);
-
// MOVE TO NEXT PHASE
testListener.pushExpectedEvent(NextEvent.PHASE);
it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusMonths(6));
@@ -449,13 +418,8 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
}
}
-
protected void testCorrectPhaseAlignmentOnChange() {
-
- log.info("Starting testCorrectPhaseAlignmentOnChange");
-
try {
-
SubscriptionData subscription = createSubscription("Shotgun", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
PlanPhase trialPhase = subscription.getCurrentPhase();
assertEquals(trialPhase.getPhaseType(), PhaseType.TRIAL);
@@ -464,7 +428,6 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(2));
clock.addDeltaFromReality(it.toDurationMillis());
-
// CHANGE IMMEDIATE TO A 3 PHASES PLAN
testListener.reset();
testListener.pushExpectedEvent(NextEvent.CHANGE);
@@ -495,7 +458,7 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
subscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(subscription.getId());
final DateTime expectedNextPhaseDate = subscription.getStartDate().plusDays(30).plusMonths(6);
- final SubscriptionEvent nextPhase = subscription.getPendingTransition();
+ final EffectiveSubscriptionEvent nextPhase = subscription.getPendingTransition();
final DateTime nextPhaseEffectiveDate = nextPhase.getEffectiveTransitionTime();
assertEquals(nextPhaseEffectiveDate, expectedNextPhaseDate);
@@ -506,5 +469,4 @@ public abstract class TestUserApiChangePlan extends TestApiBase {
Assert.fail(e.getMessage());
}
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanMemory.java
index 6bc6864..1bf654b 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanMemory.java
@@ -25,46 +25,43 @@ import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;
public class TestUserApiChangePlanMemory extends TestUserApiChangePlan {
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, new MockEngineModuleMemory());
}
-
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testChangePlanBundleAlignEOTWithNoChargeThroughDate() {
super.testChangePlanBundleAlignEOTWithNoChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testChangePlanBundleAlignEOTWithChargeThroughDate() throws EntitlementBillingApiException {
super.testChangePlanBundleAlignEOTWithChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testChangePlanBundleAlignIMM() {
super.testChangePlanBundleAlignIMM();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testMultipleChangeLastIMM() throws EntitlementBillingApiException {
super.testMultipleChangeLastIMM();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testMultipleChangeLastEOT() throws EntitlementBillingApiException {
super.testMultipleChangeLastEOT();
}
-
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCorrectPhaseAlignmentOnChange() {
super.testCorrectPhaseAlignmentOnChange();
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanSql.java
index bec359b..406b575 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiChangePlanSql.java
@@ -25,13 +25,12 @@ import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
import com.ning.billing.entitlement.glue.MockEngineModuleSql;
public class TestUserApiChangePlanSql extends TestUserApiChangePlan {
-
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(enabled = false, groups = {"stress"})
+ @Test(enabled = false, groups = {"slow", "stress"})
public void stressTest() throws Exception {
final int MAX_STRESS_ITERATIONS = 10;
for (int i = 0; i < MAX_STRESS_ITERATIONS; i++) {
@@ -54,37 +53,37 @@ public class TestUserApiChangePlanSql extends TestUserApiChangePlan {
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCorrectPhaseAlignmentOnChange() {
super.testCorrectPhaseAlignmentOnChange();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testChangePlanBundleAlignEOTWithNoChargeThroughDate() {
super.testChangePlanBundleAlignEOTWithNoChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testChangePlanBundleAlignEOTWithChargeThroughDate() throws EntitlementBillingApiException {
super.testChangePlanBundleAlignEOTWithChargeThroughDate();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testChangePlanBundleAlignIMM() {
super.testChangePlanBundleAlignIMM();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testMultipleChangeLastIMM() throws EntitlementBillingApiException {
super.testMultipleChangeLastIMM();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testMultipleChangeLastEOT() throws EntitlementBillingApiException {
super.testMultipleChangeLastEOT();
}
@@ -95,5 +94,4 @@ public class TestUserApiChangePlanSql extends TestUserApiChangePlan {
public void testChangePlanChangePlanAlignEOTWithChargeThroughDate() throws EntitlementBillingApiException {
super.testChangePlanChangePlanAlignEOTWithChargeThroughDate();
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreate.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreate.java
index 510f55b..9ab3af1 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreate.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreate.java
@@ -16,7 +16,6 @@
package com.ning.billing.entitlement.api.user;
-
import java.util.List;
import org.joda.time.DateTime;
@@ -42,13 +41,10 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public abstract class TestUserApiCreate extends TestApiBase {
-
private static final Logger log = LoggerFactory.getLogger(TestUserApiCreate.class);
public void testCreateWithRequestedDate() {
- log.info("Starting testCreateWithRequestedDate");
try {
-
final DateTime init = clock.getUTCNow();
final DateTime requestedDate = init.minusYears(1);
@@ -56,13 +52,11 @@ public abstract class TestUserApiCreate extends TestApiBase {
final BillingPeriod term = BillingPeriod.MONTHLY;
final String planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
-
testListener.pushExpectedEvent(NextEvent.PHASE);
testListener.pushExpectedEvent(NextEvent.CREATE);
-
final SubscriptionData subscription = (SubscriptionData) entitlementApi.createSubscription(bundle.getId(),
- getProductSpecifier(productName, planSetName, term, null), requestedDate, context);
+ getProductSpecifier(productName, planSetName, term, null), requestedDate, context);
assertNotNull(subscription);
assertEquals(subscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION);
@@ -80,12 +74,8 @@ public abstract class TestUserApiCreate extends TestApiBase {
}
}
-
protected void testCreateWithInitialPhase() {
- log.info("Starting testCreateWithInitialPhase");
try {
-
-
final DateTime init = clock.getUTCNow();
final String productName = "Shotgun";
@@ -95,7 +85,7 @@ public abstract class TestUserApiCreate extends TestApiBase {
testListener.pushExpectedEvent(NextEvent.CREATE);
final SubscriptionData subscription = (SubscriptionData) entitlementApi.createSubscription(bundle.getId(),
- getProductSpecifier(productName, planSetName, term, PhaseType.EVERGREEN), clock.getUTCNow(), context);
+ getProductSpecifier(productName, planSetName, term, PhaseType.EVERGREEN), clock.getUTCNow(), context);
assertNotNull(subscription);
assertEquals(subscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION);
@@ -122,10 +112,7 @@ public abstract class TestUserApiCreate extends TestApiBase {
}
protected void testSimpleCreateSubscription() {
-
- log.info("Starting testSimpleCreateSubscription");
try {
-
final DateTime init = clock.getUTCNow();
final String productName = "Shotgun";
@@ -135,8 +122,8 @@ public abstract class TestUserApiCreate extends TestApiBase {
testListener.pushExpectedEvent(NextEvent.CREATE);
final SubscriptionData subscription = (SubscriptionData) entitlementApi.createSubscription(bundle.getId(),
- getProductSpecifier(productName, planSetName, term, null),
- clock.getUTCNow(), context);
+ getProductSpecifier(productName, planSetName, term, null),
+ clock.getUTCNow(), context);
assertNotNull(subscription);
assertEquals(subscription.getActiveVersion(), SubscriptionEvents.INITIAL_VERSION);
@@ -180,12 +167,8 @@ public abstract class TestUserApiCreate extends TestApiBase {
}
}
-
protected void testSimpleSubscriptionThroughPhases() {
-
- log.info("Starting testSimpleSubscriptionThroughPhases");
try {
-
final String productName = "Pistol";
final BillingPeriod term = BillingPeriod.ANNUAL;
final String planSetName = "gunclubDiscount";
@@ -211,7 +194,6 @@ public abstract class TestUserApiCreate extends TestApiBase {
assertNotNull(currentPhase);
assertEquals(currentPhase.getPhaseType(), PhaseType.DISCOUNT);
-
// MOVE TO EVERGREEN PHASE + RE-READ SUBSCRIPTION
testListener.pushExpectedEvent(NextEvent.PHASE);
it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusYears(1));
@@ -230,10 +212,7 @@ public abstract class TestUserApiCreate extends TestApiBase {
}
protected void testSubscriptionWithAddOn() {
-
- log.info("Starting testSubscriptionWithAddOn");
try {
-
final String productName = "Shotgun";
final BillingPeriod term = BillingPeriod.ANNUAL;
final String planSetName = PriceListSet.DEFAULT_PRICELIST_NAME;
@@ -241,7 +220,7 @@ public abstract class TestUserApiCreate extends TestApiBase {
testListener.pushExpectedEvent(NextEvent.CREATE);
final SubscriptionData subscription = (SubscriptionData) entitlementApi.createSubscription(bundle.getId(),
- getProductSpecifier(productName, planSetName, term, null), clock.getUTCNow(), context);
+ getProductSpecifier(productName, planSetName, term, null), clock.getUTCNow(), context);
assertNotNull(subscription);
assertListenerStatus();
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateMemory.java
index d671d2a..a7cd464 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateMemory.java
@@ -24,41 +24,38 @@ import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;
public class TestUserApiCreateMemory extends TestUserApiCreate {
-
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, new MockEngineModuleMemory());
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateWithRequestedDate() {
super.testCreateWithRequestedDate();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateWithInitialPhase() {
super.testSimpleSubscriptionThroughPhases();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testSimpleCreateSubscription() {
super.testSimpleCreateSubscription();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
protected void testSimpleSubscriptionThroughPhases() {
super.testSimpleSubscriptionThroughPhases();
}
@Override
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
protected void testSubscriptionWithAddOn() {
super.testSubscriptionWithAddOn();
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateSql.java
index ca3bc10..64c436a 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiCreateSql.java
@@ -24,32 +24,31 @@ import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleSql;
public class TestUserApiCreateSql extends TestUserApiCreate {
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCreateWithRequestedDate() {
super.testCreateWithRequestedDate();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testCreateWithInitialPhase() {
super.testCreateWithInitialPhase();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
public void testSimpleCreateSubscription() {
super.testSimpleCreateSubscription();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
protected void testSimpleSubscriptionThroughPhases() {
super.testSimpleSubscriptionThroughPhases();
}
@@ -59,5 +58,4 @@ public class TestUserApiCreateSql extends TestUserApiCreate {
protected void testSubscriptionWithAddOn() {
super.testSubscriptionWithAddOn();
}
-
}
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 49e7a59..d2d33c4 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
@@ -46,7 +46,6 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class TestUserApiDemos extends TestApiBase {
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
@@ -67,10 +66,8 @@ public class TestUserApiDemos extends TestApiBase {
* 7. Move to next Phase
* 8. Cancel EOT
*/
- @Test(enabled = true, groups = "demos")
+ @Test(enabled = false, groups = {"slow", "demos"})
public void testDemo1() throws EntitlementBillingApiException {
-
- log.info("Starting testSubscriptionWithAddOn");
try {
System.out.println("DEMO 1 START");
@@ -173,15 +170,12 @@ public class TestUserApiDemos extends TestApiBase {
}
-
private void displayState(final UUID subscriptionId, final String stepMsg) {
-
System.out.println("");
System.out.println("******\t STEP " + stepMsg + " **************");
try {
final SubscriptionData subscription = (SubscriptionData) entitlementApi.getSubscriptionFromId(subscriptionId);
-
final Plan currentPlan = subscription.getCurrentPlan();
final PlanPhase currentPhase = subscription.getCurrentPhase();
final String priceList = subscription.getCurrentPriceList().getName();
@@ -203,7 +197,7 @@ public class TestUserApiDemos extends TestApiBase {
}
- @Test(enabled = true, groups = {"stress"})
+ @Test(enabled = false, groups = {"slow", "stress"})
public void stressTest() throws Exception {
for (int i = 0; i < 100; i++) {
cleanupTest();
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiError.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiError.java
index fa947f1..afa82d0 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiError.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiError.java
@@ -42,24 +42,17 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class TestUserApiError extends TestApiBase {
-
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleMemory());
}
-
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionBadCatalog() {
-
- log.info("Starting testCreateSubscriptionBadCatalog");
-
// WRONG PRODUCTS
tCreateSubscriptionInternal(bundle.getId(), null, BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.CAT_NULL_PRODUCT_NAME);
tCreateSubscriptionInternal(bundle.getId(), "Whatever", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.CAT_NO_SUCH_PRODUCT);
-
// TODO: MARTIN TO FIX WITH CORRECT ERROR CODE. RIGHT NOW NPE
// WRONG BILLING PERIOD
@@ -69,33 +62,28 @@ public class TestUserApiError extends TestApiBase {
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionNoBundle() {
- log.info("Starting testCreateSubscriptionNoBundle");
tCreateSubscriptionInternal(null, "Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.ENT_CREATE_NO_BUNDLE);
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionNoBP() {
- log.info("Starting testCreateSubscriptionNoBP");
tCreateSubscriptionInternal(bundle.getId(), "Telescopic-Scope", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.ENT_CREATE_NO_BP);
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionBPExists() {
- log.info("Starting testCreateSubscriptionBPExists");
try {
createSubscription("Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME);
tCreateSubscriptionInternal(bundle.getId(), "Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.ENT_CREATE_BP_EXISTS);
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testRecreateSubscriptionBPNotCancelled() {
- log.info("Starting testRecreateSubscriptionBPNotCancelled");
try {
final SubscriptionData subscription = createSubscription("Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME);
try {
@@ -105,26 +93,23 @@ public class TestUserApiError extends TestApiBase {
assertEquals(e.getCode(), ErrorCode.ENT_RECREATE_BAD_STATE.getCode());
}
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionAddOnNotAvailable() {
- log.info("Starting testCreateSubscriptionAddOnNotAvailable");
try {
final UUID accountId = UUID.randomUUID();
final SubscriptionBundle aoBundle = entitlementApi.createBundleForAccount(accountId, "myAOBundle", context);
createSubscriptionWithBundle(aoBundle.getId(), "Pistol", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
tCreateSubscriptionInternal(aoBundle.getId(), "Telescopic-Scope", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.ENT_CREATE_AO_NOT_AVAILABLE);
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testCreateSubscriptionAddOnIncluded() {
log.info("Starting testCreateSubscriptionAddOnIncluded");
try {
@@ -133,12 +118,10 @@ public class TestUserApiError extends TestApiBase {
createSubscriptionWithBundle(aoBundle.getId(), "Assault-Rifle", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
tCreateSubscriptionInternal(aoBundle.getId(), "Telescopic-Scope", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, ErrorCode.ENT_CREATE_AO_ALREADY_INCLUDED);
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
-
private void tCreateSubscriptionInternal(@Nullable final UUID bundleId, @Nullable final String productName,
@Nullable final BillingPeriod term, final String planSet, final ErrorCode expected) {
try {
@@ -156,10 +139,8 @@ public class TestUserApiError extends TestApiBase {
}
}
-
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testChangeSubscriptionNonActive() {
- log.info("Starting testChangeSubscriptionNonActive");
try {
final Subscription subscription = createSubscription("Shotgun", BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME);
@@ -176,15 +157,12 @@ public class TestUserApiError extends TestApiBase {
}
}
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
-
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testChangeSubscriptionFutureCancelled() {
- log.info("Starting testChangeSubscriptionFutureCancelled");
try {
Subscription subscription = createSubscription("Shotgun", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
final PlanPhase trialPhase = subscription.getCurrentPhase();
@@ -196,7 +174,6 @@ public class TestUserApiError extends TestApiBase {
clock.addDeltaFromReality(it.toDurationMillis());
assertTrue(testListener.isCompleted(5000));
-
// SET CTD TO CANCEL IN FUTURE
final DateTime expectedPhaseTrialChange = DefaultClock.addDuration(subscription.getStartDate(), trialPhase.getDuration());
final Duration ctd = getDurationMonth(1);
@@ -219,20 +196,16 @@ public class TestUserApiError extends TestApiBase {
assertListenerStatus();
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
}
-
- @Test(enabled = false, groups = {"fast"})
+ @Test(enabled = false, groups = "fast")
public void testCancelBadState() {
- log.info("Starting testCancelBadState");
}
- @Test(enabled = true, groups = {"fast"})
+ @Test(groups = "fast")
public void testUncancelBadState() {
- log.info("Starting testUncancelBadState");
try {
final Subscription subscription = createSubscription("Shotgun", BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME);
@@ -248,10 +221,7 @@ public class TestUserApiError extends TestApiBase {
}
assertListenerStatus();
} catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
+ Assert.fail(e.toString());
}
-
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiPriceList.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiPriceList.java
index 36d699d..f2d7f22 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiPriceList.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiPriceList.java
@@ -20,18 +20,14 @@ import com.google.inject.Injector;
import com.ning.billing.entitlement.api.TestApiBase;
public class TestUserApiPriceList extends TestApiBase {
-
@Override
protected Injector getInjector() {
return null;
}
protected void testChangeDefaultToDiscountToDefault() {
-
}
protected void testChangeDiscountToDefaultoDiscount() {
-
}
-
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreate.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreate.java
index cd09fdf..d35c9f3 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreate.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreate.java
@@ -31,12 +31,9 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public abstract class TestUserApiRecreate extends TestApiBase {
-
private static final Logger log = LoggerFactory.getLogger(TestUserApiRecreate.class);
-
protected void testRecreateWithBPCanceledThroughSubscription() {
- log.info("Starting testRecreateWithBPCanceledThroughSubscription");
try {
testCreateAndRecreate(false);
assertListenerStatus();
@@ -47,7 +44,6 @@ public abstract class TestUserApiRecreate extends TestApiBase {
}
protected void testCreateWithBPCanceledFromUserApi() {
- log.info("Starting testCreateWithBPCanceledFromUserApi");
try {
testCreateAndRecreate(true);
assertListenerStatus();
@@ -57,9 +53,7 @@ public abstract class TestUserApiRecreate extends TestApiBase {
}
}
-
private SubscriptionData testCreateAndRecreate(final boolean fromUserAPi) throws EntitlementUserApiException {
-
final DateTime init = clock.getUTCNow();
final DateTime requestedDate = init.minusYears(1);
@@ -103,12 +97,11 @@ public abstract class TestUserApiRecreate extends TestApiBase {
testListener.pushExpectedEvent(NextEvent.PHASE);
testListener.pushExpectedEvent(NextEvent.RE_CREATE);
- // Avoid ordering issue for events at exact same date; this is actually a real good test, we
+ // Avoid ordering issue for events at exact same date; this is actually a real good test,
// we test it at Beatrix level. At this level that would work for sql tests but not for in memory.
try {
Thread.sleep(1000);
- } catch (InterruptedException e) {
-
+ } catch (InterruptedException ignored) {
}
if (fromUserAPi) {
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateMemory.java
index 3640b28..e033b2e 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateMemory.java
@@ -24,8 +24,6 @@ import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;
public class TestUserApiRecreateMemory extends TestUserApiRecreate {
-
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, new MockEngineModuleMemory());
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateSql.java
index 7b6217c..5dfcea1 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiRecreateSql.java
@@ -24,20 +24,19 @@ import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleSql;
public class TestUserApiRecreateSql extends TestUserApiRecreate {
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
protected void testRecreateWithBPCanceledThroughSubscription() {
super.testRecreateWithBPCanceledThroughSubscription();
}
@Override
- @Test(enabled = true, groups = {"slow"})
+ @Test(groups = "slow")
protected void testCreateWithBPCanceledFromUserApi() {
super.testRecreateWithBPCanceledThroughSubscription();
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiScenarios.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiScenarios.java
index 81aa23b..f679b73 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiScenarios.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/user/TestUserApiScenarios.java
@@ -39,17 +39,13 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
public class TestUserApiScenarios extends TestApiBase {
-
@Override
protected Injector getInjector() {
return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleSql());
}
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testChangeIMMCancelUncancelChangeEOT() throws EntitlementBillingApiException {
-
- log.info("Starting testChangeIMMCancelUncancelChangeEOT");
-
try {
SubscriptionData subscription = createSubscription("Assault-Rifle", BillingPeriod.MONTHLY, "gunclubDiscount");
final PlanPhase trialPhase = subscription.getCurrentPhase();
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoMemory.java
index ec5c17e..3479d0e 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoMemory.java
@@ -35,7 +35,6 @@ import com.google.inject.Inject;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.catalog.api.TimeUnit;
-import com.ning.billing.config.EntitlementConfig;
import com.ning.billing.entitlement.api.SubscriptionFactory;
import com.ning.billing.entitlement.api.migration.AccountMigrationData;
import com.ning.billing.entitlement.api.migration.AccountMigrationData.BundleMigrationData;
@@ -59,8 +58,7 @@ import com.ning.billing.util.notificationq.NotificationQueue;
import com.ning.billing.util.notificationq.NotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService.NoSuchNotificationQueue;
-public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlementDao {
-
+public class MockEntitlementDaoMemory implements EntitlementDao {
protected static final Logger log = LoggerFactory.getLogger(EntitlementDao.class);
private final List<SubscriptionBundle> bundles;
@@ -71,12 +69,11 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
private final CatalogService catalogService;
@Inject
- public MockEntitlementDaoMemory(final Clock clock, final EntitlementConfig config,
+ public MockEntitlementDaoMemory(final Clock clock,
final NotificationQueueService notificationQueueService,
final CatalogService catalogService) {
super();
this.clock = clock;
- final EntitlementConfig config1 = config;
this.catalogService = catalogService;
this.notificationQueueService = notificationQueueService;
this.bundles = new ArrayList<SubscriptionBundle>();
@@ -84,7 +81,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
this.events = new TreeSet<EntitlementEvent>();
}
- @Override
public void reset() {
bundles.clear();
subscriptions.clear();
@@ -154,7 +150,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
return Collections.emptyList();
}
-
@Override
public void createSubscription(final SubscriptionData subscription, final List<EntitlementEvent> initialEvents,
final CallContext context) {
@@ -169,7 +164,7 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
@Override
- public void recreateSubscription(final UUID subscriptionId,
+ public void recreateSubscription(final SubscriptionData subscription,
final List<EntitlementEvent> recreateEvents, final CallContext context) {
synchronized (events) {
@@ -220,7 +215,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
}
-
@Override
public Subscription getBaseSubscription(final SubscriptionFactory factory, final UUID bundleId) {
for (final Subscription cur : subscriptions) {
@@ -233,13 +227,12 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
@Override
- public void createNextPhaseEvent(final UUID subscriptionId, final EntitlementEvent nextPhase,
+ public void createNextPhaseEvent(final SubscriptionData subscription, final EntitlementEvent nextPhase,
final CallContext context) {
- cancelNextPhaseEvent(subscriptionId);
+ cancelNextPhaseEvent(subscription.getId());
insertEvent(nextPhase);
}
-
private Subscription buildSubscription(final SubscriptionFactory factory, final SubscriptionData in) {
if (factory != null) {
return factory.createSubscription(new SubscriptionBuilder(in), getEventsForSubscription(in.getId()));
@@ -271,20 +264,20 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
@Override
- public void cancelSubscription(final UUID subscriptionId, final EntitlementEvent cancelEvent,
+ public void cancelSubscription(final SubscriptionData subscription, final EntitlementEvent cancelEvent,
final CallContext context, final int seqId) {
synchronized (events) {
- cancelNextPhaseEvent(subscriptionId);
+ cancelNextPhaseEvent(subscription.getId());
insertEvent(cancelEvent);
}
}
@Override
- public void changePlan(final UUID subscriptionId, final List<EntitlementEvent> changeEvents,
+ public void changePlan(final SubscriptionData subscription, final List<EntitlementEvent> changeEvents,
final CallContext context) {
synchronized (events) {
- cancelNextChangeEvent(subscriptionId);
- cancelNextPhaseEvent(subscriptionId);
+ cancelNextChangeEvent(subscription.getId());
+ cancelNextPhaseEvent(subscription.getId());
events.addAll(changeEvents);
for (final EntitlementEvent cur : changeEvents) {
recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new EntitlementNotificationKey(cur.getId()));
@@ -299,7 +292,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
}
-
private void cancelNextPhaseEvent(final UUID subscriptionId) {
final Subscription curSubscription = getSubscriptionFromId(null, subscriptionId);
@@ -326,7 +318,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
}
-
private void cancelNextChangeEvent(final UUID subscriptionId) {
synchronized (events) {
@@ -348,7 +339,7 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
@Override
- public void uncancelSubscription(final UUID subscriptionId, final List<EntitlementEvent> uncancelEvents,
+ public void uncancelSubscription(final SubscriptionData subscription, final List<EntitlementEvent> uncancelEvents,
final CallContext context) {
synchronized (events) {
@@ -356,7 +347,7 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
final Iterator<EntitlementEvent> it = events.descendingIterator();
while (it.hasNext()) {
final EntitlementEvent cur = it.next();
- if (cur.getSubscriptionId() != subscriptionId) {
+ if (cur.getSubscriptionId() != subscription.getId()) {
continue;
}
if (cur.getType() == EventType.API_USER &&
@@ -374,7 +365,6 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
}
}
-
@Override
public void migrate(final UUID accountId, final AccountMigrationData accountData, final CallContext context) {
synchronized (events) {
@@ -410,18 +400,17 @@ public class MockEntitlementDaoMemory implements EntitlementDao, MockEntitlement
private void recordFutureNotificationFromTransaction(final Transmogrifier transactionalDao, final DateTime effectiveDate, final NotificationKey notificationKey) {
try {
final NotificationQueue subscriptionEventQueue = notificationQueueService.getNotificationQueue(Engine.ENTITLEMENT_SERVICE_NAME,
- Engine.NOTIFICATION_QUEUE_NAME);
- subscriptionEventQueue.recordFutureNotificationFromTransaction(transactionalDao, effectiveDate, notificationKey);
+ Engine.NOTIFICATION_QUEUE_NAME);
+ subscriptionEventQueue.recordFutureNotificationFromTransaction(transactionalDao, effectiveDate, null, notificationKey);
} catch (NoSuchNotificationQueue e) {
throw new RuntimeException(e);
} catch (IOException e) {
- throw new RuntimeException(e);
+ throw new RuntimeException(e);
}
}
@Override
public Map<UUID, List<EntitlementEvent>> getEventsForBundle(final UUID bundleId) {
- // TODO Auto-generated method stub
return null;
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoSql.java
index 929f03d..0c104fc 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/engine/dao/MockEntitlementDaoSql.java
@@ -17,63 +17,18 @@
package com.ning.billing.entitlement.engine.dao;
import org.skife.jdbi.v2.IDBI;
-import org.skife.jdbi.v2.Transaction;
-import org.skife.jdbi.v2.TransactionStatus;
-import org.skife.jdbi.v2.sqlobject.SqlUpdate;
-import org.skife.jdbi.v2.sqlobject.mixins.CloseMe;
-import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
import com.google.inject.Inject;
+import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.entitlement.engine.addon.AddonUtils;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.notificationq.NotificationQueueService;
-public class MockEntitlementDaoSql extends AuditedEntitlementDao implements MockEntitlementDao {
-
- private final ResetSqlDao resetDao;
-
+public class MockEntitlementDaoSql extends AuditedEntitlementDao {
@Inject
public MockEntitlementDaoSql(final IDBI dbi, final Clock clock, final AddonUtils addonUtils, final NotificationQueueService notificationQueueService,
- final Bus eventBus) {
- super(dbi, clock, addonUtils, notificationQueueService, eventBus);
- this.resetDao = dbi.onDemand(ResetSqlDao.class);
- }
-
-
- @Override
- public void reset() {
- resetDao.inTransaction(new Transaction<Void, ResetSqlDao>() {
-
- @Override
- public Void inTransaction(final ResetSqlDao dao, final TransactionStatus status)
- throws Exception {
- resetDao.resetEvents();
- resetDao.resetSubscriptions();
- resetDao.resetBundles();
- resetDao.resetClaimedNotifications();
- resetDao.resetNotifications();
- return null;
- }
- });
- }
-
- public static interface ResetSqlDao extends Transactional<ResetSqlDao>, CloseMe {
-
- @SqlUpdate("truncate table subscription_events")
- public void resetEvents();
-
- @SqlUpdate("truncate table subscriptions")
- public void resetSubscriptions();
-
- @SqlUpdate("truncate table bundles")
- public void resetBundles();
-
- @SqlUpdate("truncate table notifications")
- public void resetNotifications();
-
- @SqlUpdate("truncate table claimed_notifications")
- public void resetClaimedNotifications();
-
+ final Bus eventBus, final CatalogService catalogService) {
+ super(dbi, clock, addonUtils, notificationQueueService, eventBus, catalogService);
}
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuite.java b/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuite.java
new file mode 100644
index 0000000..e839150
--- /dev/null
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.entitlement;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class EntitlementTestSuite extends KillbillTestSuite {
+}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuiteWithEmbeddedDB.java b/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..0537107
--- /dev/null
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/EntitlementTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.entitlement;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class EntitlementTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModule.java b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModule.java
index 844bf90..dd48560 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModule.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModule.java
@@ -16,20 +16,19 @@
package com.ning.billing.entitlement.glue;
+import org.mockito.Mockito;
+
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.catalog.glue.CatalogModule;
-import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.util.glue.CallContextModule;
public class MockEngineModule extends DefaultEntitlementModule {
-
-
@Override
protected void configure() {
super.configure();
install(new CatalogModule());
- bind(AccountUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class));
+ bind(AccountUserApi.class).toInstance(Mockito.mock(AccountUserApi.class));
install(new MockClockModule());
install(new CallContextModule());
}
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleMemory.java b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleMemory.java
index 148b62d..13a9012 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleMemory.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleMemory.java
@@ -16,7 +16,6 @@
package com.ning.billing.entitlement.glue;
-
import com.google.inject.name.Names;
import com.ning.billing.entitlement.api.timeline.RepairEntitlementLifecycleDao;
import com.ning.billing.entitlement.engine.dao.EntitlementDao;
@@ -28,7 +27,6 @@ import com.ning.billing.util.notificationq.MockNotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService;
public class MockEngineModuleMemory extends MockEngineModule {
-
@Override
protected void installEntitlementDao() {
bind(EntitlementDao.class).to(MockEntitlementDaoMemory.class).asEagerSingleton();
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleSql.java b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleSql.java
index 51a55a0..fd3d266 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleSql.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/glue/MockEngineModuleSql.java
@@ -16,11 +16,11 @@
package com.ning.billing.entitlement.glue;
-
import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import com.google.inject.name.Names;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
@@ -34,8 +34,6 @@ import com.ning.billing.util.glue.CustomFieldModule;
import com.ning.billing.util.glue.NotificationQueueModule;
public class MockEngineModuleSql extends MockEngineModule {
-
-
@Override
protected void installEntitlementDao() {
bind(EntitlementDao.class).to(MockEntitlementDaoSql.class).asEagerSingleton();
@@ -44,9 +42,8 @@ public class MockEngineModuleSql extends MockEngineModule {
bind(RepairEntitlementDao.class).asEagerSingleton();
}
-
protected void installDBI() {
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
invoice/pom.xml 2(+1 -1)
diff --git a/invoice/pom.xml b/invoice/pom.xml
index 07f9191..596f296 100644
--- a/invoice/pom.xml
+++ b/invoice/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-invoice</artifactId>
diff --git a/invoice/src/main/java/com/ning/billing/invoice/api/invoice/DefaultInvoicePaymentApi.java b/invoice/src/main/java/com/ning/billing/invoice/api/invoice/DefaultInvoicePaymentApi.java
index a93ee28..dfb40b4 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/api/invoice/DefaultInvoicePaymentApi.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/api/invoice/DefaultInvoicePaymentApi.java
@@ -28,6 +28,7 @@ import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.invoice.api.InvoicePayment;
+import com.ning.billing.invoice.api.InvoicePayment.InvoicePaymentType;
import com.ning.billing.invoice.api.InvoicePaymentApi;
import com.ning.billing.invoice.dao.InvoiceDao;
import com.ning.billing.invoice.model.DefaultInvoicePayment;
@@ -42,8 +43,8 @@ public class DefaultInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context) {
- dao.notifyOfPaymentAttempt(invoicePayment, context);
+ public void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context) {
+ dao.notifyOfPayment(invoicePayment, context);
}
@Override
@@ -57,39 +58,30 @@ public class DefaultInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public Invoice getInvoiceForPaymentAttemptId(final UUID paymentAttemptId) {
- final UUID invoiceIdStr = dao.getInvoiceIdByPaymentAttemptId(paymentAttemptId);
+ public Invoice getInvoiceForPaymentId(final UUID paymentId) {
+ final UUID invoiceIdStr = dao.getInvoiceIdByPaymentId(paymentId);
return invoiceIdStr == null ? null : dao.getById(invoiceIdStr);
}
@Override
- public InvoicePayment getInvoicePayment(final UUID paymentAttemptId) {
- return dao.getInvoicePayment(paymentAttemptId);
+ public InvoicePayment getInvoicePayment(final UUID paymentId) {
+ return dao.getInvoicePayment(paymentId);
}
@Override
- public void notifyOfPaymentAttempt(final UUID invoiceId, final BigDecimal amount, final Currency currency, final UUID paymentAttemptId, final DateTime paymentAttemptDate, final CallContext context) {
- final InvoicePayment invoicePayment = new DefaultInvoicePayment(paymentAttemptId, invoiceId, paymentAttemptDate, amount, currency);
- dao.notifyOfPaymentAttempt(invoicePayment, context);
+ public void notifyOfPayment(final UUID invoiceId, final BigDecimal amount, final Currency currency, final UUID paymentId, final DateTime paymentDate, final CallContext context) {
+ final InvoicePayment invoicePayment = new DefaultInvoicePayment(InvoicePaymentType.ATTEMPT, paymentId, invoiceId, paymentDate, amount, currency);
+ dao.notifyOfPayment(invoicePayment, context);
}
@Override
- public void notifyOfPaymentAttempt(final UUID invoiceId, final UUID paymentAttemptId, final DateTime paymentAttemptDate, final CallContext context) {
- final InvoicePayment invoicePayment = new DefaultInvoicePayment(paymentAttemptId, invoiceId, paymentAttemptDate);
- dao.notifyOfPaymentAttempt(invoicePayment, context);
- }
-
- @Override
- public InvoicePayment processChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException {
+ public InvoicePayment createChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException {
return dao.postChargeback(invoicePaymentId, amount, context);
}
@Override
- public InvoicePayment processChargeback(final UUID invoicePaymentId, final CallContext context) throws InvoiceApiException {
- // use the invoicePaymentId to get the amount remaining on the payment
- // (preventing charge backs totalling more than the payment)
- final BigDecimal amount = dao.getRemainingAmountPaid(invoicePaymentId);
- return processChargeback(invoicePaymentId, amount, context);
+ public InvoicePayment createChargeback(final UUID invoicePaymentId, final CallContext context) throws InvoiceApiException {
+ return createChargeback(invoicePaymentId, null, context);
}
@Override
@@ -103,8 +95,8 @@ public class DefaultInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public List<InvoicePayment> getChargebacksByPaymentAttemptId(final UUID paymentAttemptId) {
- return dao.getChargebacksByPaymentAttemptId(paymentAttemptId);
+ public List<InvoicePayment> getChargebacksByPaymentId(final UUID paymentId) {
+ return dao.getChargebacksByPaymentId(paymentId);
}
@Override
@@ -116,4 +108,10 @@ public class DefaultInvoicePaymentApi implements InvoicePaymentApi {
public UUID getAccountIdFromInvoicePaymentId(final UUID invoicePaymentId) throws InvoiceApiException {
return dao.getAccountIdFromInvoicePaymentId(invoicePaymentId);
}
+
+ @Override
+ public InvoicePayment createRefund(final UUID paymentId, final BigDecimal amount, final boolean isInvoiceAdjusted,
+ final UUID paymentCookieId, final CallContext context) throws InvoiceApiException {
+ return dao.createRefund(paymentId, amount, isInvoiceAdjusted, paymentCookieId, context);
+ }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/api/migration/DefaultInvoiceMigrationApi.java b/invoice/src/main/java/com/ning/billing/invoice/api/migration/DefaultInvoiceMigrationApi.java
index 9e9b95c..67d3c77 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/api/migration/DefaultInvoiceMigrationApi.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/api/migration/DefaultInvoiceMigrationApi.java
@@ -20,8 +20,13 @@ import java.math.BigDecimal;
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.AccountUserApi;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
@@ -35,23 +40,35 @@ import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.Clock;
public class DefaultInvoiceMigrationApi implements InvoiceMigrationApi {
+ private static final Logger log = LoggerFactory.getLogger(DefaultInvoiceMigrationApi.class);
+ private final AccountUserApi accountUserApi;
private final DefaultInvoiceDao dao;
private final Clock clock;
@Inject
- public DefaultInvoiceMigrationApi(final DefaultInvoiceDao dao, final Clock clock) {
+ public DefaultInvoiceMigrationApi(final AccountUserApi accountUserApi, final DefaultInvoiceDao dao, final Clock clock) {
+ this.accountUserApi = accountUserApi;
this.dao = dao;
this.clock = clock;
}
@Override
public UUID createMigrationInvoice(final UUID accountId, final DateTime targetDate, final BigDecimal balance, final Currency currency) {
+ final Account account;
+ try {
+ account = accountUserApi.getAccountById(accountId);
+ } catch (AccountApiException e) {
+ log.warn("Unable to find account for id {}", accountId);
+ return null;
+ }
+
final CallContext context = new DefaultCallContextFactory(clock).createMigrationCallContext("Migration", CallOrigin.INTERNAL, UserType.MIGRATION, clock.getUTCNow(), clock.getUTCNow());
final Invoice migrationInvoice = new MigrationInvoice(accountId, clock.getUTCNow(), targetDate, currency);
final InvoiceItem migrationInvoiceItem = new MigrationInvoiceItem(migrationInvoice.getId(), accountId, targetDate, balance, currency);
migrationInvoice.addInvoiceItem(migrationInvoiceItem);
- dao.create(migrationInvoice, context);
+
+ dao.create(migrationInvoice, account.getBillCycleDay(), context);
return migrationInvoice.getId();
}
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/api/user/DefaultInvoiceUserApi.java b/invoice/src/main/java/com/ning/billing/invoice/api/user/DefaultInvoiceUserApi.java
index 4245ba8..0a6a8f1 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/api/user/DefaultInvoiceUserApi.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/api/user/DefaultInvoiceUserApi.java
@@ -65,8 +65,8 @@ public class DefaultInvoiceUserApi implements InvoiceUserApi {
}
@Override
- public void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context) {
- dao.notifyOfPaymentAttempt(invoicePayment, context);
+ public void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context) {
+ dao.notifyOfPayment(invoicePayment, context);
}
@Override
@@ -89,7 +89,7 @@ public class DefaultInvoiceUserApi implements InvoiceUserApi {
public Invoice triggerInvoiceGeneration(final UUID accountId,
final DateTime targetDate, final boolean dryRun,
final CallContext context) throws InvoiceApiException {
- Invoice result = dispatcher.processAccount(accountId, targetDate, dryRun, context);
+ final Invoice result = dispatcher.processAccount(accountId, targetDate, dryRun, context);
if (result == null) {
throw new InvoiceApiException(ErrorCode.INVOICE_NOTHING_TO_DO, accountId, targetDate);
} else {
@@ -115,10 +115,18 @@ public class DefaultInvoiceUserApi implements InvoiceUserApi {
@Override
public InvoiceItem insertCredit(final UUID accountId, final BigDecimal amount, final DateTime effectiveDate,
final Currency currency, final CallContext context) throws InvoiceApiException {
- return dao.insertCredit(accountId, amount, effectiveDate, currency, context);
+ return dao.insertCredit(accountId, null, amount, effectiveDate, currency, context);
}
@Override
+ public InvoiceItem insertCreditForInvoice(UUID accountId, UUID invoiceId,
+ BigDecimal amount, DateTime effectiveDate, Currency currency,
+ CallContext context) throws InvoiceApiException {
+ return dao.insertCredit(accountId, invoiceId, amount, effectiveDate, currency, context);
+ }
+
+
+ @Override
public String getInvoiceAsHTML(final UUID invoiceId) throws AccountApiException, IOException, InvoiceApiException {
final Invoice invoice = getInvoice(invoiceId);
if (invoice == null) {
diff --git a/invoice/src/main/java/com/ning/billing/invoice/dao/DefaultInvoiceDao.java b/invoice/src/main/java/com/ning/billing/invoice/dao/DefaultInvoiceDao.java
index 7102051..fe88a63 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/dao/DefaultInvoiceDao.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/dao/DefaultInvoiceDao.java
@@ -18,6 +18,7 @@ package com.ning.billing.invoice.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import java.util.UUID;
@@ -26,17 +27,23 @@ import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.Transaction;
import org.skife.jdbi.v2.TransactionStatus;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
import com.google.inject.Inject;
import com.ning.billing.ErrorCode;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.invoice.api.InvoiceItem;
+import com.ning.billing.invoice.api.InvoiceItemType;
import com.ning.billing.invoice.api.InvoicePayment;
-import com.ning.billing.invoice.model.CreditInvoiceItem;
+import com.ning.billing.invoice.api.InvoicePayment.InvoicePaymentType;
+import com.ning.billing.invoice.model.CreditAdjInvoiceItem;
+import com.ning.billing.invoice.model.CreditBalanceAdjInvoiceItem;
import com.ning.billing.invoice.model.DefaultInvoice;
-import com.ning.billing.invoice.model.FixedPriceInvoiceItem;
+import com.ning.billing.invoice.model.DefaultInvoicePayment;
import com.ning.billing.invoice.model.RecurringInvoiceItem;
+import com.ning.billing.invoice.model.RefundAdjInvoiceItem;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.util.ChangeType;
import com.ning.billing.util.api.TagApiException;
@@ -50,9 +57,9 @@ import com.ning.billing.util.tag.ControlTagType;
public class DefaultInvoiceDao implements InvoiceDao {
private final InvoiceSqlDao invoiceSqlDao;
private final InvoicePaymentSqlDao invoicePaymentSqlDao;
- private final CreditInvoiceItemSqlDao creditInvoiceItemSqlDao;
private final TagUserApi tagUserApi;
private final NextBillingDatePoster nextBillingDatePoster;
+ private final InvoiceItemSqlDao invoiceItemSqlDao;
@Inject
public DefaultInvoiceDao(final IDBI dbi,
@@ -60,7 +67,7 @@ public class DefaultInvoiceDao implements InvoiceDao {
final TagUserApi tagUserApi) {
this.invoiceSqlDao = dbi.onDemand(InvoiceSqlDao.class);
this.invoicePaymentSqlDao = dbi.onDemand(InvoicePaymentSqlDao.class);
- this.creditInvoiceItemSqlDao = dbi.onDemand(CreditInvoiceItemSqlDao.class);
+ this.invoiceItemSqlDao = dbi.onDemand(InvoiceItemSqlDao.class);
this.nextBillingDatePoster = nextBillingDatePoster;
this.tagUserApi = tagUserApi;
}
@@ -71,9 +78,7 @@ public class DefaultInvoiceDao implements InvoiceDao {
@Override
public List<Invoice> inTransaction(final InvoiceSqlDao invoiceDao, final TransactionStatus status) throws Exception {
final List<Invoice> invoices = invoiceDao.getInvoicesByAccount(accountId.toString());
-
populateChildren(invoices, invoiceDao);
-
return invoices;
}
});
@@ -84,11 +89,7 @@ public class DefaultInvoiceDao implements InvoiceDao {
return invoiceSqlDao.inTransaction(new Transaction<List<Invoice>, InvoiceSqlDao>() {
@Override
public List<Invoice> inTransaction(final InvoiceSqlDao invoiceDao, final TransactionStatus status) throws Exception {
- final List<Invoice> invoices = invoiceDao.getAllInvoicesByAccount(accountId.toString());
-
- populateChildren(invoices, invoiceDao);
-
- return invoices;
+ return getAllInvoicesByAccountFromTransaction(accountId, invoiceDao);
}
});
}
@@ -138,14 +139,11 @@ public class DefaultInvoiceDao implements InvoiceDao {
}
@Override
- public void create(final Invoice invoice, final CallContext context) {
+ public void create(final Invoice invoice, final int billCycleDay, final CallContext context) {
invoiceSqlDao.inTransaction(new Transaction<Void, InvoiceSqlDao>() {
@Override
public Void inTransaction(final InvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
-
- // STEPH this seems useless
final Invoice currentInvoice = transactional.getById(invoice.getId().toString());
-
if (currentInvoice == null) {
final List<EntityAudit> audits = new ArrayList<EntityAudit>();
@@ -155,25 +153,14 @@ public class DefaultInvoiceDao implements InvoiceDao {
List<Long> recordIdList;
- final List<InvoiceItem> recurringInvoiceItems = invoice.getInvoiceItems(RecurringInvoiceItem.class);
- final RecurringInvoiceItemSqlDao recurringInvoiceItemDao = transactional.become(RecurringInvoiceItemSqlDao.class);
- recurringInvoiceItemDao.batchCreateFromTransaction(recurringInvoiceItems, context);
- recordIdList = recurringInvoiceItemDao.getRecordIds(invoice.getId().toString());
- audits.addAll(createAudits(TableName.RECURRING_INVOICE_ITEMS, recordIdList));
-
- notifyOfFutureBillingEvents(transactional, recurringInvoiceItems);
+ final List<InvoiceItem> invoiceItems = invoice.getInvoiceItems();
+ final InvoiceItemSqlDao transInvoiceItemSqlDao = transactional.become(InvoiceItemSqlDao.class);
+ transInvoiceItemSqlDao.batchCreateFromTransaction(invoiceItems, context);
+ recordIdList = transInvoiceItemSqlDao.getRecordIds(invoice.getId().toString());
+ audits.addAll(createAudits(TableName.INVOICE_ITEMS, recordIdList));
- final List<InvoiceItem> fixedPriceInvoiceItems = invoice.getInvoiceItems(FixedPriceInvoiceItem.class);
- final FixedPriceInvoiceItemSqlDao fixedPriceInvoiceItemDao = transactional.become(FixedPriceInvoiceItemSqlDao.class);
- fixedPriceInvoiceItemDao.batchCreateFromTransaction(fixedPriceInvoiceItems, context);
- recordIdList = fixedPriceInvoiceItemDao.getRecordIds(invoice.getId().toString());
- audits.addAll(createAudits(TableName.FIXED_INVOICE_ITEMS, recordIdList));
-
- final List<InvoiceItem> creditInvoiceItems = invoice.getInvoiceItems(CreditInvoiceItem.class);
- final CreditInvoiceItemSqlDao creditInvoiceItemSqlDao = transactional.become(CreditInvoiceItemSqlDao.class);
- creditInvoiceItemSqlDao.batchCreateFromTransaction(creditInvoiceItems, context);
- recordIdList = creditInvoiceItemSqlDao.getRecordIds(invoice.getId().toString());
- audits.addAll(createAudits(TableName.CREDIT_INVOICE_ITEMS, recordIdList));
+ final List<InvoiceItem> recurringInvoiceItems = invoice.getInvoiceItems(RecurringInvoiceItem.class);
+ notifyOfFutureBillingEvents(transactional, invoice.getAccountId(), billCycleDay, recurringInvoiceItems);
final List<InvoicePayment> invoicePayments = invoice.getPayments();
final InvoicePaymentSqlDao invoicePaymentSqlDao = transactional.become(InvoicePaymentSqlDao.class);
@@ -183,7 +170,6 @@ public class DefaultInvoiceDao implements InvoiceDao {
transactional.insertAuditFromTransaction(audits, context);
}
-
return null;
}
});
@@ -214,15 +200,39 @@ public class DefaultInvoiceDao implements InvoiceDao {
@Override
public BigDecimal getAccountBalance(final UUID accountId) {
- return invoiceSqlDao.getAccountBalance(accountId.toString());
+
+ return invoiceSqlDao.inTransaction(new Transaction<BigDecimal, InvoiceSqlDao>() {
+ @Override
+ public BigDecimal inTransaction(final InvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
+ BigDecimal cba = BigDecimal.ZERO;
+
+ BigDecimal accountBalance = BigDecimal.ZERO;
+ final List<Invoice> invoices = getAllInvoicesByAccountFromTransaction(accountId, transactional);
+ for (final Invoice cur : invoices) {
+ accountBalance = accountBalance.add(cur.getBalance());
+ cba = cba.add(cur.getCBAAmount());
+ }
+ return accountBalance.subtract(cba);
+ }
+ });
+ }
+
+ @Override
+ public BigDecimal getAccountCBA(final UUID accountId) {
+ return invoiceSqlDao.inTransaction(new Transaction<BigDecimal, InvoiceSqlDao>() {
+ @Override
+ public BigDecimal inTransaction(final InvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
+ return getAccountCBAFromTransaction(accountId, transactional);
+ }
+ });
}
@Override
- public void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context) {
+ public void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context) {
invoicePaymentSqlDao.inTransaction(new Transaction<Void, InvoicePaymentSqlDao>() {
@Override
public Void inTransaction(final InvoicePaymentSqlDao transactional, final TransactionStatus status) throws Exception {
- transactional.notifyOfPaymentAttempt(invoicePayment, context);
+ transactional.notifyOfPayment(invoicePayment, context);
final String invoicePaymentId = invoicePayment.getId().toString();
final Long recordId = transactional.getRecordId(invoicePaymentId);
@@ -239,23 +249,27 @@ public class DefaultInvoiceDao implements InvoiceDao {
return invoiceSqlDao.inTransaction(new Transaction<List<Invoice>, InvoiceSqlDao>() {
@Override
public List<Invoice> inTransaction(final InvoiceSqlDao invoiceDao, final TransactionStatus status) throws Exception {
- final List<Invoice> invoices = invoiceSqlDao.getUnpaidInvoicesByAccountId(accountId.toString(), upToDate.toDate());
-
- populateChildren(invoices, invoiceDao);
- return invoices;
+ final List<Invoice> invoices = getAllInvoicesByAccountFromTransaction(accountId, invoiceDao);
+ final Collection<Invoice> unpaidInvoices = Collections2.filter(invoices, new Predicate<Invoice>() {
+ @Override
+ public boolean apply(final Invoice in) {
+ return (in.getBalance().compareTo(BigDecimal.ZERO) >= 1) && !in.getTargetDate().isAfter(upToDate);
+ }
+ });
+ return new ArrayList<Invoice>(unpaidInvoices);
}
});
}
@Override
- public UUID getInvoiceIdByPaymentAttemptId(final UUID paymentAttemptId) {
- return invoiceSqlDao.getInvoiceIdByPaymentAttemptId(paymentAttemptId.toString());
+ public UUID getInvoiceIdByPaymentId(final UUID paymentId) {
+ return invoiceSqlDao.getInvoiceIdByPaymentId(paymentId.toString());
}
@Override
- public InvoicePayment getInvoicePayment(final UUID paymentAttemptId) {
- return invoicePaymentSqlDao.getInvoicePayment(paymentAttemptId.toString());
+ public InvoicePayment getInvoicePayment(final UUID paymentId) {
+ return invoicePaymentSqlDao.getInvoicePayment(paymentId.toString());
}
@Override
@@ -269,21 +283,97 @@ public class DefaultInvoiceDao implements InvoiceDao {
}
@Override
+ public InvoicePayment createRefund(final UUID paymentId, final BigDecimal amount, final boolean isInvoiceAdjusted, final UUID paymentCookieId, final CallContext context)
+ throws InvoiceApiException {
+ return invoicePaymentSqlDao.inTransaction(new Transaction<InvoicePayment, InvoicePaymentSqlDao>() {
+ @Override
+ public InvoicePayment inTransaction(final InvoicePaymentSqlDao transactional, final TransactionStatus status) throws Exception {
+
+ final InvoicePayment payment = transactional.getByPaymentId(paymentId.toString());
+ if (payment == null) {
+ throw new InvoiceApiException(ErrorCode.INVOICE_PAYMENT_BY_ATTEMPT_NOT_FOUND, paymentId);
+ }
+ final BigDecimal maxRefundAmount = payment.getAmount() == null ? BigDecimal.ZERO : payment.getAmount();
+ final BigDecimal requestedAmount = amount == null ? maxRefundAmount : amount;
+ if (requestedAmount.compareTo(BigDecimal.ZERO) >= 0) {
+ throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_IS_POSITIVE);
+ }
+
+ // Now that we checked signs, let's work with positive numbers, this makes things simpler
+ final BigDecimal requestedPositiveAmount = requestedAmount.negate();
+ if (requestedPositiveAmount.compareTo(maxRefundAmount) > 0) {
+ throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_TOO_HIGH, requestedPositiveAmount, maxRefundAmount);
+ }
+
+ // Before we go further, check if that refund already got inserted
+ final InvoicePayment existingRefund = transactional.getPaymentsForCookieId(paymentCookieId.toString());
+ if (existingRefund != null) {
+ return existingRefund;
+ }
+
+ final InvoicePayment refund = new DefaultInvoicePayment(UUID.randomUUID(), InvoicePaymentType.REFUND, paymentId,
+ payment.getInvoiceId(), context.getCreatedDate(), requestedPositiveAmount.negate(),
+ payment.getCurrency(), paymentCookieId, payment.getId());
+ transactional.create(refund, context);
+
+ // Retrieve invoice after the Refund
+ final InvoiceSqlDao transInvoiceDao = transactional.become(InvoiceSqlDao.class);
+ final Invoice invoice = transInvoiceDao.getById(payment.getInvoiceId().toString());
+ if (invoice != null) {
+ populateChildren(invoice, transInvoiceDao);
+ } else {
+ throw new IllegalStateException("Invoice shouldn't be null for payment " + payment.getId());
+ }
+
+ final BigDecimal invoiceBalanceAfterRefund = invoice.getBalance();
+ final InvoiceItemSqlDao transInvoiceItemDao = transInvoiceDao.become(InvoiceItemSqlDao.class);
+
+ // If we have an existing CBA > 0, we need to adjust it
+ //final BigDecimal cbaAmountAfterRefund = invoice.getCBAAmount();
+ final BigDecimal accountCbaAvailable = getAccountCBAFromTransaction(invoice.getAccountId(), transInvoiceDao);
+ BigDecimal cbaAdjAmount = BigDecimal.ZERO;
+ if (accountCbaAvailable.compareTo(BigDecimal.ZERO) > 0) {
+ cbaAdjAmount = (requestedPositiveAmount.compareTo(accountCbaAvailable) > 0) ? accountCbaAvailable.negate() : requestedPositiveAmount.negate();
+ final InvoiceItem cbaAdjItem = new CreditBalanceAdjInvoiceItem(invoice.getId(), invoice.getAccountId(), context.getCreatedDate(), cbaAdjAmount, invoice.getCurrency());
+ transInvoiceItemDao.create(cbaAdjItem, context);
+ }
+ final BigDecimal requestedPositiveAmountAfterCbaAdj = requestedPositiveAmount.add(cbaAdjAmount);
+
+ if (isInvoiceAdjusted) {
+ final BigDecimal maxBalanceToAdjust = (invoiceBalanceAfterRefund.compareTo(BigDecimal.ZERO) <= 0) ? BigDecimal.ZERO : invoiceBalanceAfterRefund;
+ final BigDecimal requestedPositiveAmountToAdjust = requestedPositiveAmountAfterCbaAdj.compareTo(maxBalanceToAdjust) > 0 ? maxBalanceToAdjust : requestedPositiveAmountAfterCbaAdj;
+ if (requestedPositiveAmountToAdjust.compareTo(BigDecimal.ZERO) > 0) {
+ final InvoiceItem adjItem = new RefundAdjInvoiceItem(invoice.getId(), invoice.getAccountId(), context.getCreatedDate(), requestedPositiveAmountToAdjust.negate(), invoice.getCurrency());
+ transInvoiceItemDao.create(adjItem, context);
+ }
+ }
+ return refund;
+ }
+ });
+ }
+
+ @Override
public InvoicePayment postChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException {
+
return invoicePaymentSqlDao.inTransaction(new Transaction<InvoicePayment, InvoicePaymentSqlDao>() {
@Override
public InvoicePayment inTransaction(final InvoicePaymentSqlDao transactional, final TransactionStatus status) throws Exception {
+ final BigDecimal maxChargedBackAmount = getRemainingAmountPaidFromTransaction(invoicePaymentId, transactional);
+ final BigDecimal requestedChargedBackAmout = (amount == null) ? maxChargedBackAmount : amount;
+ if (requestedChargedBackAmout.compareTo(BigDecimal.ZERO) <= 0) {
+ throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_IS_NEGATIVE);
+ }
+ if (requestedChargedBackAmout.compareTo(maxChargedBackAmount) > 0) {
+ throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_TOO_HIGH, requestedChargedBackAmout, maxChargedBackAmount);
+ }
+
final InvoicePayment payment = invoicePaymentSqlDao.getById(invoicePaymentId.toString());
if (payment == null) {
throw new InvoiceApiException(ErrorCode.INVOICE_PAYMENT_NOT_FOUND, invoicePaymentId.toString());
} else {
- if (amount.compareTo(BigDecimal.ZERO) < 0) {
- throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_IS_NEGATIVE);
- }
-
- final InvoicePayment chargeBack = payment.asChargeBack(amount, context.getCreatedDate());
+ final InvoicePayment chargeBack = new DefaultInvoicePayment(UUID.randomUUID(), InvoicePaymentType.CHARGED_BACK, null,
+ payment.getInvoiceId(), context.getCreatedDate(), requestedChargedBackAmout.negate(), payment.getCurrency(), null, payment.getId());
invoicePaymentSqlDao.create(chargeBack, context);
-
return chargeBack;
}
}
@@ -292,8 +382,7 @@ public class DefaultInvoiceDao implements InvoiceDao {
@Override
public BigDecimal getRemainingAmountPaid(final UUID invoicePaymentId) {
- final BigDecimal amount = invoicePaymentSqlDao.getRemainingAmountPaid(invoicePaymentId.toString());
- return amount == null ? BigDecimal.ZERO : amount;
+ return getRemainingAmountPaidFromTransaction(invoicePaymentId, invoicePaymentSqlDao);
}
@Override
@@ -312,8 +401,8 @@ public class DefaultInvoiceDao implements InvoiceDao {
}
@Override
- public List<InvoicePayment> getChargebacksByPaymentAttemptId(final UUID paymentAttemptId) {
- return invoicePaymentSqlDao.getChargebacksByAttemptPaymentId(paymentAttemptId.toString());
+ public List<InvoicePayment> getChargebacksByPaymentId(final UUID paymentId) {
+ return invoicePaymentSqlDao.getChargebacksByPaymentId(paymentId.toString());
}
@Override
@@ -328,21 +417,30 @@ public class DefaultInvoiceDao implements InvoiceDao {
@Override
public InvoiceItem getCreditById(final UUID creditId) throws InvoiceApiException {
- return creditInvoiceItemSqlDao.getById(creditId.toString());
+ return invoiceItemSqlDao.getById(creditId.toString());
}
- // TODO: make this transactional
@Override
- public InvoiceItem insertCredit(final UUID accountId, final BigDecimal amount,
+ public InvoiceItem insertCredit(final UUID accountId, final UUID invoiceId, final BigDecimal amount,
final DateTime effectiveDate, final Currency currency,
final CallContext context) {
- final Invoice invoice = new DefaultInvoice(accountId, effectiveDate, effectiveDate, currency);
- invoiceSqlDao.create(invoice, context);
- final InvoiceItem credit = new CreditInvoiceItem(invoice.getId(), accountId, effectiveDate, amount, currency);
- creditInvoiceItemSqlDao.create(credit, context);
+ return invoiceSqlDao.inTransaction(new Transaction<InvoiceItem, InvoiceSqlDao>() {
+ @Override
+ public InvoiceItem inTransaction(final InvoiceSqlDao transactional, final TransactionStatus status) throws Exception {
+ UUID invoiceIdForRefund = invoiceId;
+ if (invoiceIdForRefund == null) {
+ final Invoice invoiceForRefund = new DefaultInvoice(accountId, effectiveDate, effectiveDate, currency);
+ transactional.create(invoiceForRefund, context);
+ invoiceIdForRefund = invoiceForRefund.getId();
+ }
- return credit;
+ final InvoiceItem credit = new CreditAdjInvoiceItem(invoiceIdForRefund, accountId, effectiveDate, amount, currency);
+ final InvoiceItemSqlDao transInvoiceItemDao = transactional.become(InvoiceItemSqlDao.class);
+ transInvoiceItemDao.create(credit, context);
+ return credit;
+ }
+ });
}
@Override
@@ -350,6 +448,16 @@ public class DefaultInvoiceDao implements InvoiceDao {
invoiceSqlDao.test();
}
+ private BigDecimal getAccountCBAFromTransaction(final UUID accountId, final InvoiceSqlDao transactional) {
+ BigDecimal cba = BigDecimal.ZERO;
+ final List<Invoice> invoices = getAllInvoicesByAccountFromTransaction(accountId, transactional);
+ for (final Invoice cur : invoices) {
+ cba = cba.add(cur.getCBAAmount());
+ }
+
+ return cba;
+ }
+
private void populateChildren(final Invoice invoice, final InvoiceSqlDao invoiceSqlDao) {
getInvoiceItemsWithinTransaction(invoice, invoiceSqlDao);
getInvoicePaymentsWithinTransaction(invoice, invoiceSqlDao);
@@ -360,26 +468,29 @@ public class DefaultInvoiceDao implements InvoiceDao {
getInvoicePaymentsWithinTransaction(invoices, invoiceSqlDao);
}
+ private List<Invoice> getAllInvoicesByAccountFromTransaction(final UUID accountId, final InvoiceSqlDao transactional) {
+ final List<Invoice> invoices = transactional.getAllInvoicesByAccount(accountId.toString());
+ populateChildren(invoices, transactional);
+ return invoices;
+ }
+
+ private BigDecimal getRemainingAmountPaidFromTransaction(final UUID invoicePaymentId, final InvoicePaymentSqlDao transactional) {
+ final BigDecimal amount = transactional.getRemainingAmountPaid(invoicePaymentId.toString());
+ return amount == null ? BigDecimal.ZERO : amount;
+ }
+
private void getInvoiceItemsWithinTransaction(final List<Invoice> invoices, final InvoiceSqlDao invoiceDao) {
for (final Invoice invoice : invoices) {
getInvoiceItemsWithinTransaction(invoice, invoiceDao);
}
}
- private void getInvoiceItemsWithinTransaction(final Invoice invoice, final InvoiceSqlDao invoiceDao) {
+ private void getInvoiceItemsWithinTransaction(final Invoice invoice, final InvoiceSqlDao transactional) {
final String invoiceId = invoice.getId().toString();
- final RecurringInvoiceItemSqlDao recurringInvoiceItemDao = invoiceDao.become(RecurringInvoiceItemSqlDao.class);
- final List<InvoiceItem> recurringInvoiceItems = recurringInvoiceItemDao.getInvoiceItemsByInvoice(invoiceId);
- invoice.addInvoiceItems(recurringInvoiceItems);
-
- final FixedPriceInvoiceItemSqlDao fixedPriceInvoiceItemDao = invoiceDao.become(FixedPriceInvoiceItemSqlDao.class);
- final List<InvoiceItem> fixedPriceInvoiceItems = fixedPriceInvoiceItemDao.getInvoiceItemsByInvoice(invoiceId);
- invoice.addInvoiceItems(fixedPriceInvoiceItems);
-
- final CreditInvoiceItemSqlDao creditInvoiceItemSqlDao = invoiceDao.become(CreditInvoiceItemSqlDao.class);
- final List<InvoiceItem> creditInvoiceItems = creditInvoiceItemSqlDao.getInvoiceItemsByInvoice(invoiceId);
- invoice.addInvoiceItems(creditInvoiceItems);
+ final InvoiceItemSqlDao transInvoiceItemSqlDao = transactional.become(InvoiceItemSqlDao.class);
+ final List<InvoiceItem> items = transInvoiceItemSqlDao.getInvoiceItemsByInvoice(invoiceId);
+ invoice.addInvoiceItems(items);
}
private void getInvoicePaymentsWithinTransaction(final List<Invoice> invoices, final InvoiceSqlDao invoiceDao) {
@@ -395,16 +506,36 @@ public class DefaultInvoiceDao implements InvoiceDao {
invoice.addPayments(invoicePayments);
}
- private void notifyOfFutureBillingEvents(final InvoiceSqlDao dao, final List<InvoiceItem> invoiceItems) {
+ private void notifyOfFutureBillingEvents(final InvoiceSqlDao dao, final UUID accountId, final int billCycleDay, final List<InvoiceItem> invoiceItems) {
+ DateTime nextBCD = null;
+ UUID subscriptionForNextBCD = null;
for (final InvoiceItem item : invoiceItems) {
- if (item instanceof RecurringInvoiceItem) {
+ if (item.getInvoiceItemType() == InvoiceItemType.RECURRING) {
final RecurringInvoiceItem recurringInvoiceItem = (RecurringInvoiceItem) item;
if ((recurringInvoiceItem.getEndDate() != null) &&
(recurringInvoiceItem.getAmount() == null ||
recurringInvoiceItem.getAmount().compareTo(BigDecimal.ZERO) >= 0)) {
- nextBillingDatePoster.insertNextBillingNotification(dao, item.getSubscriptionId(), recurringInvoiceItem.getEndDate());
+ if (nextBCD == null || nextBCD.compareTo(recurringInvoiceItem.getEndDate()) > 0) {
+ nextBCD = recurringInvoiceItem.getEndDate();
+ subscriptionForNextBCD = recurringInvoiceItem.getSubscriptionId();
+ }
}
}
}
+ // We need to be notified if and only if the maximum end date of the invoiced recurring items is equal
+ // to the next bill cycle day.
+ // We take the maximum because we're guaranteed to have invoiced all subscriptions up until that date
+ // (and no further processing is needed).
+ // Also, we only need to get notified on the BDC. For other invoice events (e.g. phase changes),
+ // we'll be notified by entitlement.
+ if (subscriptionForNextBCD != null && nextBCD != null) {
+ final int lastDayOfMonth = nextBCD.dayOfMonth().withMaximumValue().getDayOfMonth();
+ final int nextBCDDay = nextBCD.getDayOfMonth();
+ // Small trick here in case the bill cycle day doesn't exist for that month, e.g. the bill cycle day
+ // is on the 31st, but the month has only 30 days
+ if (nextBCDDay == billCycleDay || (lastDayOfMonth == nextBCDDay && billCycleDay > lastDayOfMonth)) {
+ nextBillingDatePoster.insertNextBillingNotification(dao, accountId, subscriptionForNextBCD, nextBCD);
+ }
+ }
}
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceDao.java b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceDao.java
index 888295a..1812ed1 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceDao.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceDao.java
@@ -31,7 +31,7 @@ import com.ning.billing.util.api.TagApiException;
import com.ning.billing.util.callcontext.CallContext;
public interface InvoiceDao {
- void create(Invoice invoice, CallContext context);
+ void create(final Invoice invoice, final int billCycleDay, final CallContext context);
Invoice getById(final UUID id);
@@ -43,14 +43,16 @@ public interface InvoiceDao {
List<Invoice> getInvoicesBySubscription(final UUID subscriptionId);
- UUID getInvoiceIdByPaymentAttemptId(final UUID paymentAttemptId);
+ UUID getInvoiceIdByPaymentId(final UUID paymentId);
- InvoicePayment getInvoicePayment(final UUID paymentAttemptId);
+ InvoicePayment getInvoicePayment(final UUID paymentId);
- void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context);
+ void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context);
BigDecimal getAccountBalance(final UUID accountId);
+ public BigDecimal getAccountCBA(final UUID accountId);
+
List<Invoice> getUnpaidInvoicesByAccountId(final UUID accountId, final DateTime upToDate);
void test();
@@ -63,19 +65,21 @@ public interface InvoiceDao {
InvoicePayment postChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException;
+ InvoicePayment createRefund(UUID paymentId, BigDecimal amount, boolean isInvoiceAdjusted, UUID paymentCookieId, CallContext context) throws InvoiceApiException;
+
BigDecimal getRemainingAmountPaid(final UUID invoicePaymentId);
UUID getAccountIdFromInvoicePaymentId(final UUID invoicePaymentId) throws InvoiceApiException;
List<InvoicePayment> getChargebacksByAccountId(final UUID accountId);
- List<InvoicePayment> getChargebacksByPaymentAttemptId(final UUID paymentAttemptId);
+ List<InvoicePayment> getChargebacksByPaymentId(final UUID paymentId);
InvoicePayment getChargebackById(final UUID chargebackId) throws InvoiceApiException;
InvoiceItem getCreditById(final UUID creditId) throws InvoiceApiException;
- InvoiceItem insertCredit(final UUID accountId, final BigDecimal amount,
- final DateTime effectiveDate, final Currency currency,
- final CallContext context);
+ InvoiceItem insertCredit(final UUID accountId, final UUID invoiceId, final BigDecimal amount,
+ final DateTime effectiveDate, final Currency currency, final CallContext context);
+
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.java b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.java
index 8b12f8d..4a9f143 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.java
@@ -45,6 +45,7 @@ import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.InvoicePayment;
+import com.ning.billing.invoice.api.InvoicePayment.InvoicePaymentType;
import com.ning.billing.invoice.model.DefaultInvoicePayment;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallContextBinder;
@@ -61,28 +62,30 @@ public interface InvoicePaymentSqlDao extends EntitySqlDao<InvoicePayment>, Tran
List<Long> getRecordIds(@Bind("invoiceId") final String invoiceId);
@SqlQuery
- public InvoicePayment getByPaymentAttemptId(@Bind("paymentAttempt") final String paymentAttemptId);
+ public InvoicePayment getByPaymentId(@Bind("paymentId") final String paymentId);
+ @Override
@SqlQuery
public List<InvoicePayment> get();
+ @Override
@SqlUpdate
- public void create(@InvoicePaymentBinder final InvoicePayment invoicePayment,
- @CallContextBinder final CallContext context);
+ public void create(@InvoicePaymentBinder final InvoicePayment invoicePayment, @CallContextBinder final CallContext context);
@SqlBatch(transactional = false)
- void batchCreateFromTransaction(@InvoicePaymentBinder final List<InvoicePayment> items,
- @CallContextBinder final CallContext context);
+ void batchCreateFromTransaction(@InvoicePaymentBinder final List<InvoicePayment> items, @CallContextBinder final CallContext context);
@SqlQuery
public List<InvoicePayment> getPaymentsForInvoice(@Bind("invoiceId") final String invoiceId);
@SqlQuery
- InvoicePayment getInvoicePayment(@Bind("paymentAttemptId") final String paymentAttemptId);
+ InvoicePayment getInvoicePayment(@Bind("paymentId") final String paymentId);
+
+ @SqlQuery
+ InvoicePayment getPaymentsForCookieId(@Bind("paymentCookieId") final String paymentCookieId);
@SqlUpdate
- void notifyOfPaymentAttempt(@InvoicePaymentBinder final InvoicePayment invoicePayment,
- @CallContextBinder final CallContext context);
+ void notifyOfPayment(@InvoicePaymentBinder final InvoicePayment invoicePayment, @CallContextBinder final CallContext context);
@SqlQuery
BigDecimal getRemainingAmountPaid(@Bind("invoicePaymentId") final String invoicePaymentId);
@@ -95,22 +98,24 @@ public interface InvoicePaymentSqlDao extends EntitySqlDao<InvoicePayment>, Tran
List<InvoicePayment> getChargeBacksByAccountId(@Bind("accountId") final String accountId);
@SqlQuery
- List<InvoicePayment> getChargebacksByAttemptPaymentId(@Bind("paymentAttemptId") final String paymentAttemptId);
+ List<InvoicePayment> getChargebacksByPaymentId(@Bind("paymentId") final String paymentId);
public static class InvoicePaymentMapper extends MapperBase implements ResultSetMapper<InvoicePayment> {
@Override
public InvoicePayment map(final int index, final ResultSet result, final StatementContext context) throws SQLException {
final UUID id = getUUID(result, "id");
- final UUID paymentAttemptId = getUUID(result, "payment_attempt_id");
+ final InvoicePaymentType type = InvoicePaymentType.valueOf(result.getString("type"));
+ final UUID paymentId = getUUID(result, "payment_id");
final UUID invoiceId = getUUID(result, "invoice_id");
- final DateTime paymentAttemptDate = getDate(result, "payment_attempt_date");
+ final DateTime paymentDate = getDate(result, "payment_date");
final BigDecimal amount = result.getBigDecimal("amount");
final String currencyString = result.getString("currency");
final Currency currency = (currencyString == null) ? null : Currency.valueOf(currencyString);
- final UUID reversedInvoicePaymentId = getUUID(result, "reversed_invoice_Payment_id");
+ final UUID paymentCookieId = getUUID(result, "payment_cookie_id");
+ final UUID linkedInvoicePaymentId = getUUID(result, "linked_invoice_payment_id");
- return new DefaultInvoicePayment(id, paymentAttemptId, invoiceId, paymentAttemptDate,
- amount, currency, reversedInvoicePaymentId);
+ return new DefaultInvoicePayment(id, type, paymentId, invoiceId, paymentDate,
+ amount, currency, paymentCookieId, linkedInvoicePaymentId);
}
}
@@ -125,13 +130,15 @@ public interface InvoicePaymentSqlDao extends EntitySqlDao<InvoicePayment>, Tran
@Override
public void bind(final SQLStatement q, final InvoicePaymentBinder bind, final InvoicePayment payment) {
q.bind("id", payment.getId().toString());
+ q.bind("type", payment.getType().toString());
q.bind("invoiceId", payment.getInvoiceId().toString());
- q.bind("paymentAttemptId", uuidToString(payment.getPaymentAttemptId()));
- q.bind("paymentAttemptDate", payment.getPaymentAttemptDate().toDate());
+ q.bind("paymentId", uuidToString(payment.getPaymentId()));
+ q.bind("paymentDate", payment.getPaymentDate().toDate());
q.bind("amount", payment.getAmount());
final Currency currency = payment.getCurrency();
q.bind("currency", (currency == null) ? null : currency.toString());
- q.bind("reversedInvoicePaymentId", uuidToString(payment.getReversedInvoicePaymentId()));
+ q.bind("paymentCookieId", uuidToString(payment.getPaymentCookieId()));
+ q.bind("linkedInvoicePaymentId", uuidToString(payment.getLinkedInvoicePaymentId()));
}
};
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceSqlDao.java b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceSqlDao.java
index 21fe8d5..845b7b9 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceSqlDao.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceSqlDao.java
@@ -75,15 +75,8 @@ public interface InvoiceSqlDao extends EntitySqlDao<Invoice>, AuditSqlDao, Trans
@SqlQuery
@RegisterMapper(UuidMapper.class)
- UUID getInvoiceIdByPaymentAttemptId(@Bind("paymentAttemptId") final String paymentAttemptId);
+ UUID getInvoiceIdByPaymentId(@Bind("paymentId") final String paymentId);
- @SqlQuery
- @RegisterMapper(BalanceMapper.class)
- BigDecimal getAccountBalance(@Bind("accountId") final String accountId);
-
- @SqlQuery
- List<Invoice> getUnpaidInvoicesByAccountId(@Bind("accountId") final String accountId,
- @Bind("upToDate") final Date upToDate);
@BindingAnnotation(InvoiceBinder.InvoiceBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@@ -121,23 +114,5 @@ public interface InvoiceSqlDao extends EntitySqlDao<Invoice>, AuditSqlDao, Trans
return new DefaultInvoice(id, accountId, invoiceNumber, invoiceDate, targetDate, currency, isMigrationInvoice);
}
}
-
- public static class BalanceMapper implements ResultSetMapper<BigDecimal> {
- @Override
- public BigDecimal map(final int index, final ResultSet result, final StatementContext context) throws SQLException {
- BigDecimal amountInvoiced = result.getBigDecimal("amount_invoiced");
- BigDecimal amountPaid = result.getBigDecimal("amount_paid");
-
- if (amountInvoiced == null) {
- amountInvoiced = BigDecimal.ZERO;
- }
-
- if (amountPaid == null) {
- amountPaid = BigDecimal.ZERO;
- }
-
- return amountInvoiced.subtract(amountPaid);
- }
- }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/generator/InvoiceDateUtils.java b/invoice/src/main/java/com/ning/billing/invoice/generator/InvoiceDateUtils.java
new file mode 100644
index 0000000..5f7f86a
--- /dev/null
+++ b/invoice/src/main/java/com/ning/billing/invoice/generator/InvoiceDateUtils.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2010-2012 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.invoice.generator;
+
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+
+public class InvoiceDateUtils {
+ public static DateTime roundDateTimeToDate(final DateTime input, final DateTimeZone timeZone) {
+ if (input == null) {
+ return null;
+ }
+ final DateTime tzAdjustedStartDate = input.toDateTime(timeZone);
+
+ return new DateTime(tzAdjustedStartDate.getYear(), tzAdjustedStartDate.getMonthOfYear(), tzAdjustedStartDate.getDayOfMonth(), 0, 0, timeZone);
+ }
+}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/glue/DefaultInvoiceModule.java b/invoice/src/main/java/com/ning/billing/invoice/glue/DefaultInvoiceModule.java
index 918bfa2..1f2507b 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/glue/DefaultInvoiceModule.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/glue/DefaultInvoiceModule.java
@@ -31,20 +31,17 @@ import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.invoice.api.formatters.InvoiceFormatterFactory;
import com.ning.billing.invoice.api.invoice.DefaultInvoicePaymentApi;
import com.ning.billing.invoice.api.migration.DefaultInvoiceMigrationApi;
-import com.ning.billing.invoice.api.test.DefaultInvoiceTestApi;
-import com.ning.billing.invoice.api.test.InvoiceTestApi;
import com.ning.billing.invoice.api.user.DefaultInvoiceUserApi;
import com.ning.billing.invoice.dao.DefaultInvoiceDao;
import com.ning.billing.invoice.dao.InvoiceDao;
-import com.ning.billing.invoice.model.DefaultInvoiceGenerator;
-import com.ning.billing.invoice.model.InvoiceGenerator;
+import com.ning.billing.invoice.generator.DefaultInvoiceGenerator;
+import com.ning.billing.invoice.generator.InvoiceGenerator;
import com.ning.billing.invoice.notification.DefaultNextBillingDateNotifier;
import com.ning.billing.invoice.notification.DefaultNextBillingDatePoster;
import com.ning.billing.invoice.notification.EmailInvoiceNotifier;
import com.ning.billing.invoice.notification.NextBillingDateNotifier;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.invoice.notification.NullInvoiceNotifier;
-import com.ning.billing.invoice.template.formatters.DefaultInvoiceFormatterFactory;
import com.ning.billing.util.template.translation.TranslatorConfig;
public class DefaultInvoiceModule extends AbstractModule implements InvoiceModule {
@@ -60,11 +57,6 @@ public class DefaultInvoiceModule extends AbstractModule implements InvoiceModul
}
@Override
- public void installInvoiceTestApi() {
- bind(InvoiceTestApi.class).to(DefaultInvoiceTestApi.class).asEagerSingleton();
- }
-
- @Override
public void installInvoicePaymentApi() {
bind(InvoicePaymentApi.class).to(DefaultInvoicePaymentApi.class).asEagerSingleton();
}
@@ -120,6 +112,5 @@ public class DefaultInvoiceModule extends AbstractModule implements InvoiceModul
installInvoiceUserApi();
installInvoicePaymentApi();
installInvoiceMigrationApi();
- installInvoiceTestApi();
}
}
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 7d94daa..1fdb6f7 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/InvoiceDispatcher.java
@@ -35,17 +35,17 @@ import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceNotifier;
-import com.ning.billing.invoice.api.user.DefaultEmptyInvoiceEvent;
+import com.ning.billing.invoice.api.user.DefaultNullInvoiceEvent;
import com.ning.billing.invoice.api.user.DefaultInvoiceCreationEvent;
import com.ning.billing.invoice.dao.InvoiceDao;
+import com.ning.billing.invoice.generator.InvoiceGenerator;
import com.ning.billing.invoice.model.FixedPriceInvoiceItem;
-import com.ning.billing.invoice.model.InvoiceGenerator;
import com.ning.billing.invoice.model.RecurringInvoiceItem;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BillingEventSet;
@@ -56,7 +56,7 @@ import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.globallocker.GlobalLock;
import com.ning.billing.util.globallocker.GlobalLocker;
-import com.ning.billing.util.globallocker.GlobalLocker.LockerService;
+import com.ning.billing.util.globallocker.GlobalLocker.LockerType;
import com.ning.billing.util.globallocker.LockFailedException;
public class InvoiceDispatcher {
@@ -95,7 +95,7 @@ public class InvoiceDispatcher {
VERBOSE_OUTPUT = (verboseOutputValue != null) && Boolean.parseBoolean(verboseOutputValue);
}
- public void processSubscription(final SubscriptionEvent transition,
+ public void processSubscription(final EffectiveSubscriptionEvent transition,
final CallContext context) throws InvoiceApiException {
final UUID subscriptionId = transition.getSubscriptionId();
final DateTime targetDate = transition.getEffectiveTransitionTime();
@@ -123,7 +123,7 @@ public class InvoiceDispatcher {
final boolean dryRun, final CallContext context) throws InvoiceApiException {
GlobalLock lock = null;
try {
- lock = locker.lockWithNumberOfTries(LockerService.INVOICE, accountId.toString(), NB_LOCK_TRY);
+ lock = locker.lockWithNumberOfTries(LockerType.ACCOUNT, accountId.toString(), NB_LOCK_TRY);
return processAccountWithLock(accountId, targetDate, dryRun, context);
} catch (LockFailedException e) {
@@ -159,7 +159,7 @@ public class InvoiceDispatcher {
log.info("Generated null invoice.");
outputDebugData(billingEvents, invoices);
if (!dryRun) {
- final BusEvent event = new DefaultEmptyInvoiceEvent(accountId, clock.getUTCNow(), context.getUserToken());
+ final BusEvent event = new DefaultNullInvoiceEvent(accountId, clock.getUTCNow(), context.getUserToken());
postEvent(event, accountId);
}
} else {
@@ -172,7 +172,7 @@ public class InvoiceDispatcher {
}
outputDebugData(billingEvents, invoices);
if (!dryRun) {
- invoiceDao.create(invoice, context);
+ invoiceDao.create(invoice, account.getBillCycleDay(), context);
final List<InvoiceItem> fixedPriceInvoiceItems = invoice.getInvoiceItems(FixedPriceInvoiceItem.class);
final List<InvoiceItem> recurringInvoiceItems = invoice.getInvoiceItems(RecurringInvoiceItem.class);
diff --git a/invoice/src/main/java/com/ning/billing/invoice/InvoiceListener.java b/invoice/src/main/java/com/ning/billing/invoice/InvoiceListener.java
index 601ebeb..9b4868c 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/InvoiceListener.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/InvoiceListener.java
@@ -26,7 +26,7 @@ import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.timeline.RepairEntitlementEvent;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallContextFactory;
@@ -55,7 +55,7 @@ public class InvoiceListener {
}
@Subscribe
- public void handleSubscriptionTransition(final SubscriptionEvent transition) {
+ public void handleSubscriptionTransition(final EffectiveSubscriptionEvent transition) {
try {
// Skip future uncancel event
// Skip events which are marked as not being the last one
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/CreditAdjInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/CreditAdjInvoiceItem.java
new file mode 100644
index 0000000..bbc06da
--- /dev/null
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/CreditAdjInvoiceItem.java
@@ -0,0 +1,47 @@
+/*
+ * 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.invoice.model;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.invoice.api.InvoiceItemType;
+
+public class CreditAdjInvoiceItem extends AdjInvoiceItem {
+
+ public CreditAdjInvoiceItem(UUID invoiceId, UUID accountId, DateTime date,
+ BigDecimal amount, Currency currency) {
+ super(invoiceId, accountId, date, date, amount, currency);
+ }
+
+ public CreditAdjInvoiceItem(UUID id, UUID invoiceId, UUID accountId, DateTime date,
+ BigDecimal amount, Currency currency) {
+ super(id, invoiceId, accountId, date, date, amount, currency);
+ }
+
+ @Override
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.CREDIT_ADJ;
+ }
+
+ @Override
+ public String getDescription() {
+ return "credit-adj";
+ }
+}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/CreditBalanceAdjInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/CreditBalanceAdjInvoiceItem.java
new file mode 100644
index 0000000..f32bc72
--- /dev/null
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/CreditBalanceAdjInvoiceItem.java
@@ -0,0 +1,49 @@
+/*
+ * 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.invoice.model;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.invoice.api.InvoiceItemType;
+
+public class CreditBalanceAdjInvoiceItem extends AdjInvoiceItem {
+
+ public CreditBalanceAdjInvoiceItem(UUID invoiceId, UUID accountId,
+ DateTime date, BigDecimal amount, Currency currency) {
+ super(invoiceId, accountId, date, date, amount, currency);
+ }
+
+ public CreditBalanceAdjInvoiceItem(UUID id, UUID invoiceId, UUID accountId,
+ DateTime date, BigDecimal amount, Currency currency) {
+ super(id, invoiceId, accountId, date, date, amount, currency);
+ }
+
+
+ @Override
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.CBA_ADJ;
+ }
+
+ @Override
+ public String getDescription() {
+ return "cba-adj";
+ }
+}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoice.java b/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoice.java
index c636ada..41297fe 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoice.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoice.java
@@ -144,25 +144,25 @@ public class DefaultInvoice extends EntityBase implements Invoice {
}
@Override
- public DateTime getLastPaymentAttempt() {
- DateTime lastPaymentAttempt = null;
+ public DateTime getLastPaymentDate() {
+ DateTime lastPaymentDate = null;
for (final InvoicePayment paymentAttempt : payments) {
- final DateTime paymentAttemptDate = paymentAttempt.getPaymentAttemptDate();
- if (lastPaymentAttempt == null) {
- lastPaymentAttempt = paymentAttemptDate;
+ final DateTime paymentDate = paymentAttempt.getPaymentDate();
+ if (lastPaymentDate == null) {
+ lastPaymentDate = paymentDate;
}
- if (lastPaymentAttempt.isBefore(paymentAttemptDate)) {
- lastPaymentAttempt = paymentAttemptDate;
+ if (lastPaymentDate.isBefore(paymentDate)) {
+ lastPaymentDate = paymentDate;
}
}
- return lastPaymentAttempt;
+ return lastPaymentDate;
}
@Override
- public BigDecimal getAmountPaid() {
+ public BigDecimal getPaidAmount() {
BigDecimal amountPaid = BigDecimal.ZERO;
for (final InvoicePayment payment : payments) {
if (payment.getAmount() != null) {
@@ -173,19 +173,33 @@ public class DefaultInvoice extends EntityBase implements Invoice {
}
@Override
- public BigDecimal getAmountCharged() {
- return invoiceItems.getAmountCharged();
+ public BigDecimal getChargedAmount() {
+ return invoiceItems.getChargedAmount();
}
@Override
- public BigDecimal getAmountCredited() {
- return invoiceItems.getAmountCredited();
+ public BigDecimal getCBAAmount() {
+ return invoiceItems.getCBAAmount();
}
@Override
+ public BigDecimal getTotalAdjAmount() {
+ return invoiceItems.getTotalAdjAmount();
+ }
+
+ @Override
+ public BigDecimal getCreditAdjAmount() {
+ return invoiceItems.getCreditAdjAmount();
+ }
+
+ @Override
+ public BigDecimal getRefundAdjAmount() {
+ return invoiceItems.getRefundAdjAmount();
+ }
+ @Override
public BigDecimal getBalance() {
- // credits offset payments
- return getAmountCharged().subtract(getAmountPaid().subtract(getAmountCredited()));
+ final BigDecimal balance = getChargedAmount().add(getTotalAdjAmount()).add(getCBAAmount()).subtract(getPaidAmount());;
+ return balance;
}
@Override
@@ -194,13 +208,14 @@ public class DefaultInvoice extends EntityBase implements Invoice {
return false;
}
- final DateTime lastPaymentAttempt = getLastPaymentAttempt();
- return (lastPaymentAttempt == null) || lastPaymentAttempt.plusDays(numberOfDays).isAfter(targetDate);
+ final DateTime lastPayment = getLastPaymentDate();
+ return (lastPayment == null) || lastPayment.plusDays(numberOfDays).isAfter(targetDate);
}
@Override
public String toString() {
- return "DefaultInvoice [items=" + invoiceItems + ", payments=" + payments + ", id=" + id + ", accountId=" + accountId + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", currency=" + currency + ", amountPaid=" + getAmountPaid() + ", lastPaymentAttempt=" + getLastPaymentAttempt() + "]";
+ return "DefaultInvoice [items=" + invoiceItems + ", payments=" + payments + ", id=" + id + ", accountId=" + accountId + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", currency=" + currency + ", amountPaid=" + getPaidAmount() + ", lastPaymentDate=" + getLastPaymentDate() + "]";
}
+
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoicePayment.java b/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoicePayment.java
index db80be0..abd96b3 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoicePayment.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/DefaultInvoicePayment.java
@@ -22,44 +22,47 @@ import java.util.UUID;
import org.joda.time.DateTime;
-import com.ning.billing.ErrorCode;
import com.ning.billing.catalog.api.Currency;
-import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.invoice.api.InvoicePayment;
import com.ning.billing.util.entity.EntityBase;
public class DefaultInvoicePayment extends EntityBase implements InvoicePayment {
- private final UUID paymentAttemptId;
+ private final UUID paymentId;
+ private final InvoicePaymentType type;
private final UUID invoiceId;
private final DateTime paymentDate;
private final BigDecimal amount;
private final Currency currency;
- private final UUID reversedInvoicePaymentId;
+ private final UUID paymentCookieId;
+ private final UUID linkedInvoicePaymentId;
- public DefaultInvoicePayment(final UUID paymentAttemptId, final UUID invoiceId, final DateTime paymentDate) {
- this(UUID.randomUUID(), paymentAttemptId, invoiceId, paymentDate, null, null, null);
- }
-
- public DefaultInvoicePayment(final UUID paymentAttemptId, final UUID invoiceId, final DateTime paymentDate,
+ public DefaultInvoicePayment(final InvoicePaymentType type, final UUID paymentId, final UUID invoiceId, final DateTime paymentDate,
final BigDecimal amount, final Currency currency) {
- this(UUID.randomUUID(), paymentAttemptId, invoiceId, paymentDate, amount, currency, null);
+ this(UUID.randomUUID(), type, paymentId, invoiceId, paymentDate, amount, currency, null, null);
}
- public DefaultInvoicePayment(final UUID id, final UUID paymentAttemptId, final UUID invoiceId, final DateTime paymentDate,
- @Nullable final BigDecimal amount, @Nullable final Currency currency,
- @Nullable final UUID reversedInvoicePaymentId) {
+ public DefaultInvoicePayment(final UUID id, final InvoicePaymentType type, final UUID paymentId, final UUID invoiceId, final DateTime paymentDate,
+ @Nullable final BigDecimal amount, @Nullable final Currency currency, @Nullable final UUID paymentCookieId,
+ @Nullable final UUID linkedInvoicePaymentId) {
super(id);
- this.paymentAttemptId = paymentAttemptId;
+ this.type = type;
+ this.paymentId = paymentId;
this.amount = amount;
this.invoiceId = invoiceId;
this.paymentDate = paymentDate;
this.currency = currency;
- this.reversedInvoicePaymentId = reversedInvoicePaymentId;
+ this.paymentCookieId = paymentCookieId;
+ this.linkedInvoicePaymentId = linkedInvoicePaymentId;
}
@Override
- public UUID getPaymentAttemptId() {
- return paymentAttemptId;
+ public InvoicePaymentType getType() {
+ return type;
+ }
+
+ @Override
+ public UUID getPaymentId() {
+ return paymentId;
}
@Override
@@ -68,7 +71,7 @@ public class DefaultInvoicePayment extends EntityBase implements InvoicePayment
}
@Override
- public DateTime getPaymentAttemptDate() {
+ public DateTime getPaymentDate() {
return paymentDate;
}
@@ -83,16 +86,13 @@ public class DefaultInvoicePayment extends EntityBase implements InvoicePayment
}
@Override
- public UUID getReversedInvoicePaymentId() {
- return reversedInvoicePaymentId;
+ public UUID getLinkedInvoicePaymentId() {
+ return linkedInvoicePaymentId;
}
@Override
- public InvoicePayment asChargeBack(final BigDecimal chargeBackAmount, final DateTime chargeBackDate) throws InvoiceApiException {
- if (chargeBackAmount.compareTo(amount) > 0) {
- throw new InvoiceApiException(ErrorCode.CHARGE_BACK_AMOUNT_TOO_HIGH, chargeBackAmount, amount);
- }
-
- return new DefaultInvoicePayment(UUID.randomUUID(), null, invoiceId, chargeBackDate, chargeBackAmount.negate(), currency, id);
+ public UUID getPaymentCookieId() {
+ return paymentCookieId;
}
+
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/FixedPriceInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/FixedPriceInvoiceItem.java
index 9176230..d8ac06b 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/FixedPriceInvoiceItem.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/FixedPriceInvoiceItem.java
@@ -30,17 +30,12 @@ public class FixedPriceInvoiceItem extends InvoiceItemBase {
public FixedPriceInvoiceItem(final UUID invoiceId, final UUID accountId, @Nullable final UUID bundleId, @Nullable final UUID subscriptionId, final String planName, final String phaseName,
final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency) {
- super(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency, InvoiceItemType.FIXED);
+ super(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency);
}
public FixedPriceInvoiceItem(final UUID id, final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency) {
- super(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency, InvoiceItemType.FIXED);
- }
-
- @Override
- public InvoiceItem asReversingItem() {
- throw new UnsupportedOperationException();
+ super(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency);
}
@Override
@@ -151,4 +146,9 @@ public class FixedPriceInvoiceItem extends InvoiceItemBase {
return true;
}
+
+ @Override
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.FIXED;
+ }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/InAdvanceBillingMode.java b/invoice/src/main/java/com/ning/billing/invoice/model/InAdvanceBillingMode.java
index 3fcff90..117df30 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/InAdvanceBillingMode.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/InAdvanceBillingMode.java
@@ -77,7 +77,6 @@ public class InAdvanceBillingMode implements BillingMode {
results.add(new RecurringInvoiceItemData(lastBillingCycleDate, effectiveEndDate, trailingProRationPeriods));
}
}
-
return results;
}
@@ -137,7 +136,6 @@ public class InAdvanceBillingMode implements BillingMode {
DateTime proposedDate = tmp.toDateTime();
while (proposedDate.isBefore(date)) {
- // STEPH could be an annual ?
proposedDate = proposedDate.plusMonths(1);
}
return proposedDate;
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemBase.java b/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemBase.java
index 89bd1a3..842e4d9 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemBase.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemBase.java
@@ -28,28 +28,93 @@ import com.ning.billing.invoice.api.InvoiceItemType;
import com.ning.billing.util.entity.EntityBase;
public abstract class InvoiceItemBase extends EntityBase implements InvoiceItem {
+
+ /* Common to all items */
protected final UUID invoiceId;
protected final UUID accountId;
- protected final UUID subscriptionId;
- protected final UUID bundleId;
- protected final String planName;
- protected final String phaseName;
protected final DateTime startDate;
protected final DateTime endDate;
protected final BigDecimal amount;
protected final Currency currency;
- protected final InvoiceItemType invoiceItemType;
+ /* Fixed and recurring specific */
+ protected final UUID subscriptionId;
+ protected final UUID bundleId;
+ protected final String planName;
+ protected final String phaseName;
+
+ /* Recurring specific */
+ protected final BigDecimal rate;
+
+ /* RepairAdjInvoiceItem */
+ protected final UUID linkedItemId;
+
+
+ @Override
+ public String toString() {
+ return getInvoiceItemType() + ": [startDate=" + startDate + ", endDate="
+ + endDate + ", amount=" + amount + ", currency=" + currency
+ + ", invoiceId=" + invoiceId
+ + ", subscriptionId=" + subscriptionId + ", planName="
+ + planName + ", phaseName=" + phaseName + ", rate=" + rate
+ + ", linkedItemId=" + linkedItemId + "]";
+ }
+
+ /*
+ * CTOR without ID; called from generator when creating invoice item
+ */
+ // No rate and no reversing item
+ public InvoiceItemBase(final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency) {
+ this(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, null, currency);
+
+ }
+
+ // With rate but no reversing item
public InvoiceItemBase(final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
- final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency, final InvoiceItemType invoiceItemType) {
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final BigDecimal rate, final Currency currency) {
this(UUID.randomUUID(), invoiceId, accountId, bundleId, subscriptionId, planName, phaseName,
- startDate, endDate, amount, currency, invoiceItemType);
+ startDate, endDate, amount, rate, currency, null);
}
+ // With reversing item, no rate
+ public InvoiceItemBase(final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency, final UUID reversedItemId) {
+ this(UUID.randomUUID(), invoiceId, accountId, bundleId, subscriptionId, planName, phaseName,
+ startDate, endDate, amount, null, currency, reversedItemId);
+ }
+
+
+
+ /*
+ * CTORs with ID; called from DAO when rehydrating
+ */
+ // No rate and no reversing item
+ public InvoiceItemBase(final UUID id, final UUID invoiceId, final UUID accountId, @Nullable final UUID bundleId,
+ @Nullable final UUID subscriptionId, @Nullable final String planName, @Nullable final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency) {
+ this(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, null, currency, null);
+ }
+
+ // With rate but no reversing item
+ public InvoiceItemBase(final UUID id, final UUID invoiceId, final UUID accountId, @Nullable final UUID bundleId,
+ @Nullable final UUID subscriptionId, @Nullable final String planName, @Nullable final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final BigDecimal rate, final Currency currency) {
+ this(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, rate, currency, null);
+ }
+
+ // With reversing item, no rate
public InvoiceItemBase(final UUID id, final UUID invoiceId, final UUID accountId, @Nullable final UUID bundleId,
- @Nullable final UUID subscriptionId, @Nullable final String planName, @Nullable final String phaseName,
- final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency,
- final InvoiceItemType invoiceItemType) {
+ @Nullable final UUID subscriptionId, @Nullable final String planName, @Nullable final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final Currency currency, final UUID reversedItemId) {
+ this(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, null, currency, reversedItemId);
+ }
+
+
+ private InvoiceItemBase(final UUID id, final UUID invoiceId, final UUID accountId, @Nullable final UUID bundleId,
+ @Nullable final UUID subscriptionId, @Nullable final String planName, @Nullable final String phaseName,
+ final DateTime startDate, final DateTime endDate, final BigDecimal amount, final BigDecimal rate, final Currency currency,
+ UUID reversedItemId) {
super(id);
this.invoiceId = invoiceId;
this.accountId = accountId;
@@ -61,7 +126,8 @@ public abstract class InvoiceItemBase extends EntityBase implements InvoiceItem
this.endDate = endDate;
this.amount = amount;
this.currency = currency;
- this.invoiceItemType = invoiceItemType;
+ this.rate = rate;
+ this.linkedItemId = reversedItemId;
}
@Override
@@ -74,6 +140,7 @@ public abstract class InvoiceItemBase extends EntityBase implements InvoiceItem
return bundleId;
}
+ @Override
public UUID getAccountId() {
return accountId;
}
@@ -114,16 +181,22 @@ public abstract class InvoiceItemBase extends EntityBase implements InvoiceItem
}
@Override
- public InvoiceItemType getInvoiceItemType() {
- return invoiceItemType;
+ public BigDecimal getRate() {
+ return rate;
}
@Override
- public abstract InvoiceItem asReversingItem();
+ public UUID getLinkedItemId() {
+ return linkedItemId;
+ }
+
+ @Override
+ public abstract InvoiceItemType getInvoiceItemType();
@Override
public abstract String getDescription();
@Override
public abstract int compareTo(InvoiceItem invoiceItem);
+
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemList.java b/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemList.java
index 265f518..3b495a4 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemList.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/InvoiceItemList.java
@@ -18,11 +18,16 @@ package com.ning.billing.invoice.model;
import java.math.BigDecimal;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import com.ning.billing.invoice.api.InvoiceItem;
+import com.ning.billing.invoice.api.InvoiceItemType;
public class InvoiceItemList extends ArrayList<InvoiceItem> {
+
+ private static final long serialVersionUID = 192311667L;
+
private static final int NUMBER_OF_DECIMALS = InvoicingConfiguration.getNumberOfDecimals();
private static final int ROUNDING_METHOD = InvoicingConfiguration.getRoundingMode();
@@ -35,33 +40,45 @@ public class InvoiceItemList extends ArrayList<InvoiceItem> {
this.addAll(invoiceItems);
}
- public BigDecimal getAmountCharged() {
- // naive implementation, assumes all invoice items share the same currency
- BigDecimal total = BigDecimal.ZERO.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
+ public BigDecimal getTotalAdjAmount() {
+ return getAmoutForItems(InvoiceItemType.CREDIT_ADJ, InvoiceItemType.REFUND_ADJ);
+ }
- for (final InvoiceItem item : this) {
- if (!(item instanceof CreditInvoiceItem)) {
- if (item.getAmount() != null) {
- total = total.add(item.getAmount());
- }
- }
- }
+ public BigDecimal getCreditAdjAmount() {
+ return getAmoutForItems(InvoiceItemType.CREDIT_ADJ);
+ }
- return total.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
+ public BigDecimal getRefundAdjAmount() {
+ return getAmoutForItems(InvoiceItemType.REFUND_ADJ);
+ }
+
+ public BigDecimal getChargedAmount() {
+ return getAmoutForItems(InvoiceItemType.RECURRING, InvoiceItemType.FIXED, InvoiceItemType.REPAIR_ADJ);
+ }
+
+ public BigDecimal getCBAAmount() {
+ return getAmoutForItems(InvoiceItemType.CBA_ADJ);
}
- public BigDecimal getAmountCredited() {
- // naive implementation, assumes all invoice items share the same currency
- BigDecimal total = BigDecimal.ZERO.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
+ private BigDecimal getAmoutForItems(InvoiceItemType...types) {
+ BigDecimal total = BigDecimal.ZERO.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
for (final InvoiceItem item : this) {
- if (item instanceof CreditInvoiceItem) {
+ if (isFromType(item, types)) {
if (item.getAmount() != null) {
total = total.add(item.getAmount());
}
}
}
-
return total.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
}
+
+ private boolean isFromType(InvoiceItem item, InvoiceItemType...types) {
+ for (InvoiceItemType cur : types) {
+ if (item.getInvoiceItemType() == cur) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/RecurringInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/RecurringInvoiceItem.java
index 9c9dcb9..23ac57b 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/model/RecurringInvoiceItem.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/RecurringInvoiceItem.java
@@ -30,16 +30,13 @@ import com.ning.billing.invoice.api.InvoiceItemType;
public class RecurringInvoiceItem extends InvoiceItemBase {
private final DateTimeFormatter dateTimeFormatter = DateTimeFormat.mediumDate();
- private final BigDecimal rate;
- private final UUID reversedItemId;
+
public RecurringInvoiceItem(final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
final DateTime startDate, final DateTime endDate,
final BigDecimal amount, final BigDecimal rate,
final Currency currency) {
- super(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency, InvoiceItemType.RECURRING);
- this.rate = rate;
- this.reversedItemId = null;
+ super(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, rate, currency);
}
public RecurringInvoiceItem(final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName, final String phaseName,
@@ -47,9 +44,7 @@ public class RecurringInvoiceItem extends InvoiceItemBase {
final BigDecimal amount, final BigDecimal rate,
final Currency currency, final UUID reversedItemId) {
super(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate,
- amount, currency, InvoiceItemType.REVERSAL);
- this.rate = rate;
- this.reversedItemId = reversedItemId;
+ amount, rate, currency);
}
public RecurringInvoiceItem(final UUID id, final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId,
@@ -57,42 +52,25 @@ public class RecurringInvoiceItem extends InvoiceItemBase {
final DateTime startDate, final DateTime endDate,
final BigDecimal amount, final BigDecimal rate,
final Currency currency) {
- super(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency, InvoiceItemType.RECURRING);
- this.rate = rate;
- this.reversedItemId = null;
- }
-
- public RecurringInvoiceItem(final UUID id, final UUID invoiceId, final UUID accountId, final UUID bundleId, final UUID subscriptionId,
- final String planName, final String phaseName,
- final DateTime startDate, final DateTime endDate,
- final BigDecimal amount, final BigDecimal rate,
- final Currency currency, final UUID reversedItemId) {
- super(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency, InvoiceItemType.REVERSAL);
- this.rate = rate;
- this.reversedItemId = reversedItemId;
+ super(id, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, rate, currency);
}
- @Override
- public InvoiceItem asReversingItem() {
- final BigDecimal amountNegated = amount == null ? null : amount.negate();
-
- return new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate,
- amountNegated, rate, currency, id);
- }
@Override
public String getDescription() {
return String.format("%s from %s to %s", phaseName, startDate.toString(dateTimeFormatter), endDate.toString(dateTimeFormatter));
}
- public UUID getReversedItemId() {
- return reversedItemId;
+ @Override
+ public UUID getLinkedItemId() {
+ return linkedItemId;
}
public boolean reversesItem() {
- return (reversedItemId != null);
+ return (linkedItemId != null);
}
+ @Override
public BigDecimal getRate() {
return rate;
}
@@ -167,7 +145,7 @@ public class RecurringInvoiceItem extends InvoiceItemBase {
if (rate.compareTo(that.rate) != 0) {
return false;
}
- if (reversedItemId != null ? !reversedItemId.equals(that.reversedItemId) : that.reversedItemId != null) {
+ if (linkedItemId != null ? !linkedItemId.equals(that.linkedItemId) : that.linkedItemId != null) {
return false;
}
if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
@@ -192,22 +170,14 @@ public class RecurringInvoiceItem extends InvoiceItemBase {
result = 31 * result + amount.hashCode();
result = 31 * result + rate.hashCode();
result = 31 * result + currency.hashCode();
- result = 31 * result + invoiceItemType.hashCode();
- result = 31 * result + (reversedItemId != null ? reversedItemId.hashCode() : 0);
+ result = 31 * result + getInvoiceItemType().hashCode();
+ result = 31 * result + (linkedItemId != null ? linkedItemId.hashCode() : 0);
return result;
}
@Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
-
- sb.append(phaseName).append(", ");
- sb.append(startDate.toString()).append(", ");
- sb.append(endDate.toString()).append(", ");
- sb.append(amount.toString()).append(", ");
- sb.append("subscriptionId = ").append(subscriptionId == null ? null : subscriptionId.toString()).append(", ");
- sb.append("bundleId = ").append(bundleId == null ? null : bundleId.toString()).append(", ");
-
- return sb.toString();
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.RECURRING;
}
+
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/RefundAdjInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/RefundAdjInvoiceItem.java
new file mode 100644
index 0000000..6eac357
--- /dev/null
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/RefundAdjInvoiceItem.java
@@ -0,0 +1,49 @@
+/*
+ * 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.invoice.model;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.invoice.api.InvoiceItemType;
+
+public class RefundAdjInvoiceItem extends AdjInvoiceItem {
+
+ public RefundAdjInvoiceItem(UUID invoiceId, UUID accountId, DateTime date,
+ BigDecimal amount, Currency currency) {
+ super(invoiceId, accountId, date, date, amount, currency);
+ }
+
+ public RefundAdjInvoiceItem(UUID id, UUID invoiceId, UUID accountId, DateTime date,
+ BigDecimal amount, Currency currency) {
+ super(id, invoiceId, accountId, date, date, amount, currency);
+ }
+
+ @Override
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.REFUND_ADJ;
+ }
+
+ @Override
+ public String getDescription() {
+ return "refund-adj";
+ }
+
+
+}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/model/RepairAdjInvoiceItem.java b/invoice/src/main/java/com/ning/billing/invoice/model/RepairAdjInvoiceItem.java
new file mode 100644
index 0000000..1ea8ef4
--- /dev/null
+++ b/invoice/src/main/java/com/ning/billing/invoice/model/RepairAdjInvoiceItem.java
@@ -0,0 +1,47 @@
+/*
+ * 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.invoice.model;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.invoice.api.InvoiceItemType;
+
+public class RepairAdjInvoiceItem extends AdjInvoiceItem {
+
+ public RepairAdjInvoiceItem(UUID invoiceId, UUID accountId, DateTime startDate, DateTime endDate,
+ BigDecimal amount, Currency currency, final UUID reversingId) {
+ super(invoiceId, accountId, startDate, endDate, amount, currency, reversingId);
+ }
+
+ public RepairAdjInvoiceItem(UUID id, UUID invoiceId, UUID accountId, DateTime startDate, DateTime endDate,
+ BigDecimal amount, Currency currency, final UUID reversingId) {
+ super(id, invoiceId, accountId, startDate, endDate, amount, currency, reversingId);
+ }
+
+ @Override
+ public InvoiceItemType getInvoiceItemType() {
+ return InvoiceItemType.REPAIR_ADJ;
+ }
+
+ @Override
+ public String getDescription() {
+ return "repair-adj";
+ }
+}
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 5c03f01..99e4f28 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
@@ -38,7 +38,6 @@ import com.ning.billing.util.notificationq.NotificationQueueService.Notification
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
-
private static final Logger log = LoggerFactory.getLogger(DefaultNextBillingDateNotifier.class);
public static final String NEXT_BILLING_DATE_NOTIFIER_QUEUE = "next-billing-date-queue";
@@ -47,13 +46,12 @@ public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
private final InvoiceConfig config;
private final EntitlementUserApi entitlementUserApi;
-
private NotificationQueue nextBillingQueue;
private final InvoiceListener listener;
@Inject
public DefaultNextBillingDateNotifier(final NotificationQueueService notificationQueueService,
- final InvoiceConfig config, final EntitlementUserApi entitlementUserApi, final InvoiceListener listener) {
+ final InvoiceConfig config, final EntitlementUserApi entitlementUserApi, final InvoiceListener listener) {
this.notificationQueueService = notificationQueueService;
this.config = config;
this.entitlementUserApi = entitlementUserApi;
@@ -62,17 +60,27 @@ public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
@Override
public void initialize() throws NotificationQueueAlreadyExists {
- nextBillingQueue = notificationQueueService.createNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
- NEXT_BILLING_DATE_NOTIFIER_QUEUE,
- new NotificationQueueHandler() {
+ final NotificationConfig notificationConfig = new NotificationConfig() {
+ @Override
+ public long getSleepTimeMs() {
+ return config.getSleepTimeMs();
+ }
+
+ @Override
+ public boolean isNotificationProcessingOff() {
+ return config.isNotificationProcessingOff();
+ }
+ };
+
+ final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate) {
try {
-
- if (! (notificationKey instanceof NextBillingDateNotificationKey)) {
+ if (!(notificationKey instanceof NextBillingDateNotificationKey)) {
log.error("Invoice service received an unexpected event type {}", notificationKey.getClass().getName());
return;
}
+
final NextBillingDateNotificationKey key = (NextBillingDateNotificationKey) notificationKey;
try {
final Subscription subscription = entitlementUserApi.getSubscriptionFromId(key.getUuidKey());
@@ -87,23 +95,13 @@ public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
} catch (IllegalArgumentException e) {
log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
}
-
}
- },
- new NotificationConfig() {
-
- @Override
- public long getSleepTimeMs() {
- return config.getSleepTimeMs();
- }
-
- @Override
- public boolean isNotificationProcessingOff() {
- return config.isNotificationProcessingOff();
- }
- }
- );
+ };
+ nextBillingQueue = notificationQueueService.createNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
+ NEXT_BILLING_DATE_NOTIFIER_QUEUE,
+ notificationQueueHandler,
+ notificationConfig);
}
@Override
@@ -122,6 +120,4 @@ public class DefaultNextBillingDateNotifier implements NextBillingDateNotifier {
private void processEvent(final UUID subscriptionId, final DateTime eventDateTime) {
listener.handleNextBillingDateEvent(subscriptionId, eventDateTime);
}
-
-
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDatePoster.java b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDatePoster.java
index f2521de..5f1c8e4 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDatePoster.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/notification/DefaultNextBillingDatePoster.java
@@ -17,6 +17,7 @@
package com.ning.billing.invoice.notification;
import java.io.IOException;
+import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
@@ -26,7 +27,7 @@ import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.ning.billing.invoice.api.DefaultInvoiceService;
-import com.ning.billing.util.notificationq.NotificationKey;
+import com.ning.billing.util.notificationq.Notification;
import com.ning.billing.util.notificationq.NotificationQueue;
import com.ning.billing.util.notificationq.NotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService.NoSuchNotificationQueue;
@@ -45,18 +46,28 @@ public class DefaultNextBillingDatePoster implements NextBillingDatePoster {
}
@Override
- public void insertNextBillingNotification(final Transmogrifier transactionalDao, final UUID subscriptionId, final DateTime futureNotificationTime) {
+ public void insertNextBillingNotification(final Transmogrifier transactionalDao, final UUID accountId, final UUID subscriptionId, final DateTime futureNotificationTime) {
final NotificationQueue nextBillingQueue;
try {
+
+
nextBillingQueue = notificationQueueService.getNotificationQueue(DefaultInvoiceService.INVOICE_SERVICE_NAME,
DefaultNextBillingDateNotifier.NEXT_BILLING_DATE_NOTIFIER_QUEUE);
log.info("Queuing next billing date notification. id: {}, timestamp: {}", subscriptionId.toString(), futureNotificationTime.toString());
- nextBillingQueue.recordFutureNotificationFromTransaction(transactionalDao, futureNotificationTime, new NextBillingDateNotificationKey(subscriptionId));
+
+ List<Notification> existingNotifications = nextBillingQueue.getNotificationForAccountAndDate(accountId, futureNotificationTime);
+ if (existingNotifications.size() > 0) {
+ log.info(String.format("%s : notification for account %s and date %s already exist, skip...",
+ DefaultNextBillingDateNotifier.NEXT_BILLING_DATE_NOTIFIER_QUEUE, accountId, futureNotificationTime));
+ return;
+ }
+
+ nextBillingQueue.recordFutureNotificationFromTransaction(transactionalDao, futureNotificationTime, accountId, new NextBillingDateNotificationKey(subscriptionId));
} catch (NoSuchNotificationQueue e) {
log.error("Attempting to put items on a non-existent queue (NextBillingDateNotifier).", e);
} catch (IOException e) {
- log.error("Failed to serialize notficationKey for subscriptionId {}", subscriptionId);
+ log.error("Failed to serialize notficationKey for subscriptionId {}", subscriptionId);
}
}
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/notification/NextBillingDatePoster.java b/invoice/src/main/java/com/ning/billing/invoice/notification/NextBillingDatePoster.java
index 279c61a..60f8ec4 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/notification/NextBillingDatePoster.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/notification/NextBillingDatePoster.java
@@ -23,7 +23,7 @@ import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
public interface NextBillingDatePoster {
- void insertNextBillingNotification(Transmogrifier transactionalDao,
+ void insertNextBillingNotification(Transmogrifier transactionalDao, UUID accountId,
UUID subscriptionId, DateTime futureNotificationTime);
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceFormatter.java b/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
index 6ed5713..345fff6 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceFormatter.java
@@ -29,6 +29,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.invoice.template.formatters;
import java.math.BigDecimal;
@@ -41,6 +42,9 @@ import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
+import com.google.common.base.Objects;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
@@ -48,6 +52,9 @@ import com.ning.billing.invoice.api.InvoicePayment;
import com.ning.billing.invoice.api.formatters.InvoiceFormatter;
import com.ning.billing.util.template.translation.TranslatorConfig;
+/**
+ * Format invoice fields. Note that the Mustache engine won't accept null values.
+ */
public class DefaultInvoiceFormatter implements InvoiceFormatter {
private final TranslatorConfig config;
private final Invoice invoice;
@@ -63,7 +70,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
@Override
public Integer getInvoiceNumber() {
- return invoice.getInvoiceNumber();
+ return Objects.firstNonNull(invoice.getInvoiceNumber(), 0);
}
@Override
@@ -87,7 +94,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
@Override
public <T extends InvoiceItem> List<InvoiceItem> getInvoiceItems(final Class<T> clazz) {
- return invoice.getInvoiceItems(clazz);
+ return Objects.firstNonNull(invoice.getInvoiceItems(clazz), ImmutableList.<InvoiceItem>of());
}
@Override
@@ -107,7 +114,7 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
@Override
public List<InvoicePayment> getPayments() {
- return invoice.getPayments();
+ return Objects.firstNonNull(invoice.getPayments(), ImmutableList.<InvoicePayment>of());
}
@Override
@@ -121,18 +128,18 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
}
@Override
- public BigDecimal getAmountCharged() {
- return invoice.getAmountCharged();
+ public BigDecimal getChargedAmount() {
+ return Objects.firstNonNull(invoice.getChargedAmount(), BigDecimal.ZERO);
}
@Override
- public BigDecimal getAmountCredited() {
- return invoice.getAmountCredited();
+ public BigDecimal getCBAAmount() {
+ return Objects.firstNonNull(invoice.getCBAAmount(), BigDecimal.ZERO);
}
@Override
public BigDecimal getBalance() {
- return invoice.getBalance();
+ return Objects.firstNonNull(invoice.getBalance(), BigDecimal.ZERO);
}
@Override
@@ -161,18 +168,23 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
}
@Override
- public DateTime getLastPaymentAttempt() {
- return invoice.getLastPaymentAttempt();
+ public DateTime getLastPaymentDate() {
+ return invoice.getLastPaymentDate();
}
@Override
- public BigDecimal getAmountPaid() {
- return invoice.getAmountPaid();
+ public BigDecimal getPaidAmount() {
+ return Objects.firstNonNull(invoice.getPaidAmount(), BigDecimal.ZERO);
}
@Override
public String getFormattedInvoiceDate() {
- return invoice.getInvoiceDate().toString(dateFormatter);
+ final DateTime invoiceDate = invoice.getInvoiceDate();
+ if (invoiceDate == null) {
+ return "";
+ } else {
+ return Strings.nullToEmpty(invoiceDate.toString(dateFormatter));
+ }
}
@Override
@@ -197,4 +209,19 @@ public class DefaultInvoiceFormatter implements InvoiceFormatter {
protected Invoice getInvoice() {
return invoice;
}
+
+ @Override
+ public BigDecimal getTotalAdjAmount() {
+ return Objects.firstNonNull(invoice.getTotalAdjAmount(), BigDecimal.ZERO);
+ }
+
+ @Override
+ public BigDecimal getCreditAdjAmount() {
+ return Objects.firstNonNull(invoice.getCreditAdjAmount(), BigDecimal.ZERO);
+ }
+
+ @Override
+ public BigDecimal getRefundAdjAmount() {
+ return Objects.firstNonNull(invoice.getRefundAdjAmount(), BigDecimal.ZERO);
+ }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java b/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
index 2dc8168..86be83b 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/template/formatters/DefaultInvoiceItemFormatter.java
@@ -23,6 +23,8 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
+import com.google.common.base.Objects;
+import com.google.common.base.Strings;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceItemType;
@@ -31,6 +33,9 @@ import com.ning.billing.util.template.translation.DefaultCatalogTranslator;
import com.ning.billing.util.template.translation.Translator;
import com.ning.billing.util.template.translation.TranslatorConfig;
+/**
+ * Format invoice item fields. Note that the Mustache engine won't accept null values.
+ */
public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
private final Translator translator;
@@ -48,7 +53,7 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
@Override
public BigDecimal getAmount() {
- return item.getAmount();
+ return Objects.firstNonNull(item.getAmount(), BigDecimal.ZERO);
}
@Override
@@ -62,13 +67,8 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
}
@Override
- public InvoiceItem asReversingItem() {
- return item.asReversingItem();
- }
-
- @Override
public String getDescription() {
- return item.getDescription();
+ return Strings.nullToEmpty(item.getDescription());
}
@Override
@@ -83,12 +83,12 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
@Override
public String getFormattedStartDate() {
- return item.getStartDate().toString(dateFormatter);
+ return Strings.nullToEmpty(item.getStartDate().toString(dateFormatter));
}
@Override
public String getFormattedEndDate() {
- return item.getEndDate().toString(dateFormatter);
+ return Strings.nullToEmpty(item.getEndDate().toString(dateFormatter));
}
@Override
@@ -113,12 +113,12 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
@Override
public String getPlanName() {
- return translator.getTranslation(locale, item.getPlanName());
+ return Strings.nullToEmpty(translator.getTranslation(locale, item.getPlanName()));
}
@Override
public String getPhaseName() {
- return translator.getTranslation(locale, item.getPhaseName());
+ return Strings.nullToEmpty(translator.getTranslation(locale, item.getPhaseName()));
}
@Override
@@ -130,4 +130,14 @@ public class DefaultInvoiceItemFormatter implements InvoiceItemFormatter {
public UUID getId() {
return item.getId();
}
+
+ @Override
+ public BigDecimal getRate() {
+ return BigDecimal.ZERO;
+ }
+
+ @Override
+ public UUID getLinkedItemId() {
+ return null;
+ }
}
diff --git a/invoice/src/main/java/com/ning/billing/invoice/template/HtmlInvoiceGenerator.java b/invoice/src/main/java/com/ning/billing/invoice/template/HtmlInvoiceGenerator.java
index f27bce7..04c5075 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/template/HtmlInvoiceGenerator.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/template/HtmlInvoiceGenerator.java
@@ -16,6 +16,7 @@
package com.ning.billing.invoice.template;
+import javax.annotation.Nullable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
@@ -42,7 +43,12 @@ public class HtmlInvoiceGenerator {
this.config = config;
}
- public String generateInvoice(final Account account, final Invoice invoice) throws IOException {
+ public String generateInvoice(final Account account, @Nullable final Invoice invoice) throws IOException {
+ // Don't do anything if the invoice is null
+ if (invoice == null) {
+ return null;
+ }
+
final Map<String, Object> data = new HashMap<String, Object>();
final DefaultInvoiceTranslator invoiceTranslator = new DefaultInvoiceTranslator(config);
final Locale locale = new Locale(account.getLocale());
diff --git a/invoice/src/main/java/com/ning/billing/invoice/template/translator/DefaultInvoiceTranslator.java b/invoice/src/main/java/com/ning/billing/invoice/template/translator/DefaultInvoiceTranslator.java
index bad6d1b..3e00120 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/template/translator/DefaultInvoiceTranslator.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/template/translator/DefaultInvoiceTranslator.java
@@ -36,7 +36,7 @@ public class DefaultInvoiceTranslator extends DefaultTranslatorBase implements I
@Override
protected String getBundlePath() {
- return config.getBundlePath();
+ return config.getInvoiceTemplateBundlePath();
}
@Override
diff --git a/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.sql.stg b/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.sql.stg
index 8ccf73b..baec2d4 100644
--- a/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.sql.stg
+++ b/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoicePaymentSqlDao.sql.stg
@@ -2,32 +2,34 @@ group InvoicePayment;
invoicePaymentFields(prefix) ::= <<
<prefix>id,
+ <prefix>type,
<prefix>invoice_id,
- <prefix>payment_attempt_id,
- <prefix>payment_attempt_date,
+ <prefix>payment_id,
+ <prefix>payment_date,
<prefix>amount,
<prefix>currency,
- <prefix>reversed_invoice_payment_id,
+ <prefix>payment_cookie_id,
+ <prefix>linked_invoice_payment_id,
<prefix>created_by,
<prefix>created_date
>>
create() ::= <<
INSERT INTO invoice_payments(<invoicePaymentFields()>)
- VALUES(:id, :invoiceId, :paymentAttemptId, :paymentAttemptDate, :amount, :currency,
- :reversedInvoicePaymentId, :userName, :createdDate);
+ VALUES(:id, :type, :invoiceId, :paymentId, :paymentDate, :amount, :currency,
+ :paymentCookieId, :linkedInvoicePaymentId, :userName, :createdDate);
>>
batchCreateFromTransaction() ::= <<
INSERT INTO invoice_payments(<invoicePaymentFields()>)
- VALUES(:id, :invoiceId, :paymentAttemptId, :paymentAttemptDate, :amount, :currency,
- :reversedInvoicePaymentId, :userName, :createdDate);
+ VALUES(:id, :type, :invoiceId, :paymentId, :paymentDate, :amount, :currency,
+ :paymentCookieId, :linkedInvoicePaymentId, :userName, :createdDate);
>>
-getByPaymentAttemptId() ::= <<
+getByPaymentId() ::= <<
SELECT <invoicePaymentFields()>
FROM invoice_payments
- WHERE payment_attempt_id = :paymentAttemptId;
+ WHERE payment_id = :paymentId;
>>
get() ::= <<
@@ -41,22 +43,28 @@ getById() ::= <<
WHERE id = :id;
>>
+getPaymentsForCookieId() ::= <<
+ SELECT <invoicePaymentFields()>
+ FROM invoice_payments
+ WHERE payment_cookie_id = :paymentCookieId;
+>>
+
getPaymentsForInvoice() ::= <<
SELECT <invoicePaymentFields()>
FROM invoice_payments
WHERE invoice_id = :invoiceId;
>>
-notifyOfPaymentAttempt() ::= <<
+notifyOfPayment() ::= <<
INSERT INTO invoice_payments(<invoicePaymentFields()>)
- VALUES(:id, :invoiceId, :paymentAttemptId, :paymentAttemptDate, :amount, :currency,
- :reversedInvoicePaymentId, :userName, :createdDate);
+ VALUES(:id, :type, :invoiceId, :paymentId, :paymentDate, :amount, :currency,
+ :paymentCookieId, :linkedInvoicePaymentId, :userName, :createdDate);
>>
getInvoicePayment() ::= <<
SELECT <invoicePaymentFields()>
FROM invoice_payments
- WHERE payment_attempt_id = :paymentAttemptId;
+ WHERE payment_id = :paymentId;
>>
getRecordId() ::= <<
@@ -95,7 +103,7 @@ getRemainingAmountPaid() ::= <<
SELECT SUM(amount)
FROM invoice_payments
WHERE id = :invoicePaymentId
- OR reversed_invoice_payment_id = :invoicePaymentId;
+ OR linked_invoice_payment_id = :invoicePaymentId;
>>
getAccountIdFromInvoicePaymentId() ::= <<
@@ -110,13 +118,13 @@ getChargeBacksByAccountId() ::= <<
FROM invoice_payments ip
INNER JOIN invoices i ON i.id = ip.invoice_id
WHERE i.account_id = :accountId
- AND reversed_invoice_payment_id IS NOT NULL;
+ AND linked_invoice_payment_id IS NOT NULL;
>>
-getChargebacksByAttemptPaymentId() ::= <<
+getChargebacksByPaymentId() ::= <<
SELECT <invoicePaymentFields()>
FROM invoice_payments
- WHERE reversed_invoice_payment_id IN
- (SELECT id FROM invoice_payments WHERE payment_attempt_id = :paymentAttemptId);
+ WHERE linked_invoice_payment_id IN
+ (SELECT id FROM invoice_payments WHERE payment_id = :paymentId);
>>
;
diff --git a/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoiceSqlDao.sql.stg b/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoiceSqlDao.sql.stg
index 8c8a3a2..6ed45be 100644
--- a/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoiceSqlDao.sql.stg
+++ b/invoice/src/main/resources/com/ning/billing/invoice/dao/InvoiceSqlDao.sql.stg
@@ -20,7 +20,7 @@ get() ::= <<
getInvoicesByAccount() ::= <<
SELECT record_id as invoice_number, <invoiceFields()>
FROM invoices
- WHERE account_id = :accountId AND migrated = 'FALSE'
+ WHERE account_id = :accountId AND migrated = '0'
ORDER BY target_date ASC;
>>
@@ -34,24 +34,15 @@ getAllInvoicesByAccount() ::= <<
getInvoicesByAccountAfterDate() ::= <<
SELECT record_id as invoice_number, <invoiceFields()>
FROM invoices
- WHERE account_id = :accountId AND target_date >= :fromDate AND migrated = 'FALSE'
+ WHERE account_id = :accountId AND target_date >= :fromDate AND migrated = '0'
ORDER BY target_date ASC;
>>
getInvoicesBySubscription() ::= <<
SELECT i.record_id as invoice_number, <invoiceFields("i.")>
FROM invoices i
- LEFT JOIN recurring_invoice_items rii ON i.id = rii.invoice_id
- WHERE rii.subscription_id = :subscriptionId AND migrated = 'FALSE'
- GROUP BY i.record_id, <invoiceFields("i.")>
-
- UNION ALL
-
- SELECT i.record_id as invoice_number, <invoiceFields("i.")>
- FROM invoices i
- LEFT JOIN fixed_invoice_items fii ON i.id = fii.invoice_id
- WHERE fii.subscription_id = :subscriptionId AND migrated = 'FALSE'
- GROUP BY i.record_id, <invoiceFields("i.")>;
+ JOIN invoice_items ii ON i.id = ii.invoice_id
+ WHERE ii.subscription_id = :subscriptionId AND i.migrated = '0';
>>
getById() ::= <<
@@ -60,39 +51,18 @@ getById() ::= <<
WHERE id = :id;
>>
-getAccountBalance() ::= <<
- SELECT SUM(iis.amount_invoiced) AS amount_invoiced,
- SUM(ips.total_paid) AS amount_paid
- FROM invoices i
- LEFT JOIN invoice_payment_summary ips ON i.id = ips.invoice_id
- LEFT JOIN invoice_item_summary iis ON i.id = iis.invoice_id
- WHERE i.account_id = :accountId
- GROUP BY i.account_id;
->>
-
create() ::= <<
INSERT INTO invoices(<invoiceFields()>)
VALUES (:id, :accountId, :invoiceDate, :targetDate, :currency, :migrated, :userName, :createdDate);
>>
-getInvoiceIdByPaymentAttemptId() ::= <<
+getInvoiceIdByPaymentId() ::= <<
SELECT i.id
FROM invoices i, invoice_payments ip
WHERE ip.invoice_id = i.id
- AND ip.payment_attempt_id = :paymentAttemptId
+ AND ip.payment_id = :paymentId
>>
-getUnpaidInvoicesByAccountId() ::= <<
- SELECT record_id as invoice_number, <invoiceFields("i.")>
- FROM invoices i
- LEFT JOIN invoice_payment_summary ips ON i.id = ips.invoice_id
- LEFT JOIN invoice_item_summary iis ON i.id = iis.invoice_id
- WHERE i.account_id = :accountId AND NOT (i.target_date > :upToDate) AND migrated = 'FALSE'
- GROUP BY i.id, i.account_id, i.invoice_date, i.target_date, i.currency
- HAVING (SUM(iis.amount_invoiced) > SUM(ips.total_paid)) OR (SUM(ips.total_paid) IS NULL)
- AND SUM(iis.amount_invoiced) > 0
- ORDER BY i.target_date ASC;
->>
getRecordId() ::= <<
SELECT record_id
diff --git a/invoice/src/main/resources/com/ning/billing/invoice/ddl.sql b/invoice/src/main/resources/com/ning/billing/invoice/ddl.sql
index 7c69562..1af1116 100644
--- a/invoice/src/main/resources/com/ning/billing/invoice/ddl.sql
+++ b/invoice/src/main/resources/com/ning/billing/invoice/ddl.sql
@@ -1,67 +1,30 @@
+
DROP TABLE IF EXISTS invoice_items;
-DROP TABLE IF EXISTS recurring_invoice_items;
-CREATE TABLE recurring_invoice_items (
+CREATE TABLE invoice_items (
record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
id char(36) NOT NULL,
+ type varchar(24) NOT NULL,
invoice_id char(36) NOT NULL,
account_id char(36) NOT NULL,
bundle_id char(36),
subscription_id char(36),
- plan_name varchar(50) NOT NULL,
- phase_name varchar(50) NOT NULL,
+ plan_name varchar(50),
+ phase_name varchar(50),
start_date datetime NOT NULL,
- end_date datetime NOT NULL,
- amount numeric(10,4) NULL,
+ end_date datetime,
+ amount numeric(10,4) NOT NULL,
rate numeric(10,4) NULL,
currency char(3) NOT NULL,
- reversed_item_id char(36),
- created_by varchar(50) NOT NULL,
- created_date datetime NOT NULL,
- PRIMARY KEY(record_id)
-) ENGINE=innodb;
-CREATE UNIQUE INDEX recurring_invoice_items_id ON recurring_invoice_items(id);
-CREATE INDEX recurring_invoice_items_subscription_id ON recurring_invoice_items(subscription_id ASC);
-CREATE INDEX recurring_invoice_items_invoice_id ON recurring_invoice_items(invoice_id ASC);
-
-DROP TABLE IF EXISTS fixed_invoice_items;
-CREATE TABLE fixed_invoice_items (
- record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
- id char(36) NOT NULL,
- invoice_id char(36) NOT NULL,
- account_id char(36) NOT NULL,
- bundle_id char(36),
- subscription_id char(36),
- plan_name varchar(50) NOT NULL,
- phase_name varchar(50) NOT NULL,
- start_date datetime NOT NULL,
- end_date datetime NOT NULL,
- amount numeric(10,4) NULL,
- currency char(3) NOT NULL,
- created_by varchar(50) NOT NULL,
- created_date datetime NOT NULL,
- PRIMARY KEY(record_id)
-) ENGINE=innodb;
-CREATE UNIQUE INDEX fixed_invoice_items_id ON fixed_invoice_items(id);
-CREATE INDEX fixed_invoice_items_subscription_id ON fixed_invoice_items(subscription_id ASC);
-CREATE INDEX fixed_invoice_items_invoice_id ON fixed_invoice_items(invoice_id ASC);
-
-DROP TABLE IF EXISTS credit_invoice_items;
-CREATE TABLE credit_invoice_items (
- record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
- id char(36) NOT NULL,
- invoice_id char(36) NOT NULL,
- account_id char(36) NOT NULL,
- credit_date datetime NOT NULL,
- amount numeric(10,4) NULL,
- currency char(3) NOT NULL,
+ linked_item_id char(36),
created_by varchar(50) NOT NULL,
created_date datetime NOT NULL,
PRIMARY KEY(record_id)
) ENGINE=innodb;
-CREATE UNIQUE INDEX credit_invoice_items_id ON credit_invoice_items(id);
-CREATE INDEX credit_invoice_items_invoice_id ON credit_invoice_items(invoice_id ASC);
-DROP TABLE IF EXISTS invoice_locking;
+CREATE UNIQUE INDEX invoice_items_id ON invoice_items(id);
+CREATE INDEX invoice_items_subscription_id ON invoice_items(subscription_id ASC);
+CREATE INDEX invoice_items_invoice_id ON invoice_items(invoice_id ASC);
+CREATE INDEX invoice_items_account_id ON invoice_items(account_id ASC);
DROP TABLE IF EXISTS invoices;
CREATE TABLE invoices (
@@ -83,35 +46,18 @@ DROP TABLE IF EXISTS invoice_payments;
CREATE TABLE invoice_payments (
record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
id char(36) NOT NULL,
+ type varchar(24) NOT NULL,
invoice_id char(36) NOT NULL,
- payment_attempt_id char(36) COLLATE utf8_bin,
- payment_attempt_date datetime NOT NULL,
+ payment_id char(36) COLLATE utf8_bin,
+ payment_date datetime NOT NULL,
amount numeric(10,4) NOT NULL,
currency char(3) NOT NULL,
- reversed_invoice_payment_id char(36) DEFAULT NULL,
+ payment_cookie_id char(36) DEFAULT NULL,
+ linked_invoice_payment_id char(36) DEFAULT NULL,
created_by varchar(50) NOT NULL,
created_date datetime NOT NULL,
PRIMARY KEY(record_id)
) ENGINE=innodb;
CREATE UNIQUE INDEX invoice_payments_id ON invoice_payments(id);
-CREATE INDEX invoice_payments_attempt ON invoice_payments(payment_attempt_id);
-CREATE INDEX invoice_payments_reversals ON invoice_payments(reversed_invoice_payment_id);
-
-DROP VIEW IF EXISTS invoice_payment_summary;
-CREATE VIEW invoice_payment_summary AS
-SELECT invoice_id,
- CASE WHEN SUM(amount) IS NULL THEN 0 ELSE SUM(amount) END AS total_paid,
- MAX(payment_attempt_date) AS last_payment_date
-FROM invoice_payments
-GROUP BY invoice_id;
-
-DROP VIEW IF EXISTS invoice_item_summary;
-CREATE VIEW invoice_item_summary AS
-SELECT i.id as invoice_id,
- CASE WHEN SUM(rii.amount) IS NULL THEN 0 ELSE SUM(rii.amount) END
- + CASE WHEN SUM(fii.amount) IS NULL THEN 0 ELSE SUM(fii.amount) END AS amount_invoiced
-FROM invoices i
-LEFT JOIN recurring_invoice_items rii ON i.id = rii.invoice_id
-LEFT JOIN fixed_invoice_items fii ON i.id = fii.invoice_id
-GROUP BY invoice_id;
-
+CREATE INDEX invoice_payments ON invoice_payments(payment_id);
+CREATE INDEX invoice_payments_reversals ON invoice_payments(linked_invoice_payment_id);
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 27ea80c..ecae293 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
@@ -16,6 +16,7 @@
package com.ning.billing.invoice.api.migration;
+import org.mockito.Mockito;
import org.skife.config.ConfigurationObjectFactory;
import com.ning.billing.invoice.MockModule;
@@ -24,45 +25,25 @@ import com.ning.billing.invoice.glue.DefaultInvoiceModule;
import com.ning.billing.invoice.notification.NextBillingDateNotifier;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.invoice.notification.NullInvoiceNotifier;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.util.email.templates.TemplateModule;
import com.ning.billing.util.template.translation.TranslatorConfig;
public class MockModuleNoEntitlement extends MockModule {
-// @Override
-// protected void installEntitlementModule() {
-// BillingApi entitlementApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BillingApi.class);
-// ((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));
-// ChargeThruApi cta = BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class);
-// bind(ChargeThruApi.class).toInstance(cta);
-// ((ZombieControl)cta).addResult("setChargedThroughDateFromTransaction", BrainDeadProxyFactory.ZOMBIE_VOID);
-// }
-
@Override
protected void installInvoiceModule() {
install(new DefaultInvoiceModule() {
-
@Override
protected void installNotifiers() {
- bind(NextBillingDateNotifier.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(NextBillingDateNotifier.class));
- final NextBillingDatePoster poster = BrainDeadProxyFactory.createBrainDeadProxyFor(NextBillingDatePoster.class);
- ((ZombieControl) poster).addResult("insertNextBillingNotification", BrainDeadProxyFactory.ZOMBIE_VOID);
+ bind(NextBillingDateNotifier.class).toInstance(Mockito.mock(NextBillingDateNotifier.class));
+ final NextBillingDatePoster poster = Mockito.mock(NextBillingDatePoster.class);
bind(NextBillingDatePoster.class).toInstance(poster);
bind(InvoiceNotifier.class).to(NullInvoiceNotifier.class).asEagerSingleton();
final TranslatorConfig config = new ConfigurationObjectFactory(System.getProperties()).build(TranslatorConfig.class);
bind(TranslatorConfig.class).toInstance(config);
}
-
-
});
- install(new TemplateModule());
-
+ install(new TemplateModule());
}
-
}
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 64ee7ac..5ce310f 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
@@ -22,11 +22,13 @@ import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
@@ -39,26 +41,22 @@ import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.catalog.api.Plan;
import com.ning.billing.catalog.api.PlanPhase;
-import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingModeType;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.invoice.InvoiceDispatcher;
import com.ning.billing.invoice.MockBillingEventSet;
-import com.ning.billing.invoice.TestInvoiceDispatcher;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceMigrationApi;
import com.ning.billing.invoice.api.InvoiceNotifier;
import com.ning.billing.invoice.api.InvoicePaymentApi;
import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.invoice.dao.InvoiceDao;
-import com.ning.billing.invoice.model.InvoiceGenerator;
+import com.ning.billing.invoice.generator.InvoiceGenerator;
import com.ning.billing.invoice.notification.NullInvoiceNotifier;
import com.ning.billing.invoice.tests.InvoicingTestBase;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BillingEventSet;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.bus.DefaultBusService;
import com.ning.billing.util.callcontext.CallContext;
@@ -68,11 +66,10 @@ import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
import com.ning.billing.util.globallocker.GlobalLocker;
-import com.ning.billing.util.io.IOUtils;
@Guice(modules = {MockModuleNoEntitlement.class})
public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
- final Logger log = LoggerFactory.getLogger(TestDefaultInvoiceMigrationApi.class);
+ private final Logger log = LoggerFactory.getLogger(TestDefaultInvoiceMigrationApi.class);
@Inject
InvoiceUserApi invoiceUserApi;
@@ -82,13 +79,12 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
@Inject
private InvoiceGenerator generator;
+
@Inject
private InvoiceDao invoiceDao;
- @Inject
- private GlobalLocker locker;
@Inject
- private MysqlTestingHelper helper;
+ private GlobalLocker locker;
@Inject
private BusService busService;
@@ -99,6 +95,10 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
@Inject
private BillingApi billingApi;
+ @Inject
+ private AccountUserApi accountUserApi;
+
+ private Account account;
private UUID accountId;
private UUID subscriptionId;
private DateTime date_migrated;
@@ -112,35 +112,32 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
private final Clock clock = new ClockMock();
- @BeforeClass(groups = {"slow"})
+ @BeforeSuite(groups = "slow")
public void setup() throws Exception {
- log.info("Starting set up");
+ busService.getBus().start();
+ }
+
+ @BeforeMethod(groups = "slow")
+ public void setupMethod() throws Exception {
accountId = UUID.randomUUID();
subscriptionId = UUID.randomUUID();
date_migrated = clock.getUTCNow().minusYears(1);
date_regular = clock.getUTCNow();
- final String invoiceDdl = IOUtils.toString(TestInvoiceDispatcher.class.getResourceAsStream("/com/ning/billing/invoice/ddl.sql"));
- final String utilDdl = IOUtils.toString(TestInvoiceDispatcher.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
+ account = Mockito.mock(Account.class);
+ Mockito.when(accountUserApi.getAccountById(accountId)).thenReturn(account);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(accountId);
+ Mockito.when(account.isNotifiedForInvoices()).thenReturn(true);
- helper.initDb(invoiceDdl);
- helper.initDb(utilDdl);
-
- busService.getBus().start();
-
- ((ZombieControl) billingApi).addResult("setChargedThroughDate", BrainDeadProxyFactory.ZOMBIE_VOID);
migrationInvoiceId = createAndCheckMigrationInvoice();
regularInvoiceId = generateRegularInvoice();
-
}
- @AfterClass(groups = {"slow"})
+ @AfterSuite(groups = "slow")
public void tearDown() {
try {
((DefaultBusService) busService).stopBus();
- helper.stopMysql();
} catch (Exception e) {
log.warn("Failed to tearDown test properly ", e);
}
@@ -167,16 +164,9 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
}
private UUID generateRegularInvoice() throws Exception {
- final AccountUserApi accountUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) accountUserApi).addResult("getAccountById", account);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", accountId);
- ((ZombieControl) account).addResult("isNotifiedForInvoices", true);
-
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) subscription).addResult("getId", subscriptionId);
- ((ZombieControl) subscription).addResult("getBundleId", new UUID(0L, 0L));
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(subscription.getId()).thenReturn(subscriptionId);
+ Mockito.when(subscription.getBundleId()).thenReturn(new UUID(0L, 0L));
final BillingEventSet events = new MockBillingEventSet();
final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
final PlanPhase planPhase = MockPlanPhase.create1USDMonthlyEvergreen();
@@ -187,7 +177,7 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
fixedPrice, BigDecimal.ONE, currency, BillingPeriod.MONTHLY, 1,
BillingModeType.IN_ADVANCE, "", 1L, SubscriptionTransitionType.CREATE));
- ((ZombieControl) billingApi).addResult("getBillingEventsForAccountAndUpdateAccountBCD", events);
+ Mockito.when(billingApi.getBillingEventsForAccountAndUpdateAccountBCD(accountId)).thenReturn(events);
final InvoiceNotifier invoiceNotifier = new NullInvoiceNotifier();
final InvoiceDispatcher dispatcher = new InvoiceDispatcher(generator, accountUserApi, billingApi,
@@ -209,8 +199,7 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
return invoice.getId();
}
- // Check migration invoice is NOT returned for all user api invoice calls
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testUserApiAccess() {
final List<Invoice> byAccount = invoiceUserApi.getInvoicesByAccount(accountId);
Assert.assertEquals(byAccount.size(), 1);
@@ -221,14 +210,11 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
Assert.assertEquals(byAccountAndDate.get(0).getId(), regularInvoiceId);
final Collection<Invoice> unpaid = invoiceUserApi.getUnpaidInvoicesByAccountId(accountId, date_regular.plusDays(1));
- Assert.assertEquals(unpaid.size(), 1);
- Assert.assertEquals(regularInvoiceId, unpaid.iterator().next().getId());
-
+ Assert.assertEquals(unpaid.size(), 2);
}
-
// Check migration invoice IS returned for payment api calls
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testPaymentApi() {
final List<Invoice> allByAccount = invoicePaymentApi.getAllInvoicesByAccount(accountId);
Assert.assertEquals(allByAccount.size(), 2);
@@ -236,19 +222,16 @@ public class TestDefaultInvoiceMigrationApi extends InvoicingTestBase {
Assert.assertTrue(checkContains(allByAccount, migrationInvoiceId));
}
-
// ACCOUNT balance should reflect total of migration and non-migration invoices
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testBalance() {
final Invoice migrationInvoice = invoiceDao.getById(migrationInvoiceId);
final Invoice regularInvoice = invoiceDao.getById(regularInvoiceId);
final BigDecimal balanceOfAllInvoices = migrationInvoice.getBalance().add(regularInvoice.getBalance());
final BigDecimal accountBalance = invoiceUserApi.getAccountBalance(accountId);
- System.out.println("ACCOUNT balance: " + accountBalance + " should equal the Balance Of All Invoices: " + balanceOfAllInvoices);
+ log.info("ACCOUNT balance: " + accountBalance + " should equal the Balance Of All Invoices: " + balanceOfAllInvoices);
Assert.assertEquals(accountBalance.compareTo(balanceOfAllInvoices), 0);
-
-
}
private boolean checkContains(final List<Invoice> invoices, final UUID invoiceId) {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/api/MockInvoicePaymentApi.java b/invoice/src/test/java/com/ning/billing/invoice/api/MockInvoicePaymentApi.java
index d4feb57..87183b4 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/api/MockInvoicePaymentApi.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/api/MockInvoicePaymentApi.java
@@ -26,6 +26,7 @@ import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.invoice.api.InvoicePayment.InvoicePaymentType;
import com.ning.billing.invoice.model.DefaultInvoicePayment;
import com.ning.billing.util.callcontext.CallContext;
@@ -38,9 +39,9 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context) {
+ public void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context) {
for (final InvoicePayment existingInvoicePayment : invoicePayments) {
- if (existingInvoicePayment.getInvoiceId().equals(invoicePayment.getInvoiceId()) && existingInvoicePayment.getPaymentAttemptId().equals(invoicePayment.getPaymentAttemptId())) {
+ if (existingInvoicePayment.getInvoiceId().equals(invoicePayment.getInvoiceId()) && existingInvoicePayment.getPaymentId().equals(invoicePayment.getPaymentId())) {
invoicePayments.remove(existingInvoicePayment);
}
}
@@ -70,9 +71,9 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public Invoice getInvoiceForPaymentAttemptId(final UUID paymentAttemptId) {
+ public Invoice getInvoiceForPaymentId(final UUID paymentId) {
for (final InvoicePayment invoicePayment : invoicePayments) {
- if (invoicePayment.getPaymentAttemptId().equals(paymentAttemptId)) {
+ if (invoicePayment.getPaymentId().equals(paymentId)) {
return getInvoice(invoicePayment.getInvoiceId());
}
}
@@ -80,9 +81,9 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public InvoicePayment getInvoicePayment(final UUID paymentAttemptId) {
+ public InvoicePayment getInvoicePayment(final UUID paymentId) {
for (final InvoicePayment invoicePayment : invoicePayments) {
- if (paymentAttemptId.equals(invoicePayment.getPaymentAttemptId())) {
+ if (paymentId.equals(invoicePayment.getPaymentId())) {
return invoicePayment;
}
}
@@ -90,35 +91,31 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public void notifyOfPaymentAttempt(final UUID invoiceId, final BigDecimal amountOutstanding, final Currency currency, final UUID paymentAttemptId, final DateTime paymentAttemptDate, final CallContext context) {
- final InvoicePayment invoicePayment = new DefaultInvoicePayment(paymentAttemptId, invoiceId, paymentAttemptDate, amountOutstanding, currency);
- notifyOfPaymentAttempt(invoicePayment, context);
+ public void notifyOfPayment(final UUID invoiceId, final BigDecimal amountOutstanding, final Currency currency, final UUID paymentId, final DateTime paymentDate, final CallContext context) {
+ final InvoicePayment invoicePayment = new DefaultInvoicePayment(InvoicePaymentType.ATTEMPT, paymentId, invoiceId, paymentDate, amountOutstanding, currency);
+ notifyOfPayment(invoicePayment, context);
}
@Override
- public void notifyOfPaymentAttempt(final UUID invoiceId, final UUID paymentAttemptId, final DateTime paymentAttemptDate, final CallContext context) {
- final InvoicePayment invoicePayment = new DefaultInvoicePayment(paymentAttemptId, invoiceId, paymentAttemptDate);
- notifyOfPaymentAttempt(invoicePayment, context);
- }
-
- @Override
- public InvoicePayment processChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException {
+ public InvoicePayment createChargeback(final UUID invoicePaymentId, final BigDecimal amount, final CallContext context) throws InvoiceApiException {
InvoicePayment existingPayment = null;
for (final InvoicePayment payment : invoicePayments) {
if (payment.getId() == invoicePaymentId) {
existingPayment = payment;
+ break;
}
}
if (existingPayment != null) {
- invoicePayments.add(existingPayment.asChargeBack(amount, DateTime.now(DateTimeZone.UTC)));
+ invoicePayments.add(new DefaultInvoicePayment(UUID.randomUUID(), InvoicePaymentType.CHARGED_BACK, null, null, DateTime.now(DateTimeZone.UTC), amount,
+ Currency.USD, null, existingPayment.getId()));
}
return existingPayment;
}
@Override
- public InvoicePayment processChargeback(final UUID invoicePaymentId, final CallContext context) throws InvoiceApiException {
+ public InvoicePayment createChargeback(final UUID invoicePaymentId, final CallContext context) throws InvoiceApiException {
InvoicePayment existingPayment = null;
for (final InvoicePayment payment : invoicePayments) {
if (payment.getId() == invoicePaymentId) {
@@ -127,7 +124,7 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
if (existingPayment != null) {
- this.processChargeback(invoicePaymentId, existingPayment.getAmount(), context);
+ this.createChargeback(invoicePaymentId, existingPayment.getAmount(), context);
}
return existingPayment;
@@ -141,7 +138,7 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
amount = amount.add(payment.getAmount());
}
- if (payment.getReversedInvoicePaymentId().equals(invoicePaymentId)) {
+ if (payment.getLinkedInvoicePaymentId().equals(invoicePaymentId)) {
amount = amount.add(payment.getAmount());
}
}
@@ -160,7 +157,7 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
}
@Override
- public List<InvoicePayment> getChargebacksByPaymentAttemptId(final UUID paymentAttemptId) {
+ public List<InvoicePayment> getChargebacksByPaymentId(final UUID paymentId) {
throw new UnsupportedOperationException();
}
@@ -168,4 +165,11 @@ public class MockInvoicePaymentApi implements InvoicePaymentApi {
public InvoicePayment getChargebackById(final UUID chargebackId) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public InvoicePayment createRefund(UUID paymentId,
+ BigDecimal amount, boolean isInvoiceAdjusted, UUID paymentCookieId, CallContext context)
+ throws InvoiceApiException {
+ return null;
+ }
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/api/user/TestEventJson.java b/invoice/src/test/java/com/ning/billing/invoice/api/user/TestEventJson.java
index 404255b..848a8e6 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/api/user/TestEventJson.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/api/user/TestEventJson.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.invoice.api.user;
import java.math.BigDecimal;
@@ -23,14 +24,15 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.catalog.api.Currency;
-import com.ning.billing.invoice.api.EmptyInvoiceEvent;
+import com.ning.billing.invoice.InvoiceTestSuite;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
+import com.ning.billing.invoice.api.NullInvoiceEvent;
import com.ning.billing.util.jackson.ObjectMapper;
-public class TestEventJson {
+public class TestEventJson extends InvoiceTestSuite {
private final ObjectMapper mapper = new ObjectMapper();
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testInvoiceCreationEvent() throws Exception {
final InvoiceCreationEvent e = new DefaultInvoiceCreationEvent(UUID.randomUUID(), UUID.randomUUID(), new BigDecimal(12.0), Currency.USD, new DateTime(), UUID.randomUUID());
@@ -42,14 +44,14 @@ public class TestEventJson {
Assert.assertTrue(obj.equals(e));
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testEmptyInvoiceEvent() throws Exception {
- final EmptyInvoiceEvent e = new DefaultEmptyInvoiceEvent(UUID.randomUUID(), new DateTime(), UUID.randomUUID());
+ final NullInvoiceEvent e = new DefaultNullInvoiceEvent(UUID.randomUUID(), new DateTime(), UUID.randomUUID());
final String json = mapper.writeValueAsString(e);
- final Class<?> claz = Class.forName(DefaultEmptyInvoiceEvent.class.getName());
+ final Class<?> claz = Class.forName(DefaultNullInvoiceEvent.class.getName());
final Object obj = mapper.readValue(json, claz);
Assert.assertTrue(obj.equals(e));
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/dao/InvoiceDaoTestBase.java b/invoice/src/test/java/com/ning/billing/invoice/dao/InvoiceDaoTestBase.java
index 637dd5a..78db034 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/dao/InvoiceDaoTestBase.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/dao/InvoiceDaoTestBase.java
@@ -17,6 +17,7 @@
package com.ning.billing.invoice.dao;
import java.io.IOException;
+import java.net.URL;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
@@ -26,10 +27,12 @@ import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.config.InvoiceConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
-import com.ning.billing.invoice.model.DefaultInvoiceGenerator;
-import com.ning.billing.invoice.model.InvoiceGenerator;
+import com.ning.billing.invoice.generator.DefaultInvoiceGenerator;
+import com.ning.billing.invoice.generator.InvoiceGenerator;
+import com.ning.billing.invoice.glue.InvoiceModuleWithEmbeddedDb;
import com.ning.billing.invoice.notification.MockNextBillingDatePoster;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.invoice.tests.InvoicingTestBase;
@@ -40,7 +43,6 @@ import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.TestCallContext;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
-import com.ning.billing.util.io.IOUtils;
import com.ning.billing.util.tag.api.DefaultTagUserApi;
import com.ning.billing.util.tag.api.user.TagEventBuilder;
import com.ning.billing.util.tag.dao.AuditedTagDao;
@@ -48,17 +50,15 @@ import com.ning.billing.util.tag.dao.MockTagDefinitionDao;
import com.ning.billing.util.tag.dao.TagDao;
import com.ning.billing.util.tag.dao.TagDefinitionDao;
+import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
-public abstract class InvoiceDaoTestBase extends InvoicingTestBase {
+public class InvoiceDaoTestBase extends InvoicingTestBase {
protected final TagEventBuilder tagEventBuilder = new TagEventBuilder();
protected IDBI dbi;
- private MysqlTestingHelper mysqlTestingHelper;
protected InvoiceDao invoiceDao;
- protected RecurringInvoiceItemSqlDao recurringInvoiceItemDao;
- protected FixedPriceInvoiceItemSqlDao fixedPriceInvoiceItemSqlDao;
- protected CreditInvoiceItemSqlDao creditInvoiceItemSqlDao;
+ protected InvoiceItemSqlDao invoiceItemSqlDao;
protected InvoicePaymentSqlDao invoicePaymentDao;
protected Clock clock;
protected CallContext context;
@@ -87,17 +87,28 @@ public abstract class InvoiceDaoTestBase extends InvoicingTestBase {
}
};
- @BeforeClass(alwaysRun = true)
+ private static void loadSystemPropertiesFromClasspath(final String resource) {
+ final URL url = InvoiceModuleWithEmbeddedDb.class.getResource(resource);
+ assertNotNull(url);
+ try {
+ System.getProperties().load(url.openStream());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @BeforeClass(groups = "slow")
protected void setup() throws IOException {
- mysqlTestingHelper = new MysqlTestingHelper();
+
+ loadSystemPropertiesFromClasspath("/resource.properties");
+
+ final MysqlTestingHelper mysqlTestingHelper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
dbi = mysqlTestingHelper.getDBI();
- final String invoiceDdl = IOUtils.toString(DefaultInvoiceDao.class.getResourceAsStream("/com/ning/billing/invoice/ddl.sql"));
- final String utilDdl = IOUtils.toString(DefaultInvoiceDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
+ clock = new ClockMock();
- mysqlTestingHelper.startMysql();
- mysqlTestingHelper.initDb(invoiceDdl);
- mysqlTestingHelper.initDb(utilDdl);
+ bus = new InMemoryBus();
+ bus.start();
final NextBillingDatePoster nextBillingDatePoster = new MockNextBillingDatePoster();
final TagDefinitionDao tagDefinitionDao = new MockTagDefinitionDao();
@@ -106,41 +117,18 @@ public abstract class InvoiceDaoTestBase extends InvoicingTestBase {
invoiceDao = new DefaultInvoiceDao(dbi, nextBillingDatePoster, tagUserApi);
invoiceDao.test();
- recurringInvoiceItemDao = dbi.onDemand(RecurringInvoiceItemSqlDao.class);
- fixedPriceInvoiceItemSqlDao = dbi.onDemand(FixedPriceInvoiceItemSqlDao.class);
- creditInvoiceItemSqlDao = dbi.onDemand(CreditInvoiceItemSqlDao.class);
+ invoiceItemSqlDao = dbi.onDemand(InvoiceItemSqlDao.class);
invoicePaymentDao = dbi.onDemand(InvoicePaymentSqlDao.class);
- clock = new ClockMock();
context = new TestCallContext("Invoice Dao Tests");
generator = new DefaultInvoiceGenerator(clock, invoiceConfig);
- bus = new InMemoryBus();
- bus.start();
assertTrue(true);
}
- @BeforeMethod(alwaysRun = true)
- public void cleanupData() {
- dbi.inTransaction(new TransactionCallback<Void>() {
- @Override
- public Void inTransaction(final Handle h, final TransactionStatus status)
- throws Exception {
- h.execute("truncate table invoices");
- h.execute("truncate table fixed_invoice_items");
- h.execute("truncate table recurring_invoice_items");
- h.execute("truncate table credit_invoice_items");
- h.execute("truncate table invoice_payments");
-
- return null;
- }
- });
- }
-
- @AfterClass(alwaysRun = true)
+ @AfterClass(groups = "slow")
protected void tearDown() {
bus.stop();
- mysqlTestingHelper.stopMysql();
assertTrue(true);
}
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/dao/MockInvoiceDao.java b/invoice/src/test/java/com/ning/billing/invoice/dao/MockInvoiceDao.java
index 0564bd0..a81485f 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/dao/MockInvoiceDao.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/dao/MockInvoiceDao.java
@@ -46,7 +46,7 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public void create(final Invoice invoice, final CallContext context) {
+ public void create(final Invoice invoice, final int billCycleDay, final CallContext context) {
synchronized (monitor) {
invoices.put(invoice.getId(), invoice);
}
@@ -124,11 +124,11 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public UUID getInvoiceIdByPaymentAttemptId(final UUID paymentAttemptId) {
+ public UUID getInvoiceIdByPaymentId(final UUID paymentId) {
synchronized (monitor) {
for (final Invoice invoice : invoices.values()) {
for (final InvoicePayment payment : invoice.getPayments()) {
- if (paymentAttemptId.equals(payment.getPaymentAttemptId())) {
+ if (paymentId.equals(payment.getPaymentId())) {
return invoice.getId();
}
}
@@ -138,11 +138,11 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public InvoicePayment getInvoicePayment(final UUID paymentAttemptId) {
+ public InvoicePayment getInvoicePayment(final UUID paymentId) {
synchronized (monitor) {
for (final Invoice invoice : invoices.values()) {
for (final InvoicePayment payment : invoice.getPayments()) {
- if (paymentAttemptId.equals(payment.getPaymentAttemptId())) {
+ if (paymentId.equals(payment.getPaymentId())) {
return payment;
}
}
@@ -153,7 +153,7 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public void notifyOfPaymentAttempt(final InvoicePayment invoicePayment, final CallContext context) {
+ public void notifyOfPayment(final InvoicePayment invoicePayment, final CallContext context) {
synchronized (monitor) {
final Invoice invoice = invoices.get(invoicePayment.getInvoiceId());
if (invoice != null) {
@@ -233,7 +233,7 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public List<InvoicePayment> getChargebacksByPaymentAttemptId(final UUID paymentAttemptId) {
+ public List<InvoicePayment> getChargebacksByPaymentId(final UUID paymentId) {
throw new UnsupportedOperationException();
}
@@ -248,7 +248,22 @@ public class MockInvoiceDao implements InvoiceDao {
}
@Override
- public InvoiceItem insertCredit(final UUID accountId, final BigDecimal amount, final DateTime effectiveDate, final Currency currency, final CallContext context) {
+ public InvoiceItem insertCredit(final UUID accountId, final UUID invoiceId, final BigDecimal amount, final DateTime effectiveDate, final Currency currency, final CallContext context) {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public BigDecimal getAccountCBA(UUID accountId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public InvoicePayment createRefund(UUID paymentId,
+ BigDecimal amount, boolean isInvoiceAdjusted, UUID paymentCookieId, CallContext context)
+ throws InvoiceApiException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/dao/TestDefaultInvoiceDao.java b/invoice/src/test/java/com/ning/billing/invoice/dao/TestDefaultInvoiceDao.java
index 169f2ff..e0f3ea0 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/dao/TestDefaultInvoiceDao.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/dao/TestDefaultInvoiceDao.java
@@ -25,6 +25,7 @@ import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.ning.billing.invoice.InvoiceTestSuite;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.callcontext.CallContext;
@@ -37,7 +38,7 @@ import com.ning.billing.util.tag.dao.MockTagDefinitionDao;
import com.ning.billing.util.tag.dao.TagDao;
import com.ning.billing.util.tag.dao.TagDefinitionDao;
-public class TestDefaultInvoiceDao {
+public class TestDefaultInvoiceDao extends InvoiceTestSuite {
private TagUserApi tagUserApi;
private DefaultInvoiceDao dao;
diff --git a/invoice/src/test/java/com/ning/billing/invoice/generator/TestDefaultInvoiceGeneratorUnit.java b/invoice/src/test/java/com/ning/billing/invoice/generator/TestDefaultInvoiceGeneratorUnit.java
new file mode 100644
index 0000000..1afb905
--- /dev/null
+++ b/invoice/src/test/java/com/ning/billing/invoice/generator/TestDefaultInvoiceGeneratorUnit.java
@@ -0,0 +1,332 @@
+/*
+ * 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.invoice.generator;
+
+import java.math.BigDecimal;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.config.InvoiceConfig;
+import com.ning.billing.invoice.api.Invoice;
+import com.ning.billing.invoice.api.InvoiceItem;
+import com.ning.billing.invoice.api.InvoiceItemType;
+import com.ning.billing.invoice.model.CreditBalanceAdjInvoiceItem;
+import com.ning.billing.invoice.model.FixedPriceInvoiceItem;
+import com.ning.billing.invoice.model.RecurringInvoiceItem;
+import com.ning.billing.invoice.model.RepairAdjInvoiceItem;
+import com.ning.billing.invoice.tests.InvoicingTestBase;
+import com.ning.billing.util.clock.Clock;
+import com.ning.billing.util.clock.ClockMock;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+public class TestDefaultInvoiceGeneratorUnit extends InvoicingTestBase {
+ private DefaultInvoiceGenerator gen;
+ private Clock clock;
+
+ private final UUID invoiceId = UUID.randomUUID();
+ private final UUID accountId = UUID.randomUUID();
+ private final UUID subscriptionId = UUID.randomUUID();
+ private final UUID bundleId = UUID.randomUUID();
+ private final String planName = "my-plan";
+ private final String phaseName = "my-phase";
+ private final Currency currency = Currency.USD;
+
+ public static final class TestDefaultInvoiceGeneratorMock extends DefaultInvoiceGenerator {
+ public TestDefaultInvoiceGeneratorMock(final Clock clock, final InvoiceConfig config) {
+ super(clock, config);
+ }
+ }
+
+ @BeforeClass(groups = "fast")
+ public void setup() {
+ clock = new ClockMock();
+ gen = new TestDefaultInvoiceGeneratorMock(clock, new InvoiceConfig() {
+ @Override
+ public boolean isNotificationProcessingOff() {
+ return false;
+ }
+
+ @Override
+ public boolean isEmailNotificationsEnabled() {
+ return false;
+ }
+
+ @Override
+ public long getSleepTimeMs() {
+ return 100;
+ }
+
+ @Override
+ public int getNumberOfMonthsInFuture() {
+ return 5;
+ }
+ });
+ }
+
+ @Test(groups = "fast")
+ public void testRemoveCancellingInvoiceItemsFixedPrice() {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal amount = new BigDecimal("12.00");
+ final BigDecimal rate2 = new BigDecimal("14.85");
+ final BigDecimal amount2 = rate2;
+ final List<InvoiceItem> items = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new FixedPriceInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount, currency);
+ items.add(item1);
+ items.add(new RepairAdjInvoiceItem(invoiceId, accountId, startDate, endDate, amount.negate(), currency, item1.getId()));
+ items.add(new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, endDate, nextEndDate, amount2, rate2, currency));
+ gen.removeCancellingInvoiceItems(items);
+ assertEquals(items.size(), 1);
+ final InvoiceItem leftItem = items.get(0);
+ assertEquals(leftItem.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(leftItem.getAmount(), amount2);
+ }
+
+ @Test(groups = "fast")
+ public void testRemoveCancellingInvoiceItemsRecurringPrice() {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal rate1 = new BigDecimal("12.00");
+ final BigDecimal amount1 = rate1;
+ final BigDecimal rate2 = new BigDecimal("14.85");
+ final BigDecimal amount2 = rate2;
+ final List<InvoiceItem> items = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, rate1, currency, null);
+ items.add(item1);
+ items.add(new RepairAdjInvoiceItem(invoiceId, accountId, startDate, endDate, amount1.negate(), currency, item1.getId()));
+ items.add(new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, endDate, nextEndDate, amount2, rate2, currency));
+ gen.removeCancellingInvoiceItems(items);
+ assertEquals(items.size(), 1);
+ final InvoiceItem leftItem = items.get(0);
+ assertEquals(leftItem.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(leftItem.getAmount(), amount2);
+ }
+
+ @Test(groups = "fast")
+ public void testRemoveDuplicatedInvoiceItemsFixedPrice() {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal amount1 = new BigDecimal("12.00");
+
+ final BigDecimal amount2 = new BigDecimal("14.85");
+
+ final BigDecimal rate3 = new BigDecimal("14.85");
+ final BigDecimal amount3 = rate3;
+
+ final List<InvoiceItem> existing = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new FixedPriceInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, currency);
+ existing.add(item1);
+
+ final List<InvoiceItem> proposed = new LinkedList<InvoiceItem>();
+ final InvoiceItem other = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, endDate, nextEndDate, amount3, rate3, currency, null);
+ proposed.add(item1);
+ proposed.add(other);
+
+ gen.removeDuplicatedInvoiceItems(proposed, existing);
+ assertEquals(existing.size(), 0);
+ assertEquals(proposed.size(), 1);
+ final InvoiceItem leftItem = proposed.get(0);
+ assertEquals(leftItem.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(leftItem.getAmount(), amount2);
+ }
+
+ @Test(groups = "fast")
+ public void testRemoveDuplicatedInvoiceItemsRecurringPrice() {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal rate1 = new BigDecimal("12.00");
+ final BigDecimal amount1 = rate1;
+
+ final BigDecimal rate2 = new BigDecimal("14.85");
+ final BigDecimal amount2 = rate2;
+
+ final List<InvoiceItem> existing = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, rate1, currency, null);
+ existing.add(item1);
+
+ final List<InvoiceItem> proposed = new LinkedList<InvoiceItem>();
+ final InvoiceItem other = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, endDate, nextEndDate, amount2, rate2, currency, null);
+ proposed.add(item1);
+ proposed.add(other);
+
+ gen.removeDuplicatedInvoiceItems(proposed, existing);
+ assertEquals(existing.size(), 0);
+ assertEquals(proposed.size(), 1);
+ final InvoiceItem leftItem = proposed.get(0);
+ assertEquals(leftItem.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(leftItem.getAmount(), amount2);
+ }
+
+ // STEPH same as testRemoveCancellingInvoiceItemsFixedPrice: should we have one for FixedPrice?
+ @Test(groups = "fast")
+ public void testAddRepairedItemsItemsRecurringPrice() {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal rate1 = new BigDecimal("12.00");
+ final BigDecimal amount1 = rate1;
+
+ final BigDecimal rate2 = new BigDecimal("14.85");
+ final BigDecimal amount2 = rate2;
+
+ final UUID firstInvoiceId = UUID.randomUUID();
+ final List<InvoiceItem> existing = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new RecurringInvoiceItem(firstInvoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, rate1, currency, null);
+ existing.add(item1);
+
+ final List<InvoiceItem> proposed = new LinkedList<InvoiceItem>();
+ final InvoiceItem other = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, endDate, nextEndDate, amount2, rate2, currency, null);
+ proposed.add(other);
+
+ gen.addRepairedItems(existing, proposed);
+ assertEquals(existing.size(), 1);
+ assertEquals(proposed.size(), 2);
+ final InvoiceItem leftItem1 = proposed.get(0);
+ assertEquals(leftItem1.getInvoiceId(), invoiceId);
+ assertEquals(leftItem1.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(leftItem1.getAmount(), amount2);
+
+ final InvoiceItem newItem2 = proposed.get(1);
+ assertEquals(newItem2.getInvoiceId(), firstInvoiceId);
+ assertEquals(newItem2.getInvoiceItemType(), InvoiceItemType.REPAIR_ADJ);
+ assertEquals(newItem2.getAmount(), item1.getAmount().negate());
+ assertEquals(newItem2.getLinkedItemId(), item1.getId());
+
+ }
+
+ @Test(groups = "fast")
+ public void testGenerateCreditsForPastRepairedInvoices() {
+
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal rate1 = new BigDecimal("10.00");
+ final BigDecimal amount1 = rate1;
+
+ final List<InvoiceItem> existing = new LinkedList<InvoiceItem>();
+ final InvoiceItem item1 = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, rate1, currency, null);
+ existing.add(item1);
+
+ final UUID existingInvoiceId = UUID.randomUUID();
+ final List<Invoice> existingInvoices = new LinkedList<Invoice>();
+ final Invoice existingInvoice = mock(Invoice.class);
+ when(existingInvoice.getId()).thenReturn(existingInvoiceId);
+ when(existingInvoice.getBalance()).thenReturn(BigDecimal.ZERO);
+ when(existingInvoice.getInvoiceItems()).thenReturn(existing);
+
+ final BigDecimal rate2 = new BigDecimal("20.0");
+ final BigDecimal amount2 = rate2;
+
+ final List<InvoiceItem> proposed = new LinkedList<InvoiceItem>();
+ final InvoiceItem reversedItem1 = new RepairAdjInvoiceItem(existingInvoiceId, accountId, startDate, nextEndDate, item1.getAmount().negate(), currency, item1.getId());
+ final InvoiceItem newItem1 = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount2, rate2, currency, null);
+ proposed.add(reversedItem1);
+ proposed.add(newItem1);
+
+ gen.generateCBAForExistingInvoices(accountId, existingInvoices, proposed, currency);
+
+ assertEquals(proposed.size(), 3);
+ final InvoiceItem reversedItemCheck1 = proposed.get(0);
+ assertEquals(reversedItemCheck1.getInvoiceId(), existingInvoiceId);
+ assertEquals(reversedItemCheck1.getInvoiceItemType(), InvoiceItemType.REPAIR_ADJ);
+ assertEquals(reversedItemCheck1.getAmount(), item1.getAmount().negate());
+ assertEquals(reversedItemCheck1.getLinkedItemId(), item1.getId());
+
+ final InvoiceItem newItemCheck1 = proposed.get(1);
+ assertEquals(newItemCheck1.getInvoiceId(), invoiceId);
+ assertEquals(newItemCheck1.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(newItemCheck1.getAmount(), amount2);
+
+ final InvoiceItem creditItemCheck = proposed.get(2);
+ assertEquals(creditItemCheck.getInvoiceId(), existingInvoiceId);
+ assertEquals(creditItemCheck.getInvoiceItemType(), InvoiceItemType.CBA_ADJ);
+ assertEquals(creditItemCheck.getAmount(), amount2.add(rate1.negate()));
+ }
+
+ @Test(groups = "fast")
+ public void testConsumeNotEnoughExistingCredit() {
+ testConsumeCreditInternal(new BigDecimal("12.00"), new BigDecimal("-10.00"));
+ }
+
+ @Test(groups = "fast")
+ public void testConsumeTooMuchExistingCredit() {
+ testConsumeCreditInternal(new BigDecimal("7.00"), new BigDecimal("-7.00"));
+ }
+
+ private void testConsumeCreditInternal(final BigDecimal newRate, final BigDecimal expectedNewCba) {
+ final DateTime startDate = clock.getUTCNow();
+ final DateTime endDate = startDate.plusDays(30);
+ final DateTime nextEndDate = startDate.plusMonths(1);
+
+ final BigDecimal rate1 = new BigDecimal("20.00");
+ final BigDecimal amount1 = rate1;
+
+ final BigDecimal rate2 = new BigDecimal("10.00");
+ final BigDecimal amount2 = rate2;
+
+ final UUID firstInvoiceId = UUID.randomUUID();
+ final List<InvoiceItem> existing = new LinkedList<InvoiceItem>();
+ final BigDecimal pcba1 = new BigDecimal("10.00");
+
+ final InvoiceItem item1 = new RecurringInvoiceItem(firstInvoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount1, rate1, currency, null);
+ final InvoiceItem reversedItem1 = new RepairAdjInvoiceItem(firstInvoiceId, accountId, startDate, nextEndDate, amount1.negate(), currency, item1.getId());
+ final InvoiceItem newItem1 = new RecurringInvoiceItem(firstInvoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate, endDate, amount2, rate2, currency, null);
+ final InvoiceItem cba1 = new CreditBalanceAdjInvoiceItem(firstInvoiceId, accountId, startDate, pcba1, currency);
+ existing.add(item1);
+ existing.add(reversedItem1);
+ existing.add(newItem1);
+ existing.add(cba1);
+
+ final BigDecimal newRate2 = newRate;
+ final BigDecimal newAmount2 = newRate2;
+
+ final List<InvoiceItem> proposed = new LinkedList<InvoiceItem>();
+ final InvoiceItem item2 = new RecurringInvoiceItem(invoiceId, accountId, bundleId, subscriptionId, planName, phaseName, startDate.plusMonths(1), endDate.plusMonths(1), newAmount2, newRate2, currency, null);
+ proposed.add(item2);
+
+ gen.consumeExistingCredit(invoiceId, firstInvoiceId, existing, proposed, currency);
+ assertEquals(proposed.size(), 2);
+ final InvoiceItem item2Check = proposed.get(0);
+ assertEquals(item2Check.getInvoiceId(), invoiceId);
+ assertEquals(item2Check.getInvoiceItemType(), InvoiceItemType.RECURRING);
+ assertEquals(item2Check.getAmount(), newAmount2);
+
+ final InvoiceItem cbaCheck = proposed.get(1);
+ assertEquals(cbaCheck.getInvoiceId(), invoiceId);
+ assertEquals(cbaCheck.getInvoiceItemType(), InvoiceItemType.CBA_ADJ);
+ assertEquals(cbaCheck.getAmount(), expectedNewCba);
+ }
+}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithEmbeddedDb.java b/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithEmbeddedDb.java
index 6017a5a..34b74d5 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithEmbeddedDb.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithEmbeddedDb.java
@@ -19,24 +19,20 @@ package com.ning.billing.invoice.glue;
import java.io.IOException;
import java.net.URL;
+import org.mockito.Mockito;
import org.skife.jdbi.v2.IDBI;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.catalog.glue.CatalogModule;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.invoice.api.InvoiceNotifier;
-import com.ning.billing.invoice.api.test.DefaultInvoiceTestApi;
-import com.ning.billing.invoice.api.test.InvoiceTestApi;
-import com.ning.billing.invoice.dao.InvoicePaymentSqlDao;
-import com.ning.billing.invoice.dao.RecurringInvoiceItemSqlDao;
import com.ning.billing.invoice.notification.MockNextBillingDateNotifier;
import com.ning.billing.invoice.notification.MockNextBillingDatePoster;
import com.ning.billing.invoice.notification.NextBillingDateNotifier;
import com.ning.billing.invoice.notification.NextBillingDatePoster;
import com.ning.billing.invoice.notification.NullInvoiceNotifier;
import com.ning.billing.junction.api.BillingApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockEntitlementModule;
import com.ning.billing.util.callcontext.CallContextFactory;
import com.ning.billing.util.callcontext.DefaultCallContextFactory;
@@ -53,32 +49,7 @@ import com.ning.billing.util.notificationq.NotificationQueueService;
import static org.testng.Assert.assertNotNull;
public class InvoiceModuleWithEmbeddedDb extends DefaultInvoiceModule {
- private final MysqlTestingHelper helper = new MysqlTestingHelper();
- private IDBI dbi;
-
- public void startDb() throws IOException {
- helper.startMysql();
- }
-
- public void initDb(final String ddl) throws IOException {
- helper.initDb(ddl);
- }
-
- public void stopDb() {
- helper.stopMysql();
- }
-
- public IDBI getDbi() {
- return dbi;
- }
-
- public RecurringInvoiceItemSqlDao getInvoiceItemSqlDao() {
- return dbi.onDemand(RecurringInvoiceItemSqlDao.class);
- }
-
- public InvoicePaymentSqlDao getInvoicePaymentSqlDao() {
- return dbi.onDemand(InvoicePaymentSqlDao.class);
- }
+ private final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
private void installNotificationQueue() {
bind(NotificationQueueService.class).to(MockNotificationQueueService.class).asEagerSingleton();
@@ -95,7 +66,7 @@ public class InvoiceModuleWithEmbeddedDb extends DefaultInvoiceModule {
public void configure() {
loadSystemPropertiesFromClasspath("/resource.properties");
- dbi = helper.getDBI();
+ final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
bind(Clock.class).to(DefaultClock.class).asEagerSingleton();
@@ -104,11 +75,9 @@ public class InvoiceModuleWithEmbeddedDb extends DefaultInvoiceModule {
install(new TagStoreModule());
installNotificationQueue();
-// install(new AccountModule());
- bind(AccountUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class));
+ bind(AccountUserApi.class).toInstance(Mockito.mock(AccountUserApi.class));
- final BillingApi billingApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BillingApi.class);
- ((ZombieControl) billingApi).addResult("setChargedThroughDateFromTransaction", BrainDeadProxyFactory.ZOMBIE_VOID);
+ final BillingApi billingApi = Mockito.mock(BillingApi.class);
bind(BillingApi.class).toInstance(billingApi);
install(new CatalogModule());
@@ -117,10 +86,8 @@ public class InvoiceModuleWithEmbeddedDb extends DefaultInvoiceModule {
super.configure();
- bind(InvoiceTestApi.class).to(DefaultInvoiceTestApi.class).asEagerSingleton();
install(new BusModule());
install(new TemplateModule());
-
}
private static void loadSystemPropertiesFromClasspath(final String resource) {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithMocks.java b/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithMocks.java
index 1019710..3e2a772 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithMocks.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/glue/InvoiceModuleWithMocks.java
@@ -28,7 +28,6 @@ import com.ning.billing.util.globallocker.GlobalLocker;
import com.ning.billing.util.globallocker.MockGlobalLocker;
import com.ning.billing.util.template.translation.TranslatorConfig;
-
public class InvoiceModuleWithMocks extends DefaultInvoiceModule {
@Override
protected void installInvoiceDao() {
@@ -39,7 +38,6 @@ public class InvoiceModuleWithMocks extends DefaultInvoiceModule {
@Override
protected void installInvoiceListener() {
-
}
@Override
@@ -52,11 +50,9 @@ public class InvoiceModuleWithMocks extends DefaultInvoiceModule {
@Override
protected void installInvoiceService() {
-
}
@Override
public void installInvoiceMigrationApi() {
-
}
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuite.java b/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuite.java
new file mode 100644
index 0000000..7291fce
--- /dev/null
+++ b/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.invoice;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class InvoiceTestSuite extends KillbillTestSuite {
+}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuiteWithEmbeddedDB.java b/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..de4234f
--- /dev/null
+++ b/invoice/src/test/java/com/ning/billing/invoice/InvoiceTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.invoice;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class InvoiceTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/MockModule.java b/invoice/src/test/java/com/ning/billing/invoice/MockModule.java
index 120ab0e..4b15dc3 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/MockModule.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/MockModule.java
@@ -16,15 +16,20 @@
package com.ning.billing.invoice;
+import java.io.IOException;
+import java.net.URL;
+
import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import com.google.inject.AbstractModule;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.catalog.glue.CatalogModule;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.invoice.api.formatters.InvoiceFormatterFactory;
+import com.ning.billing.invoice.api.migration.TestDefaultInvoiceMigrationApi;
import com.ning.billing.invoice.glue.DefaultInvoiceModule;
import com.ning.billing.invoice.template.formatters.DefaultInvoiceFormatterFactory;
import com.ning.billing.mock.glue.MockJunctionModule;
@@ -40,16 +45,20 @@ import com.ning.billing.util.glue.GlobalLockerModule;
import com.ning.billing.util.glue.NotificationQueueModule;
import com.ning.billing.util.glue.TagStoreModule;
+import static org.testng.Assert.assertNotNull;
+
public class MockModule extends AbstractModule {
@Override
protected void configure() {
+ loadSystemPropertiesFromClasspath("/resource.properties");
+
bind(Clock.class).to(ClockMock.class).asEagerSingleton();
bind(ClockMock.class).asEagerSingleton();
bind(CallContextFactory.class).to(DefaultCallContextFactory.class).asEagerSingleton();
install(new TagStoreModule());
install(new CustomFieldModule());
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
@@ -70,10 +79,19 @@ public class MockModule extends AbstractModule {
installInvoiceModule();
install(new MockJunctionModule());
install(new TemplateModule());
-
}
protected void installInvoiceModule() {
install(new DefaultInvoiceModule());
}
+
+ private static void loadSystemPropertiesFromClasspath(final String resource) {
+ final URL url = TestDefaultInvoiceMigrationApi.class.getResource(resource);
+ assertNotNull(url);
+ try {
+ System.getProperties().load(url.openStream());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/notification/MockNextBillingDatePoster.java b/invoice/src/test/java/com/ning/billing/invoice/notification/MockNextBillingDatePoster.java
index 1079a2f..5742247 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/notification/MockNextBillingDatePoster.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/notification/MockNextBillingDatePoster.java
@@ -23,7 +23,7 @@ import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
public class MockNextBillingDatePoster implements NextBillingDatePoster {
@Override
- public void insertNextBillingNotification(final Transmogrifier transactionalDao, final UUID subscriptionId, final DateTime futureNotificationTime) {
+ public void insertNextBillingNotification(final Transmogrifier transactionalDao, final UUID accountId, final UUID subscriptionId, final DateTime futureNotificationTime) {
// do nothing
}
}
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 f1f7614..e126ba2 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
@@ -22,6 +22,7 @@ import java.util.UUID;
import java.util.concurrent.Callable;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.Transaction;
@@ -29,26 +30,26 @@ import org.skife.jdbi.v2.TransactionStatus;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.catalog.MockCatalogModule;
import com.ning.billing.config.InvoiceConfig;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
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.invoice.InvoiceDispatcher;
import com.ning.billing.invoice.InvoiceListener;
+import com.ning.billing.invoice.InvoiceTestSuiteWithEmbeddedDB;
import com.ning.billing.invoice.glue.InvoiceModuleWithMocks;
import com.ning.billing.lifecycle.KillbillService;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.mock.glue.MockJunctionModule;
import com.ning.billing.util.bus.Bus;
@@ -60,20 +61,17 @@ import com.ning.billing.util.email.templates.TemplateModule;
import com.ning.billing.util.glue.BusModule;
import com.ning.billing.util.glue.BusModule.BusType;
import com.ning.billing.util.glue.NotificationQueueModule;
-import com.ning.billing.util.io.IOUtils;
import com.ning.billing.util.notificationq.DummySqlTest;
import com.ning.billing.util.notificationq.NotificationQueueService;
-import com.ning.billing.util.notificationq.dao.NotificationSqlDao;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.MINUTES;
-public class TestNextBillingDateNotifier {
+public class TestNextBillingDateNotifier extends InvoiceTestSuiteWithEmbeddedDB {
private Clock clock;
private DefaultNextBillingDateNotifier notifier;
private DummySqlTest dao;
private Bus eventBus;
- private MysqlTestingHelper helper;
private InvoiceListenerMock listener;
private NotificationQueueService notificationQueueService;
@@ -102,16 +100,11 @@ public class TestNextBillingDateNotifier {
}
- @BeforeMethod(groups = {"slow"})
- public void cleanDb() {
- helper.cleanupAllTables();
- }
-
@BeforeClass(groups = {"slow"})
- public void setup() throws KillbillService.ServiceException, IOException, ClassNotFoundException, SQLException {
+ public void setup() throws KillbillService.ServiceException, IOException, ClassNotFoundException, SQLException, EntitlementUserApiException {
//TestApiBase.loadSystemPropertiesFromClasspath("/entitlement.properties");
final Injector g = Guice.createInjector(Stage.PRODUCTION, new AbstractModule() {
-
+ @Override
protected void configure() {
install(new MockClockModule());
install(new BusModule(BusType.MEMORY));
@@ -121,7 +114,7 @@ public class TestNextBillingDateNotifier {
install(new NotificationQueueModule());
install(new TemplateModule());
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
@@ -131,8 +124,6 @@ public class TestNextBillingDateNotifier {
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
}
-
-
}
});
@@ -140,31 +131,22 @@ public class TestNextBillingDateNotifier {
final IDBI dbi = g.getInstance(IDBI.class);
dao = dbi.onDemand(DummySqlTest.class);
eventBus = g.getInstance(Bus.class);
- helper = g.getInstance(MysqlTestingHelper.class);
notificationQueueService = g.getInstance(NotificationQueueService.class);
final InvoiceDispatcher dispatcher = g.getInstance(InvoiceDispatcher.class);
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- final EntitlementUserApi entitlementUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- ((ZombieControl) entitlementUserApi).addResult("getSubscriptionFromId", subscription);
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ final EntitlementUserApi entitlementUserApi = Mockito.mock(EntitlementUserApi.class);
+ Mockito.when(entitlementUserApi.getSubscriptionFromId(Mockito.<UUID>any())).thenReturn(subscription);
final CallContextFactory factory = new DefaultCallContextFactory(clock);
listener = new InvoiceListenerMock(factory, dispatcher);
notifier = new DefaultNextBillingDateNotifier(notificationQueueService, g.getInstance(InvoiceConfig.class), entitlementUserApi, listener);
- startMysql();
- }
-
- private void startMysql() throws IOException, ClassNotFoundException, SQLException {
- final String ddl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- final String testDdl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
- helper.startMysql();
- helper.initDb(ddl);
- helper.initDb(testDdl);
}
-
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void testInvoiceNotifier() throws Exception {
+
+ final UUID accountId = UUID.randomUUID();
final UUID subscriptionId = new UUID(0L, 1L);
final DateTime now = new DateTime();
final DateTime readyTime = now.plusMillis(2000);
@@ -174,22 +156,19 @@ public class TestNextBillingDateNotifier {
notifier.initialize();
notifier.start();
-
dao.inTransaction(new Transaction<Void, DummySqlTest>() {
@Override
public Void inTransaction(final DummySqlTest transactional,
final TransactionStatus status) throws Exception {
- poster.insertNextBillingNotification(transactional, subscriptionId, readyTime);
+ poster.insertNextBillingNotification(transactional, accountId, subscriptionId, readyTime);
return null;
}
});
-
// Move time in the future after the notification effectiveDate
((ClockMock) clock).setDeltaFromReality(3000);
-
await().atMost(1, MINUTES).until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
@@ -204,7 +183,5 @@ public class TestNextBillingDateNotifier {
@AfterClass(groups = "slow")
public void tearDown() throws Exception {
notifier.stop();
- helper.stopMysql();
}
-
}
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 88401ec..73acc50 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/TestInvoiceDispatcher.java
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
@@ -31,6 +32,7 @@ import org.testng.annotations.Test;
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.catalog.MockPlan;
import com.ning.billing.catalog.MockPlanPhase;
@@ -46,14 +48,12 @@ import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceApiException;
import com.ning.billing.invoice.api.InvoiceNotifier;
import com.ning.billing.invoice.dao.InvoiceDao;
-import com.ning.billing.invoice.model.InvoiceGenerator;
+import com.ning.billing.invoice.generator.InvoiceGenerator;
import com.ning.billing.invoice.notification.NextBillingDateNotifier;
import com.ning.billing.invoice.notification.NullInvoiceNotifier;
import com.ning.billing.invoice.tests.InvoicingTestBase;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BillingEventSet;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.bus.DefaultBusService;
import com.ning.billing.util.callcontext.CallContext;
@@ -62,9 +62,7 @@ import com.ning.billing.util.callcontext.DefaultCallContextFactory;
import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.globallocker.GlobalLocker;
-import com.ning.billing.util.io.IOUtils;
-@Test(groups = "slow")
@Guice(modules = {MockModule.class})
public class TestInvoiceDispatcher extends InvoicingTestBase {
private final Logger log = LoggerFactory.getLogger(TestInvoiceDispatcher.class);
@@ -95,51 +93,42 @@ public class TestInvoiceDispatcher extends InvoicingTestBase {
private CallContext context;
- @BeforeSuite(groups = "slow")
+ @BeforeSuite(groups = {"slow"})
public void setup() throws Exception {
- final String invoiceDdl = IOUtils.toString(TestInvoiceDispatcher.class.getResourceAsStream("/com/ning/billing/invoice/ddl.sql"));
- final String utilDdl = IOUtils.toString(TestInvoiceDispatcher.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
-
- helper.initDb(invoiceDdl);
- helper.initDb(utilDdl);
notifier.initialize();
notifier.start();
context = new DefaultCallContextFactory(clock).createCallContext("Miracle Max", CallOrigin.TEST, UserType.TEST);
busService.getBus().start();
- ((ZombieControl) billingApi).addResult("setChargedThroughDate", BrainDeadProxyFactory.ZOMBIE_VOID);
}
- @AfterClass(alwaysRun = true)
+ @AfterClass(groups = {"slow"})
public void tearDown() {
try {
((DefaultBusService) busService).stopBus();
notifier.stop();
- helper.stopMysql();
} catch (Exception e) {
log.warn("Failed to tearDown test properly ", e);
}
}
@Test(groups = {"slow"}, enabled = true)
- public void testDryRunInvoice() throws InvoiceApiException {
+ public void testDryRunInvoice() throws InvoiceApiException, AccountApiException {
final UUID accountId = UUID.randomUUID();
final UUID subscriptionId = UUID.randomUUID();
- final AccountUserApi accountUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
+ final AccountUserApi accountUserApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
- ((ZombieControl) accountUserApi).addResult("getAccountById", account);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", accountId);
- ((ZombieControl) account).addResult(("isNotifiedForInvoices"), true);
+ Mockito.when(accountUserApi.getAccountById(accountId)).thenReturn(account);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(accountId);
+ Mockito.when(account.isNotifiedForInvoices()).thenReturn(true);
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) subscription).addResult("getId", subscriptionId);
- ((ZombieControl) subscription).addResult("getBundleId", new UUID(0L, 0L));
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(subscription.getId()).thenReturn(subscriptionId);
+ Mockito.when(subscription.getBundleId()).thenReturn(new UUID(0L, 0L));
final BillingEventSet events = new MockBillingEventSet();
final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
final PlanPhase planPhase = MockPlanPhase.create1USDMonthlyEvergreen();
@@ -150,7 +139,7 @@ public class TestInvoiceDispatcher extends InvoicingTestBase {
fixedPrice, BigDecimal.ONE, currency, BillingPeriod.MONTHLY, 1,
BillingModeType.IN_ADVANCE, "", 1L, SubscriptionTransitionType.CREATE));
- ((ZombieControl) billingApi).addResult("getBillingEventsForAccountAndUpdateAccountBCD", events);
+ Mockito.when(billingApi.getBillingEventsForAccountAndUpdateAccountBCD(accountId)).thenReturn(events);
final DateTime target = new DateTime();
@@ -181,5 +170,4 @@ public class TestInvoiceDispatcher extends InvoicingTestBase {
}
//MDW add a test to cover when the account auto-invoice-off tag is present
-
}
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/GenericProRationTests.java b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/GenericProRationTests.java
index 81d5347..4b37ad8 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/GenericProRationTests.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/annual/GenericProRationTests.java
@@ -23,7 +23,6 @@ import org.testng.annotations.Test;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.invoice.tests.inAdvance.GenericProRationTestBase;
-@Test(groups = {"fast", "invoicing", "proRation"})
public class GenericProRationTests extends GenericProRationTestBase {
@Override
protected BillingPeriod getBillingPeriod() {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/GenericProRationTestBase.java b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/GenericProRationTestBase.java
index ea37848..500ffd0 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/GenericProRationTestBase.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/GenericProRationTestBase.java
@@ -23,7 +23,6 @@ import org.testng.annotations.Test;
import com.ning.billing.invoice.model.InvalidDateSequenceException;
-@Test(groups = {"fast", "invoicing", "proRation"})
public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBase {
/**
* used for testing cancellation in less than a single billing period
@@ -32,14 +31,14 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
*/
protected abstract BigDecimal getDaysInTestPeriod();
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_OnStartDate() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
testCalculateNumberOfBillingCycles(startDate, startDate, 15, ONE);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_LessThanOnePeriod() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
final DateTime targetDate = buildDateTime(2011, 3, 1);
@@ -47,7 +46,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, ONE);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_OnePeriodLessADayAfterStart() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
final DateTime targetDate = startDate.plusMonths(getBillingPeriod().getNumberOfMonths()).plusDays(-1);
@@ -55,7 +54,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, ONE);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_ExactlyOnePeriodAfterStart() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
final DateTime targetDate = startDate.plusMonths(getBillingPeriod().getNumberOfMonths());
@@ -63,7 +62,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, TWO);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_SlightlyMoreThanOnePeriodAfterStart() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
final DateTime targetDate = startDate.plusMonths(getBillingPeriod().getNumberOfMonths()).plusDays(1);
@@ -71,7 +70,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, TWO);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_CrossingYearBoundary() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 12, 15);
final DateTime oneCycleLater = startDate.plusMonths(getBillingPeriod().getNumberOfMonths());
@@ -86,7 +85,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, oneCycleLater.plusDays(1), 15, TWO);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_StartingMidFebruary() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 2, 15);
final DateTime targetDate = startDate.plusMonths(getBillingPeriod().getNumberOfMonths());
@@ -94,7 +93,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, TWO);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_StartingMidFebruaryOfLeapYear() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2012, 2, 15);
final DateTime targetDate = startDate.plusMonths(getBillingPeriod().getNumberOfMonths());
@@ -102,7 +101,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, targetDate, 15, TWO);
}
- @Test
+ @Test(groups = "fast")
public void testSinglePlan_MovingForwardThroughTime() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 31);
BigDecimal expectedValue = ONE;
@@ -123,7 +122,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
}
// tests for cancellation in less than one period, beginning Jan 1
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateInStartDate() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 1, 1);
@@ -133,7 +132,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, endDate, targetDate, 1, expectedValue);
}
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateInSubscriptionPeriod() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 1, 7);
@@ -143,7 +142,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, endDate, targetDate, 1, expectedValue);
}
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateOnEndDate() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 1, 15);
@@ -153,7 +152,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, endDate, targetDate, 1, expectedValue);
}
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateAfterEndDateButInFirstBillingPeriod() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 1, 17);
@@ -163,7 +162,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, endDate, targetDate, 1, expectedValue);
}
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateAtEndOfFirstBillingPeriod() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 2, 1);
@@ -173,7 +172,7 @@ public abstract class GenericProRationTestBase extends ProRationInAdvanceTestBas
testCalculateNumberOfBillingCycles(startDate, endDate, targetDate, 1, expectedValue);
}
- @Test
+ @Test(groups = "fast")
public void testCancelledBeforeOnePeriod_TargetDateAfterFirstBillingPeriod() throws InvalidDateSequenceException {
final DateTime startDate = buildDateTime(2011, 1, 1);
final DateTime targetDate = buildDateTime(2011, 4, 5);
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/GenericProRationTests.java b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/GenericProRationTests.java
index b749ab8..87aeac6 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/GenericProRationTests.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/monthly/GenericProRationTests.java
@@ -23,7 +23,6 @@ import org.testng.annotations.Test;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.invoice.tests.inAdvance.GenericProRationTestBase;
-@Test(groups = {"fast", "invoicing", "proRation"})
public class GenericProRationTests extends GenericProRationTestBase {
@Override
protected BillingPeriod getBillingPeriod() {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/ProRationInAdvanceTestBase.java b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/ProRationInAdvanceTestBase.java
index b8f3848..dca4d61 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/ProRationInAdvanceTestBase.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/ProRationInAdvanceTestBase.java
@@ -22,7 +22,6 @@ import com.ning.billing.invoice.model.BillingMode;
import com.ning.billing.invoice.model.InAdvanceBillingMode;
import com.ning.billing.invoice.tests.ProRationTestBase;
-@Test(groups = {"fast", "invoicing", "proRation"})
public abstract class ProRationInAdvanceTestBase extends ProRationTestBase {
@Override
protected BillingMode getBillingMode() {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/GenericProRationTests.java b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/GenericProRationTests.java
index 3351807..72e83d1 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/GenericProRationTests.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/inAdvance/quarterly/GenericProRationTests.java
@@ -23,7 +23,6 @@ import org.testng.annotations.Test;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.invoice.tests.inAdvance.GenericProRationTestBase;
-@Test(groups = {"fast", "invoicing", "proRation"})
public class GenericProRationTests extends GenericProRationTestBase {
@Override
protected BillingPeriod getBillingPeriod() {
diff --git a/invoice/src/test/java/com/ning/billing/invoice/tests/InvoicingTestBase.java b/invoice/src/test/java/com/ning/billing/invoice/tests/InvoicingTestBase.java
index 1b4efdd..edb4450 100644
--- a/invoice/src/test/java/com/ning/billing/invoice/tests/InvoicingTestBase.java
+++ b/invoice/src/test/java/com/ning/billing/invoice/tests/InvoicingTestBase.java
@@ -31,9 +31,10 @@ import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.BillingModeType;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.invoice.InvoiceTestSuiteWithEmbeddedDB;
import com.ning.billing.invoice.model.InvoicingConfiguration;
-public abstract class InvoicingTestBase {
+public abstract class InvoicingTestBase extends InvoiceTestSuiteWithEmbeddedDB {
protected static final int NUMBER_OF_DECIMALS = InvoicingConfiguration.getNumberOfDecimals();
protected static final int ROUNDING_METHOD = InvoicingConfiguration.getRoundingMode();
diff --git a/invoice/src/test/resources/resource.properties b/invoice/src/test/resources/resource.properties
index 4e66149..b271d93 100644
--- a/invoice/src/test/resources/resource.properties
+++ b/invoice/src/test/resources/resource.properties
@@ -1 +1 @@
-com.ning.billing.invoice.maxNumberOfMonthsInFuture = 36
\ No newline at end of file
+com.ning.billing.invoice.maxNumberOfMonthsInFuture = 36
jaxrs/pom.xml 2(+1 -1)
diff --git a/jaxrs/pom.xml b/jaxrs/pom.xml
index d4ea8bf..d28944f 100644
--- a/jaxrs/pom.xml
+++ b/jaxrs/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-jaxrs</artifactId>
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/AccountTimelineJson.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/AccountTimelineJson.java
index 94ed09a..789ccc3 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/AccountTimelineJson.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/AccountTimelineJson.java
@@ -92,8 +92,10 @@ public class AccountTimelineJson {
}
this.invoices = new LinkedList<InvoiceJsonWithBundleKeys>();
for (final Invoice cur : invoices) {
- this.invoices.add(new InvoiceJsonWithBundleKeys(cur.getAmountPaid(),
- cur.getAmountCredited(),
+ this.invoices.add(new InvoiceJsonWithBundleKeys(cur.getPaidAmount(),
+ cur.getCBAAmount(),
+ cur.getCreditAdjAmount(),
+ cur.getRefundAdjAmount(),
cur.getId().toString(),
cur.getInvoiceDate(),
cur.getTargetDate(),
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/ChargebackJson.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/ChargebackJson.java
index f9b681f..2cb35fc 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/ChargebackJson.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/ChargebackJson.java
@@ -47,9 +47,9 @@ public class ChargebackJson {
public ChargebackJson(final InvoicePayment chargeback) {
this.requestedDate = null;
- this.effectiveDate = chargeback.getPaymentAttemptDate();
+ this.effectiveDate = chargeback.getPaymentDate();
this.chargebackAmount = chargeback.getAmount().negate();
- this.paymentId = chargeback.getReversedInvoicePaymentId().toString();
+ this.paymentId = chargeback.getLinkedInvoicePaymentId().toString();
this.reason = null;
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonSimple.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonSimple.java
index 2cb2447..670c0c6 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonSimple.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonSimple.java
@@ -32,25 +32,31 @@ public class InvoiceJsonSimple {
private final DateTime invoiceDate;
private final DateTime targetDate;
private final String invoiceNumber;
- private final BigDecimal credit;
private final BigDecimal balance;
+ private final BigDecimal creditAdj;
+ private final BigDecimal refundAdj;
+ private final BigDecimal cba;
private final String accountId;
public InvoiceJsonSimple() {
- this(BigDecimal.ZERO, BigDecimal.ZERO, null, null, null, null, BigDecimal.ZERO, null);
+ this(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO , BigDecimal.ZERO, null, null, null, null, BigDecimal.ZERO, null);
}
@JsonCreator
public InvoiceJsonSimple(@JsonProperty("amount") final BigDecimal amount,
- @JsonProperty("credit") final BigDecimal credit,
- @JsonProperty("invoiceId") @Nullable final String invoiceId,
- @JsonProperty("invoiceDate") @Nullable final DateTime invoiceDate,
- @JsonProperty("targetDate") @Nullable final DateTime targetDate,
- @JsonProperty("invoiceNumber") @Nullable final String invoiceNumber,
- @JsonProperty("balance") final BigDecimal balance,
- @JsonProperty("accountId") @Nullable final String accountId) {
+ @JsonProperty("cba") final BigDecimal cba,
+ @JsonProperty("creditAdj") final BigDecimal creditAdj,
+ @JsonProperty("refundAdj") final BigDecimal refundAdj,
+ @JsonProperty("invoiceId") @Nullable final String invoiceId,
+ @JsonProperty("invoiceDate") @Nullable final DateTime invoiceDate,
+ @JsonProperty("targetDate") @Nullable final DateTime targetDate,
+ @JsonProperty("invoiceNumber") @Nullable final String invoiceNumber,
+ @JsonProperty("balance") final BigDecimal balance,
+ @JsonProperty("accountId") @Nullable final String accountId) {
this.amount = amount;
- this.credit = credit;
+ this.cba = cba;
+ this.creditAdj = creditAdj;
+ this.refundAdj = refundAdj;
this.invoiceId = invoiceId;
this.invoiceDate = invoiceDate;
this.targetDate = targetDate;
@@ -60,16 +66,24 @@ public class InvoiceJsonSimple {
}
public InvoiceJsonSimple(final Invoice input) {
- this(input.getAmountCharged(), input.getAmountCredited(), input.getId().toString(), input.getInvoiceDate(),
- input.getTargetDate(), String.valueOf(input.getInvoiceNumber()), input.getBalance(), input.getAccountId().toString());
+ this(input.getChargedAmount(), input.getCBAAmount(), input.getCreditAdjAmount(), input.getRefundAdjAmount(), input.getId().toString(), input.getInvoiceDate(),
+ input.getTargetDate(), String.valueOf(input.getInvoiceNumber()), input.getBalance(), input.getAccountId().toString());
}
public BigDecimal getAmount() {
return amount;
}
- public BigDecimal getCredit() {
- return credit;
+ public BigDecimal getCBA() {
+ return cba;
+ }
+
+ public BigDecimal getCreditAdj() {
+ return creditAdj;
+ }
+
+ public BigDecimal getRefundAdj() {
+ return refundAdj;
}
public String getInvoiceId() {
@@ -118,8 +132,16 @@ public class InvoiceJsonSimple {
(balance != null && that.balance != null && balance.compareTo(that.balance) == 0))) {
return false;
}
- if (!((credit == null && that.credit == null) ||
- (credit != null && that.credit != null && credit.compareTo(that.credit) == 0))) {
+ if (!((cba == null && that.cba == null) ||
+ (cba != null && that.cba != null && cba.compareTo(that.cba) == 0))) {
+ return false;
+ }
+ if (!((creditAdj == null && that.creditAdj == null) ||
+ (creditAdj != null && that.creditAdj != null && creditAdj.compareTo(that.creditAdj) == 0))) {
+ return false;
+ }
+ if (!((refundAdj == null && that.refundAdj == null) ||
+ (refundAdj != null && that.refundAdj != null && refundAdj.compareTo(that.refundAdj) == 0))) {
return false;
}
if (!((invoiceDate == null && that.invoiceDate == null) ||
@@ -143,7 +165,9 @@ public class InvoiceJsonSimple {
@Override
public int hashCode() {
int result = amount != null ? amount.hashCode() : 0;
- result = 31 * result + (credit != null ? credit.hashCode() : 0);
+ result = 31 * result + (cba != null ? cba.hashCode() : 0);
+ result = 31 * result + (creditAdj != null ? creditAdj.hashCode() : 0);
+ result = 31 * result + (refundAdj != null ? refundAdj.hashCode() : 0);
result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
result = 31 * result + (invoiceDate != null ? invoiceDate.hashCode() : 0);
result = 31 * result + (targetDate != null ? targetDate.hashCode() : 0);
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithBundleKeys.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithBundleKeys.java
index 67d5e6a..963e78b 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithBundleKeys.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithBundleKeys.java
@@ -34,15 +34,17 @@ public class InvoiceJsonWithBundleKeys extends InvoiceJsonSimple {
@JsonCreator
public InvoiceJsonWithBundleKeys(@JsonProperty("amount") final BigDecimal amount,
- @JsonProperty("credit") final BigDecimal credit,
- @JsonProperty("invoiceId") final String invoiceId,
- @JsonProperty("invoiceDate") final DateTime invoiceDate,
- @JsonProperty("targetDate") final DateTime targetDate,
- @JsonProperty("invoiceNumber") final String invoiceNumber,
- @JsonProperty("balance") final BigDecimal balance,
- @JsonProperty("accountId") final String accountId,
- @JsonProperty("externalBundleKeys") final String bundleKeys) {
- super(amount, credit, invoiceId, invoiceDate, targetDate, invoiceNumber, balance, accountId);
+ @JsonProperty("cba") final BigDecimal cba,
+ @JsonProperty("creditAdj") final BigDecimal creditAdj,
+ @JsonProperty("refundAdj") final BigDecimal refundAdj,
+ @JsonProperty("invoiceId") final String invoiceId,
+ @JsonProperty("invoiceDate") final DateTime invoiceDate,
+ @JsonProperty("targetDate") final DateTime targetDate,
+ @JsonProperty("invoiceNumber") final String invoiceNumber,
+ @JsonProperty("balance") final BigDecimal balance,
+ @JsonProperty("accountId") final String accountId,
+ @JsonProperty("externalBundleKeys") final String bundleKeys) {
+ super(amount, cba, creditAdj, refundAdj, invoiceId, invoiceDate, targetDate, invoiceNumber, balance, accountId);
this.bundleKeys = bundleKeys;
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithItems.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithItems.java
index 6c5445e..ab26af2 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithItems.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/InvoiceJsonWithItems.java
@@ -33,15 +33,17 @@ public class InvoiceJsonWithItems extends InvoiceJsonSimple {
@JsonCreator
public InvoiceJsonWithItems(@JsonProperty("amount") final BigDecimal amount,
- @JsonProperty("credit") final BigDecimal credit,
- @JsonProperty("invoiceId") final String invoiceId,
- @JsonProperty("invoiceDate") final DateTime invoiceDate,
- @JsonProperty("targetDate") final DateTime targetDate,
- @JsonProperty("invoiceNumber") final String invoiceNumber,
- @JsonProperty("balance") final BigDecimal balance,
- @JsonProperty("accountId") final String accountId,
- @JsonProperty("items") final List<InvoiceItemJsonSimple> items) {
- super(amount, credit, invoiceId, invoiceDate, targetDate, invoiceNumber, balance, accountId);
+ @JsonProperty("cba") final BigDecimal cba,
+ @JsonProperty("creditAdj") final BigDecimal creditAdj,
+ @JsonProperty("refundAdj") final BigDecimal refundAdj,
+ @JsonProperty("invoiceId") final String invoiceId,
+ @JsonProperty("invoiceDate") final DateTime invoiceDate,
+ @JsonProperty("targetDate") final DateTime targetDate,
+ @JsonProperty("invoiceNumber") final String invoiceNumber,
+ @JsonProperty("balance") final BigDecimal balance,
+ @JsonProperty("accountId") final String accountId,
+ @JsonProperty("items") final List<InvoiceItemJsonSimple> items) {
+ super(amount, cba, creditAdj, refundAdj, invoiceId, invoiceDate, targetDate, invoiceNumber, balance, accountId);
this.items = new ArrayList<InvoiceItemJsonSimple>(items);
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/RefundJson.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/RefundJson.java
new file mode 100644
index 0000000..f65f6d7
--- /dev/null
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/RefundJson.java
@@ -0,0 +1,125 @@
+/*
+ * 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.jaxrs.json;
+
+import java.math.BigDecimal;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.ning.billing.payment.api.Refund;
+
+
+public class RefundJson {
+
+ private final String refundId;
+ private final String paymentId;
+ private final BigDecimal refundAmount;
+ private final Boolean isAdjusted;
+
+ public RefundJson(Refund input) {
+ this(input.getId().toString(), input.getPaymentId().toString(), input.getRefundAmount(), input.isAdjusted());
+ }
+
+ @JsonCreator
+ public RefundJson(@JsonProperty("refund_id") final String refundId,
+ @JsonProperty("paymentId") String paymentId,
+ @JsonProperty("refundAmount") BigDecimal refundAmount,
+ @JsonProperty("adjusted") final Boolean isAdjusted) {
+ this.refundId = refundId;
+ this.paymentId = paymentId;
+ this.refundAmount = refundAmount;
+ this.isAdjusted = isAdjusted;
+ }
+
+ public RefundJson() {
+ this(null, null, null, null);
+ }
+
+ public String getRefundId() {
+ return refundId;
+ }
+
+ public String getPaymentId() {
+ return paymentId;
+ }
+
+ public BigDecimal getRefundAmount() {
+ return refundAmount;
+ }
+
+ public boolean isAdjusted() {
+ return isAdjusted;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((isAdjusted == null) ? 0 : isAdjusted.hashCode());
+ result = prime * result
+ + ((paymentId == null) ? 0 : paymentId.hashCode());
+ result = prime * result
+ + ((refundAmount == null) ? 0 : refundAmount.hashCode());
+ result = prime * result
+ + ((refundId == null) ? 0 : refundId.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (! this.equalsNoId(obj)) {
+ return false;
+ } else {
+ RefundJson other = (RefundJson) obj;
+ if (getRefundId() == null) {
+ return other.getRefundId() == null;
+ } else {
+ return getRefundId().equals(other.getRefundId());
+ }
+ }
+ }
+
+ public boolean equalsNoId(final Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ RefundJson other = (RefundJson) obj;
+ if (isAdjusted == null) {
+ if (other.isAdjusted != null)
+ return false;
+ } else if (!isAdjusted.equals(other.isAdjusted))
+ return false;
+ if (paymentId == null) {
+ if (other.paymentId != null)
+ return false;
+ } else if (!paymentId.equals(other.paymentId))
+ return false;
+ if (refundAmount == null) {
+ if (other.refundAmount != null)
+ return false;
+ } else if (!refundAmount.equals(other.refundAmount)) {
+ return false;
+ }
+ return true;
+ }
+
+
+}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/SubscriptionJsonNoEvents.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/SubscriptionJsonNoEvents.java
index 3c7b2f6..988daed 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/json/SubscriptionJsonNoEvents.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/json/SubscriptionJsonNoEvents.java
@@ -39,6 +39,8 @@ public class SubscriptionJsonNoEvents extends SubscriptionJsonSimple {
private final DateTime chargedThroughDate;
+ private final DateTime cancelledDate;
+
@JsonCreator
public SubscriptionJsonNoEvents(@JsonProperty("subscriptionId") @Nullable final String subscriptionId,
@JsonProperty("bundleId") @Nullable final String bundleId,
@@ -47,7 +49,8 @@ public class SubscriptionJsonNoEvents extends SubscriptionJsonSimple {
@JsonProperty("productCategory") @Nullable final String productCategory,
@JsonProperty("billingPeriod") @Nullable final String billingPeriod,
@JsonProperty("priceList") @Nullable final String priceList,
- @JsonProperty("chargedThroughDate") @Nullable final DateTime chargedThroughDate) {
+ @JsonProperty("chargedThroughDate") @Nullable final DateTime chargedThroughDate,
+ @JsonProperty("cancelledDate") @Nullable final DateTime cancelledDate) {
super(subscriptionId);
this.bundleId = bundleId;
this.startDate = startDate;
@@ -56,18 +59,21 @@ public class SubscriptionJsonNoEvents extends SubscriptionJsonSimple {
this.billingPeriod = billingPeriod;
this.priceList = priceList;
this.chargedThroughDate = chargedThroughDate;
+ this.cancelledDate = cancelledDate;
}
public SubscriptionJsonNoEvents() {
- this(null, null, null, null, null, null, null, null);
+ this(null, null, null, null, null, null, null, null, null);
}
public SubscriptionJsonNoEvents(final Subscription data) {
this(data.getId().toString(), data.getBundleId().toString(), data.getStartDate(), data.getCurrentPlan().getProduct().getName(),
data.getCurrentPlan().getProduct().getCategory().toString(), data.getCurrentPlan().getBillingPeriod().toString(),
- data.getCurrentPriceList().getName(), data.getChargedThroughDate());
+ data.getCurrentPriceList().getName(), data.getChargedThroughDate(),
+ data.getEndDate() != null ? data.getEndDate() : data.getFutureEndDate());
}
+ @Override
public String getSubscriptionId() {
return subscriptionId;
}
@@ -100,6 +106,10 @@ public class SubscriptionJsonNoEvents extends SubscriptionJsonSimple {
return chargedThroughDate;
}
+ public DateTime getCancelledDate() {
+ return cancelledDate;
+ }
+
@Override
public String toString() {
return "SubscriptionJson [subscriptionId=" + subscriptionId
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 1b3f9ce..0dec7e0 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
@@ -16,6 +16,14 @@
package com.ning.billing.jaxrs.resources;
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.UUID;
+
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
@@ -30,11 +38,6 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,6 +68,7 @@ import com.ning.billing.jaxrs.json.CustomFieldJson;
import com.ning.billing.jaxrs.json.InvoiceEmailJson;
import com.ning.billing.jaxrs.json.PaymentJsonSimple;
import com.ning.billing.jaxrs.json.PaymentMethodJson;
+import com.ning.billing.jaxrs.json.RefundJson;
import com.ning.billing.jaxrs.util.Context;
import com.ning.billing.jaxrs.util.JaxrsUriBuilder;
import com.ning.billing.jaxrs.util.TagHelper;
@@ -72,19 +76,18 @@ import com.ning.billing.payment.api.Payment;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentApiException;
import com.ning.billing.payment.api.PaymentMethod;
+import com.ning.billing.payment.api.Refund;
import com.ning.billing.util.api.CustomFieldUserApi;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.dao.ObjectType;
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
-
@Singleton
@Path(JaxrsResource.ACCOUNTS_PATH)
public class AccountResource extends JaxRsResourceBase {
private static final Logger log = LoggerFactory.getLogger(AccountResource.class);
private static final String ID_PARAM_NAME = "accountId";
- private static final String CUSTOM_FIELD_URI = JaxrsResource.CUSTOM_FIELDS + "/{" + ID_PARAM_NAME + ":" + UUID_PATTERN + "}";
- private static final String TAG_URI = JaxrsResource.TAGS + "/{" + ID_PARAM_NAME + ":" + UUID_PATTERN + "}";
+ private static final String CUSTOM_FIELD_URI = JaxrsResource.CUSTOM_FIELDS;
+ private static final String TAG_URI = JaxrsResource.TAGS;
private final AccountUserApi accountApi;
private final EntitlementUserApi entitlementApi;
@@ -125,7 +128,11 @@ public class AccountResource extends JaxRsResourceBase {
final AccountJson json = new AccountJson(account);
return Response.status(Status.OK).entity(json).build();
} catch (AccountApiException e) {
- return Response.status(Status.NO_CONTENT).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -147,7 +154,11 @@ public class AccountResource extends JaxRsResourceBase {
});
return Response.status(Status.OK).entity(result).build();
} catch (AccountApiException e) {
- return Response.status(Status.NO_CONTENT).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -165,7 +176,11 @@ public class AccountResource extends JaxRsResourceBase {
final AccountJson json = new AccountJson(account);
return Response.status(Status.OK).entity(json).build();
} catch (AccountApiException e) {
- return Response.status(Status.NO_CONTENT).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_KEY.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -252,7 +267,11 @@ public class AccountResource extends JaxRsResourceBase {
final AccountTimelineJson json = new AccountTimelineJson(account, invoices, payments, bundlesTimeline);
return Response.status(Status.OK).entity(json).build();
} catch (AccountApiException e) {
- return Response.status(Status.NO_CONTENT).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
} catch (PaymentApiException e) {
log.error(e.getMessage());
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
@@ -276,7 +295,11 @@ public class AccountResource extends JaxRsResourceBase {
return Response.status(Status.OK).entity(invoiceEmailJson).build();
} catch (AccountApiException e) {
- return Response.status(Status.NOT_FOUND).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -299,7 +322,11 @@ public class AccountResource extends JaxRsResourceBase {
return Response.status(Status.OK).build();
} catch (AccountApiException e) {
- return Response.status(Status.NOT_FOUND).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -321,7 +348,7 @@ public class AccountResource extends JaxRsResourceBase {
}
return Response.status(Status.OK).entity(result).build();
} catch (PaymentApiException e) {
- return Response.status(Status.NOT_FOUND).build();
+ return Response.status(Status.BAD_REQUEST).build();
}
}
@@ -342,9 +369,11 @@ public class AccountResource extends JaxRsResourceBase {
final UUID paymentMethodId = paymentApi.addPaymentMethod(data.getPluginName(), account, isDefault, data.getPluginDetail(), context.createContext(createdBy, reason, comment));
return uriBuilder.buildResponse(PaymentMethodResource.class, "getPaymentMethod", paymentMethodId, uriInfo.getBaseUri().toString());
} catch (AccountApiException e) {
- final String error = String.format("Failed to create account %s", json);
- log.info(error, e);
- return Response.status(Status.BAD_REQUEST).entity(error).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
} catch (PaymentApiException e) {
final String error = String.format("Failed to create payment Method %s", json);
log.info(error, e);
@@ -376,7 +405,11 @@ public class AccountResource extends JaxRsResourceBase {
} catch (PaymentApiException e) {
return Response.status(Status.NOT_FOUND).build();
} catch (AccountApiException e) {
- return Response.status(Status.NOT_FOUND).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
}
@@ -394,7 +427,11 @@ public class AccountResource extends JaxRsResourceBase {
paymentApi.setDefaultPaymentMethod(account, UUID.fromString(paymentMethodId), context.createContext(createdBy, reason, comment));
return Response.status(Status.OK).build();
} catch (AccountApiException e) {
- return Response.status(Status.BAD_REQUEST).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
} catch (PaymentApiException e) {
return Response.status(Status.NOT_FOUND).build();
} catch (IllegalArgumentException e) {
@@ -402,19 +439,51 @@ public class AccountResource extends JaxRsResourceBase {
}
}
+
+ /*
+ * ************************** REFUNDS ********************************
+ */
+ @GET
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + REFUNDS)
+ @Produces(APPLICATION_JSON)
+ public Response getRefunds(@PathParam("accountId") final String accountId) {
+
+ try {
+ final Account account = accountApi.getAccountById(UUID.fromString(accountId));
+ List<Refund> refunds = paymentApi.getAccountRefunds(account);
+ List<RefundJson> result = new ArrayList<RefundJson>(Collections2.transform(refunds, new Function<Refund, RefundJson>() {
+ @Override
+ public RefundJson apply(Refund input) {
+ return new RefundJson(input);
+ }
+ }));
+ return Response.status(Status.OK).entity(result).build();
+ } catch (AccountApiException e) {
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ } catch (PaymentApiException e) {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ }
+
+
+
/*
* ************************* CUSTOM FIELDS *****************************
*/
@GET
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Produces(APPLICATION_JSON)
public Response getCustomFields(@PathParam(ID_PARAM_NAME) final String id) {
return super.getCustomFields(UUID.fromString(id));
}
@POST
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response createCustomFields(@PathParam(ID_PARAM_NAME) final String id,
@@ -427,7 +496,7 @@ public class AccountResource extends JaxRsResourceBase {
}
@DELETE
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response deleteCustomFields(@PathParam(ID_PARAM_NAME) final String id,
@@ -444,15 +513,14 @@ public class AccountResource extends JaxRsResourceBase {
*/
@GET
- @Path(TAG_URI)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + TAG_URI)
@Produces(APPLICATION_JSON)
public Response getTags(@PathParam(ID_PARAM_NAME) final String id) {
return super.getTags(UUID.fromString(id));
}
@POST
- @Path(TAG_URI)
- @Consumes(APPLICATION_JSON)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + TAG_URI)
@Produces(APPLICATION_JSON)
public Response createTags(@PathParam(ID_PARAM_NAME) final String id,
@QueryParam(QUERY_TAGS) final String tagList,
@@ -464,7 +532,7 @@ public class AccountResource extends JaxRsResourceBase {
}
@DELETE
- @Path(TAG_URI)
+ @Path("/{accountId:" + UUID_PATTERN + "}/" + TAG_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response deleteTags(@PathParam(ID_PARAM_NAME) final String id,
@@ -518,7 +586,11 @@ public class AccountResource extends JaxRsResourceBase {
} catch (RuntimeException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (AccountApiException e) {
- return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).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 33d7965..5e8877c 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
@@ -59,8 +59,8 @@ public class BundleResource extends JaxRsResourceBase {
private static final Logger log = LoggerFactory.getLogger(BundleResource.class);
private static final String ID_PARAM_NAME = "bundleId";
- private static final String CUSTOM_FIELD_URI = JaxrsResource.CUSTOM_FIELDS + "/{" + ID_PARAM_NAME + ":" + UUID_PATTERN + "}";
- private static final String TAG_URI = JaxrsResource.TAGS + "/{" + ID_PARAM_NAME + ":" + UUID_PATTERN + "}";
+ private static final String CUSTOM_FIELD_URI = JaxrsResource.CUSTOM_FIELDS;
+ private static final String TAG_URI = JaxrsResource.TAGS;
private final EntitlementUserApi entitlementApi;
private final Context context;
@@ -160,14 +160,14 @@ public class BundleResource extends JaxRsResourceBase {
}
@GET
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Produces(APPLICATION_JSON)
public Response getCustomFields(@PathParam(ID_PARAM_NAME) final String id) {
return super.getCustomFields(UUID.fromString(id));
}
@POST
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response createCustomFields(@PathParam(ID_PARAM_NAME) final String id,
@@ -180,7 +180,7 @@ public class BundleResource extends JaxRsResourceBase {
}
@DELETE
- @Path(CUSTOM_FIELD_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + CUSTOM_FIELD_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response deleteCustomFields(@PathParam(ID_PARAM_NAME) final String id,
@@ -193,14 +193,14 @@ public class BundleResource extends JaxRsResourceBase {
}
@GET
- @Path(TAG_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + TAG_URI)
@Produces(APPLICATION_JSON)
public Response getTags(@PathParam(ID_PARAM_NAME) final String id) {
return super.getTags(UUID.fromString(id));
}
@POST
- @Path(TAG_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + TAG_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response createTags(@PathParam(ID_PARAM_NAME) final String id,
@@ -213,7 +213,7 @@ public class BundleResource extends JaxRsResourceBase {
}
@DELETE
- @Path(TAG_URI)
+ @Path("/{bundleId:" + UUID_PATTERN + "}/" + TAG_URI)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response deleteTags(@PathParam(ID_PARAM_NAME) final String id,
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/ChargebackResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/ChargebackResource.java
index 8823018..5920cc2 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/ChargebackResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/ChargebackResource.java
@@ -59,7 +59,6 @@ public class ChargebackResource implements JaxrsResource {
private final JaxrsUriBuilder uriBuilder;
private final InvoicePaymentApi invoicePaymentApi;
- private final PaymentApi paymentApi;
private final Context context;
@Inject
@@ -69,7 +68,6 @@ public class ChargebackResource implements JaxrsResource {
final Context context) {
this.uriBuilder = uriBuilder;
this.invoicePaymentApi = invoicePaymentApi;
- this.paymentApi = paymentApi;
this.context = context;
}
@@ -106,20 +104,7 @@ public class ChargebackResource implements JaxrsResource {
public Response getForPayment(@PathParam("paymentId") final String paymentId) {
try {
- final Payment payment = paymentApi.getPayment(UUID.fromString(paymentId));
- final Collection<PaymentAttempt> attempts = Collections2.filter(payment.getAttempts(), new Predicate<PaymentAttempt>() {
- @Override
- public boolean apply(final PaymentAttempt input) {
- return input.getPaymentStatus() == PaymentStatus.SUCCESS;
- }
- });
- if (attempts.size() == 0) {
- final String error = String.format("Failed to locate successful payment attempts for paymentId %s", paymentId);
- return Response.status(Response.Status.NO_CONTENT).entity(error).build();
- }
- final UUID paymentAttemptId = attempts.iterator().next().getId();
-
- final List<InvoicePayment> chargebacks = invoicePaymentApi.getChargebacksByPaymentAttemptId(paymentAttemptId);
+ final List<InvoicePayment> chargebacks = invoicePaymentApi.getChargebacksByPaymentId(UUID.fromString(paymentId));
if (chargebacks.size() == 0) {
return Response.status(Response.Status.NO_CONTENT).build();
}
@@ -130,9 +115,6 @@ public class ChargebackResource implements JaxrsResource {
final ChargebackCollectionJson json = new ChargebackCollectionJson(accountId, chargebacksJson);
return Response.status(Response.Status.OK).entity(json).build();
- } catch (PaymentApiException e) {
- final String error = String.format("Failed to locate payment attempt for payment id %s", paymentId);
- return Response.status(Response.Status.NO_CONTENT).entity(error).build();
} catch (InvoiceApiException e) {
final String error = String.format("Failed to locate account for payment id %s", paymentId);
return Response.status(Response.Status.NO_CONTENT).entity(error).build();
@@ -147,26 +129,13 @@ public class ChargebackResource implements JaxrsResource {
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment) {
try {
- final Payment payment = paymentApi.getPayment(UUID.fromString(json.getPaymentId()));
- final Collection<PaymentAttempt> attempts = Collections2.filter(payment.getAttempts(), new Predicate<PaymentAttempt>() {
- @Override
- public boolean apply(final PaymentAttempt input) {
- return input.getPaymentStatus() == PaymentStatus.SUCCESS;
- }
- });
- if (attempts.size() == 0) {
- final String error = String.format("Failed to locate successful payment attempts for paymentId %s", json.getPaymentId());
- return Response.status(Response.Status.NO_CONTENT).entity(error).build();
- }
-
- final UUID paymentAttemptId = attempts.iterator().next().getId();
- final InvoicePayment invoicePayment = invoicePaymentApi.getInvoicePayment(paymentAttemptId);
+ final InvoicePayment invoicePayment = invoicePaymentApi.getInvoicePayment(UUID.fromString(json.getPaymentId()));
if (invoicePayment == null) {
- final String error = String.format("Failed to locate invoice payment for paymentAttemptId %s", paymentAttemptId);
- return Response.status(Response.Status.NO_CONTENT).entity(error).build();
+ final String error = String.format("Failed to locate invoice payment for paymentAttemptId %s", json.getPaymentId());
+ return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
- final InvoicePayment chargeBack = invoicePaymentApi.processChargeback(invoicePayment.getId(), json.getChargebackAmount(),
+ final InvoicePayment chargeBack = invoicePaymentApi.createChargeback(invoicePayment.getId(), json.getChargebackAmount(),
context.createContext(createdBy, reason, comment));
return uriBuilder.buildResponse(ChargebackResource.class, "getChargeback", chargeBack.getId());
} catch (InvoiceApiException e) {
@@ -175,8 +144,6 @@ public class ChargebackResource implements JaxrsResource {
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
} catch (IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
- } catch (PaymentApiException e) {
- return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/InvoiceResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/InvoiceResource.java
index 822e0ab..1144a36 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/InvoiceResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/InvoiceResource.java
@@ -208,6 +208,9 @@ public class InvoiceResource extends JaxRsResourceBase {
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment) {
+ if (externalPayment) {
+ return Response.status(Status.BAD_REQUEST).entity("External payments have not been implemented yet").build();
+ }
try {
final Account account = accountApi.getAccountById(UUID.fromString(payment.getAccountId()));
paymentApi.createPayment(account, UUID.fromString(payment.getInvoiceId()), null, context.createContext(createdBy, reason, comment));
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxrsResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxrsResource.java
index 16c6bc5..984f633 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxrsResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxrsResource.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -79,6 +79,9 @@ public interface JaxrsResource {
public static final String PAYMENTS = "payments";
public static final String PAYMENTS_PATH = PREFIX + "/" + PAYMENTS;
+ public static final String REFUNDS = "refunds";
+ public static final String REFUNDS_PATH = PREFIX + "/" + "refunds";
+
public static final String PAYMENT_METHODS = "paymentMethods";
public static final String PAYMENT_METHODS_PATH = PREFIX + "/" + PAYMENT_METHODS;
public static final String PAYMENT_METHODS_DEFAULT_PATH_POSTFIX = "setDefault";
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxRsResourceBase.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxRsResourceBase.java
index bdff8e8..8dc98a9 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxRsResourceBase.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/JaxRsResourceBase.java
@@ -42,10 +42,11 @@ import com.ning.billing.util.tag.Tag;
import com.ning.billing.util.tag.TagDefinition;
public abstract class JaxRsResourceBase implements JaxrsResource {
- private final JaxrsUriBuilder uriBuilder;
- private final TagUserApi tagUserApi;
- private final TagHelper tagHelper;
- private final CustomFieldUserApi customFieldUserApi;
+
+ protected final JaxrsUriBuilder uriBuilder;
+ protected final TagUserApi tagUserApi;
+ protected final TagHelper tagHelper;
+ protected final CustomFieldUserApi customFieldUserApi;
protected abstract ObjectType getObjectType();
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/PaymentResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/PaymentResource.java
index 5f53ab3..faaccb5 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/PaymentResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/PaymentResource.java
@@ -26,14 +26,31 @@ 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.UriInfo;
+import javax.ws.rs.core.Response.Status;
+
+import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+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.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.jaxrs.json.AccountJson;
import com.ning.billing.jaxrs.json.CustomFieldJson;
+import com.ning.billing.jaxrs.json.RefundJson;
import com.ning.billing.jaxrs.util.Context;
import com.ning.billing.jaxrs.util.JaxrsUriBuilder;
import com.ning.billing.jaxrs.util.TagHelper;
+import com.ning.billing.payment.api.Payment;
+import com.ning.billing.payment.api.PaymentApi;
+import com.ning.billing.payment.api.PaymentApiException;
+import com.ning.billing.payment.api.Refund;
import com.ning.billing.util.api.CustomFieldUserApi;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.dao.ObjectType;
@@ -48,13 +65,71 @@ public class PaymentResource extends JaxRsResourceBase {
private static final String TAG_URI = JaxrsResource.TAGS + "/{" + ID_PARAM_NAME + ":" + UUID_PATTERN + "}";
private final Context context;
+ private final PaymentApi paymentApi;
+ private final AccountUserApi accountApi;
@Inject
- public PaymentResource(final JaxrsUriBuilder uriBuilder, final TagUserApi tagUserApi,
- final TagHelper tagHelper, final CustomFieldUserApi customFieldUserApi,
- final Context context) {
+ public PaymentResource(final JaxrsUriBuilder uriBuilder,
+ final AccountUserApi accountApi,
+ final PaymentApi paymentApi,
+ final TagUserApi tagUserApi,
+ final TagHelper tagHelper,
+ final CustomFieldUserApi customFieldUserApi,
+ final Context context) {
super(uriBuilder, tagUserApi, tagHelper, customFieldUserApi);
this.context = context;
+ this.paymentApi = paymentApi;
+ this.accountApi = accountApi;
+ }
+
+
+ @GET
+ @Path("/{paymentId:" + UUID_PATTERN + "}/" + REFUNDS)
+ @Produces(APPLICATION_JSON)
+ public Response getRefunds(@PathParam("paymentId") final String paymentId) {
+
+ try {
+ List<Refund> refunds = paymentApi.getPaymentRefunds(UUID.fromString(paymentId));
+ List<RefundJson> result = new ArrayList<RefundJson>(Collections2.transform(refunds, new Function<Refund, RefundJson>() {
+ @Override
+ public RefundJson apply(Refund input) {
+ return new RefundJson(input);
+ }
+ }));
+ return Response.status(Status.OK).entity(result).build();
+ } catch (PaymentApiException e) {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ }
+
+ @POST
+ @Path("/{paymentId:" + UUID_PATTERN + "}/" + REFUNDS)
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ public Response createRefund(final RefundJson json,
+ @PathParam("paymentId") final String paymentId,
+ @HeaderParam(HDR_CREATED_BY) final String createdBy,
+ @HeaderParam(HDR_REASON) final String reason,
+ @HeaderParam(HDR_COMMENT) final String comment,
+ @javax.ws.rs.core.Context final UriInfo uriInfo) {
+
+ try {
+ final UUID paymentUuid = UUID.fromString(paymentId);
+ final Payment payment = paymentApi.getPayment(paymentUuid);
+
+ final Account account = accountApi.getAccountById(payment.getAccountId());
+
+ Refund result = paymentApi.createRefund(account, paymentUuid, json.getRefundAmount(), json.isAdjusted(), context.createContext(createdBy, reason, comment));
+ return uriBuilder.buildResponse(RefundResource.class, "getRefund", result.getId(), uriInfo.getBaseUri().toString());
+ } catch (AccountApiException e) {
+ if (e.getCode() == ErrorCode.ACCOUNT_DOES_NOT_EXIST_FOR_ID.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ } catch (PaymentApiException e) {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
}
@GET
diff --git a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/RefundResource.java b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/RefundResource.java
index 05acf58..6a5a729 100644
--- a/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/RefundResource.java
+++ b/jaxrs/src/main/java/com/ning/billing/jaxrs/resources/RefundResource.java
@@ -16,6 +16,72 @@
package com.ning.billing.jaxrs.resources;
-public class RefundResource {
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.Inject;
+import com.ning.billing.ErrorCode;
+import com.ning.billing.jaxrs.json.RefundJson;
+import com.ning.billing.jaxrs.util.Context;
+import com.ning.billing.jaxrs.util.JaxrsUriBuilder;
+import com.ning.billing.jaxrs.util.TagHelper;
+import com.ning.billing.payment.api.PaymentApi;
+import com.ning.billing.payment.api.PaymentApiException;
+import com.ning.billing.payment.api.Refund;
+import com.ning.billing.util.api.CustomFieldUserApi;
+import com.ning.billing.util.api.TagUserApi;
+import com.ning.billing.util.dao.ObjectType;
+
+
+@Path(JaxrsResource.REFUNDS_PATH)
+public class RefundResource extends JaxRsResourceBase {
+
+ private static final Logger log = LoggerFactory.getLogger(RefundResource.class);
+
+ private final PaymentApi paymentApi;
+
+ @Inject
+ public RefundResource(final JaxrsUriBuilder uriBuilder,
+ final PaymentApi paymentApi,
+ final TagUserApi tagUserApi,
+ final TagHelper tagHelper,
+ final CustomFieldUserApi customFieldUserApi,
+ final Context context) {
+ super(uriBuilder, tagUserApi, tagHelper, customFieldUserApi);
+ this.paymentApi = paymentApi;
+ }
+
+ @GET
+ @Path("/{refundId:" + UUID_PATTERN + "}")
+ @Produces(APPLICATION_JSON)
+ public Response getRefund(@PathParam("refundId") final String refundId) {
+ try {
+ Refund refund = paymentApi.getRefund(UUID.fromString(refundId));
+ return Response.status(Status.OK).entity(new RefundJson(refund)).build();
+ } catch (PaymentApiException e) {
+ if (e.getCode() == ErrorCode.PAYMENT_NO_SUCH_REFUND.getCode()) {
+ return Response.status(Status.NO_CONTENT).build();
+ } else {
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ }
+ }
+
+ @Override
+ protected ObjectType getObjectType() {
+ return ObjectType.REFUND;
+ }
}
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 fe79b2a..6cb4de1 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
@@ -45,11 +45,11 @@ 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;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.SubscriptionEvent;
-import com.ning.billing.invoice.api.EmptyInvoiceEvent;
+import com.ning.billing.invoice.api.NullInvoiceEvent;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.jaxrs.json.CustomFieldJson;
import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
@@ -289,13 +289,13 @@ public class SubscriptionResource extends JaxRsResourceBase {
}
@Override
- public void onSubscriptionTransition(SubscriptionEvent curEvent) {
+ public void onSubscriptionTransition(EffectiveSubscriptionEvent curEventEffective) {
log.info(String.format("Got event SubscriptionTransition token = %s, type = %s, remaining = %d ",
- curEvent.getUserToken(), curEvent.getTransitionType(), curEvent.getRemainingEventsForUserOperation()));
+ curEventEffective.getUserToken(), curEventEffective.getTransitionType(), curEventEffective.getRemainingEventsForUserOperation()));
}
@Override
- public void onEmptyInvoice(final EmptyInvoiceEvent curEvent) {
+ public void onEmptyInvoice(final NullInvoiceEvent curEvent) {
log.info(String.format("Got event EmptyInvoiceNotification token = %s ", curEvent.getUserToken()));
notifyForCompletion();
}
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/JaxrsTestSuite.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/JaxrsTestSuite.java
new file mode 100644
index 0000000..51e2ac7
--- /dev/null
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/JaxrsTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.jaxrs;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class JaxrsTestSuite extends KillbillTestSuite {
+}
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountEmailJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountEmailJson.java
index c9e55f8..08a56fd 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountEmailJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountEmailJson.java
@@ -23,8 +23,9 @@ import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ning.billing.account.api.AccountEmail;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestAccountEmailJson {
+public class TestAccountEmailJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJson.java
index 96b497f..f06c4ea 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJson.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.jaxrs.json;
import java.util.UUID;
@@ -24,9 +25,10 @@ import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ning.billing.account.api.Account;
import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
import com.ning.billing.mock.MockAccountBuilder;
-public class TestAccountJson {
+public class TestAccountJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJsonSimple.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJsonSimple.java
index 386d7cd..b26c086 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJsonSimple.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountJsonSimple.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.jaxrs.json;
import java.util.UUID;
@@ -21,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestAccountJsonSimple {
+public class TestAccountJsonSimple extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountTimelineJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountTimelineJson.java
index 50b9a4f..612557f 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountTimelineJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestAccountTimelineJson.java
@@ -16,5 +16,7 @@
package com.ning.billing.jaxrs.json;
-public class TestAccountTimelineJson {
+import com.ning.billing.jaxrs.JaxrsTestSuite;
+
+public class TestAccountTimelineJson extends JaxrsTestSuite {
}
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonNoSubscriptions.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonNoSubscriptions.java
index e0e89ea..97caed0 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonNoSubscriptions.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonNoSubscriptions.java
@@ -24,8 +24,9 @@ import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestBundleJsonNoSubscriptions {
+public class TestBundleJsonNoSubscriptions extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonSimple.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonSimple.java
index 7ac93ed..e00ed56 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonSimple.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonSimple.java
@@ -22,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestBundleJsonSimple {
+public class TestBundleJsonSimple extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonWithSubscriptions.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonWithSubscriptions.java
index 5c65a7d..84cac3c 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonWithSubscriptions.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleJsonWithSubscriptions.java
@@ -36,9 +36,10 @@ import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.timeline.BundleTimeline;
import com.ning.billing.entitlement.api.timeline.SubscriptionTimeline;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
import com.ning.billing.util.clock.DefaultClock;
-public class TestBundleJsonWithSubscriptions {
+public class TestBundleJsonWithSubscriptions extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleTimelineJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleTimelineJson.java
index 8e6f306..d6bf35f 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleTimelineJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestBundleTimelineJson.java
@@ -35,9 +35,10 @@ import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.timeline.SubscriptionTimeline;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
import com.ning.billing.util.clock.DefaultClock;
-public class TestBundleTimelineJson {
+public class TestBundleTimelineJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -94,7 +95,9 @@ public class TestBundleTimelineJson {
"\"currency\":\"" + payment.getCurrency() + "\"," +
"\"status\":\"" + payment.getStatus() + "\"}]," +
"\"invoices\":[{\"amount\":" + invoice.getAmount() + "," +
- "\"credit\":" + invoice.getCredit() + "," +
+ "\"cba\":" + invoice.getCBA() + "," +
+ "\"creditAdj\":" + invoice.getCreditAdj() + "," +
+ "\"refundAdj\":" + invoice.getRefundAdj() + "," +
"\"invoiceId\":\"" + invoice.getInvoiceId() + "\"," +
"\"invoiceDate\":\"" + invoice.getInvoiceDate().toDateTimeISO().toString() + "\"," +
"\"targetDate\":\"" + invoice.getTargetDate() + "\"," +
@@ -134,13 +137,15 @@ public class TestBundleTimelineJson {
final UUID accountId = UUID.randomUUID();
final UUID invoiceId = UUID.randomUUID();
final BigDecimal invoiceAmount = BigDecimal.TEN;
- final BigDecimal credit = BigDecimal.ONE;
+ final BigDecimal cba = BigDecimal.ONE;
+ final BigDecimal creditAdj = BigDecimal.ONE;
+ final BigDecimal refundAdj = BigDecimal.ONE;
final DateTime invoiceDate = DefaultClock.toUTCDateTime(new DateTime(DateTimeZone.UTC));
final DateTime targetDate = DefaultClock.toUTCDateTime(new DateTime(DateTimeZone.UTC));
final String invoiceNumber = UUID.randomUUID().toString();
final BigDecimal balance = BigDecimal.ZERO;
- return new InvoiceJsonSimple(invoiceAmount, credit, invoiceId.toString(), invoiceDate,
+ return new InvoiceJsonSimple(invoiceAmount, cba, creditAdj, refundAdj, invoiceId.toString(), invoiceDate,
targetDate, invoiceNumber, balance, accountId.toString());
}
@@ -154,7 +159,6 @@ public class TestBundleTimelineJson {
final String currency = "USD";
final String status = UUID.randomUUID().toString();
-
return new PaymentJsonSimple(amount, paidAmount, accountId.toString(), invoiceId.toString(), paymentId.toString(),
paymentRequestedDate, paymentEffectiveDate, retryCount,
currency, status);
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackCollectionJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackCollectionJson.java
index b9a7612..af4c8c6 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackCollectionJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackCollectionJson.java
@@ -28,8 +28,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.common.collect.ImmutableList;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestChargebackCollectionJson {
+public class TestChargebackCollectionJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackJson.java
index 3806741..006582d 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestChargebackJson.java
@@ -27,8 +27,9 @@ import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestChargebackJson {
+public class TestChargebackJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditCollectionJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditCollectionJson.java
index 5a93778..31be145 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditCollectionJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditCollectionJson.java
@@ -28,8 +28,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.common.collect.ImmutableList;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestCreditCollectionJson {
+public class TestCreditCollectionJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditJson.java
index eee0cef..b15b6d1 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCreditJson.java
@@ -27,8 +27,9 @@ import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestCreditJson {
+public class TestCreditJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCustomFieldJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCustomFieldJson.java
index ab7af78..6342b57 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCustomFieldJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestCustomFieldJson.java
@@ -22,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestCustomFieldJson {
+public class TestCustomFieldJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceEmailJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceEmailJson.java
index c859596..f72ba4c 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceEmailJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceEmailJson.java
@@ -22,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestInvoiceEmailJson {
+public class TestInvoiceEmailJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceItemJsonSimple.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceItemJsonSimple.java
index ec9fc54..3191568 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceItemJsonSimple.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceItemJsonSimple.java
@@ -30,8 +30,9 @@ import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.InvoiceItem;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestInvoiceItemJsonSimple {
+public class TestInvoiceItemJsonSimple extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonSimple.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonSimple.java
index 64f0ac0..0080402 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonSimple.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonSimple.java
@@ -29,8 +29,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.ning.billing.invoice.api.Invoice;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestInvoiceJsonSimple {
+public class TestInvoiceJsonSimple extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -41,17 +42,21 @@ public class TestInvoiceJsonSimple {
@Test(groups = "fast")
public void testJson() throws Exception {
final BigDecimal amount = BigDecimal.TEN;
- final BigDecimal credit = BigDecimal.ONE;
+ final BigDecimal cba = BigDecimal.ONE;
+ final BigDecimal creditAdj = BigDecimal.ONE;
+ final BigDecimal refundAdj = BigDecimal.ONE;
final String invoiceId = UUID.randomUUID().toString();
final DateTime invoiceDate = new DateTime(DateTimeZone.UTC);
final DateTime targetDate = new DateTime(DateTimeZone.UTC);
final String invoiceNumber = UUID.randomUUID().toString();
final BigDecimal balance = BigDecimal.ZERO;
final String accountId = UUID.randomUUID().toString();
- final InvoiceJsonSimple invoiceJsonSimple = new InvoiceJsonSimple(amount, credit, invoiceId, invoiceDate,
+ final InvoiceJsonSimple invoiceJsonSimple = new InvoiceJsonSimple(amount, cba, creditAdj, refundAdj, invoiceId, invoiceDate,
targetDate, invoiceNumber, balance, accountId);
Assert.assertEquals(invoiceJsonSimple.getAmount(), amount);
- Assert.assertEquals(invoiceJsonSimple.getCredit(), credit);
+ Assert.assertEquals(invoiceJsonSimple.getCBA(), cba);
+ Assert.assertEquals(invoiceJsonSimple.getCreditAdj(), creditAdj);
+ Assert.assertEquals(invoiceJsonSimple.getRefundAdj(), refundAdj);
Assert.assertEquals(invoiceJsonSimple.getInvoiceId(), invoiceId);
Assert.assertEquals(invoiceJsonSimple.getInvoiceDate(), invoiceDate);
Assert.assertEquals(invoiceJsonSimple.getTargetDate(), targetDate);
@@ -61,7 +66,9 @@ public class TestInvoiceJsonSimple {
final String asJson = mapper.writeValueAsString(invoiceJsonSimple);
Assert.assertEquals(asJson, "{\"amount\":" + invoiceJsonSimple.getAmount().toString() + "," +
- "\"credit\":" + invoiceJsonSimple.getCredit().toString() + "," +
+ "\"cba\":" + invoiceJsonSimple.getCBA().toString() + "," +
+ "\"creditAdj\":" + invoiceJsonSimple.getCreditAdj().toString() + "," +
+ "\"refundAdj\":" + invoiceJsonSimple.getRefundAdj().toString() + "," +
"\"invoiceId\":\"" + invoiceJsonSimple.getInvoiceId() + "\"," +
"\"invoiceDate\":\"" + invoiceJsonSimple.getInvoiceDate().toDateTimeISO().toString() + "\"," +
"\"targetDate\":\"" + invoiceJsonSimple.getTargetDate().toDateTimeISO().toString() + "\"," +
@@ -76,8 +83,10 @@ public class TestInvoiceJsonSimple {
@Test(groups = "fast")
public void testFromInvoice() throws Exception {
final Invoice invoice = Mockito.mock(Invoice.class);
- Mockito.when(invoice.getAmountCharged()).thenReturn(BigDecimal.TEN);
- Mockito.when(invoice.getAmountCredited()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getChargedAmount()).thenReturn(BigDecimal.TEN);
+ Mockito.when(invoice.getCBAAmount()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getCreditAdjAmount()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getRefundAdjAmount()).thenReturn(BigDecimal.ONE);
Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());
Mockito.when(invoice.getInvoiceDate()).thenReturn(new DateTime(DateTimeZone.UTC));
Mockito.when(invoice.getTargetDate()).thenReturn(new DateTime(DateTimeZone.UTC));
@@ -86,8 +95,10 @@ public class TestInvoiceJsonSimple {
Mockito.when(invoice.getAccountId()).thenReturn(UUID.randomUUID());
final InvoiceJsonSimple invoiceJsonSimple = new InvoiceJsonSimple(invoice);
- Assert.assertEquals(invoiceJsonSimple.getAmount(), invoice.getAmountCharged());
- Assert.assertEquals(invoiceJsonSimple.getCredit(), invoice.getAmountCredited());
+ Assert.assertEquals(invoiceJsonSimple.getAmount(), invoice.getChargedAmount());
+ Assert.assertEquals(invoiceJsonSimple.getCBA(), invoice.getCBAAmount());
+ Assert.assertEquals(invoiceJsonSimple.getCreditAdj(), invoice.getCreditAdjAmount());
+ Assert.assertEquals(invoiceJsonSimple.getRefundAdj(), invoice.getRefundAdjAmount());
Assert.assertEquals(invoiceJsonSimple.getInvoiceId(), invoice.getId().toString());
Assert.assertEquals(invoiceJsonSimple.getInvoiceDate(), invoice.getInvoiceDate());
Assert.assertEquals(invoiceJsonSimple.getTargetDate(), invoice.getTargetDate());
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithBundleKeys.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithBundleKeys.java
index 8603492..e50bd4b 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithBundleKeys.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithBundleKeys.java
@@ -29,8 +29,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.ning.billing.invoice.api.Invoice;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestInvoiceJsonWithBundleKeys {
+public class TestInvoiceJsonWithBundleKeys extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -41,7 +42,9 @@ public class TestInvoiceJsonWithBundleKeys {
@Test(groups = "fast")
public void testJson() throws Exception {
final BigDecimal amount = BigDecimal.TEN;
- final BigDecimal credit = BigDecimal.ONE;
+ final BigDecimal cba = BigDecimal.ONE;
+ final BigDecimal creditAdj = BigDecimal.ONE;
+ final BigDecimal refundAdj = BigDecimal.ONE;
final String invoiceId = UUID.randomUUID().toString();
final DateTime invoiceDate = new DateTime(DateTimeZone.UTC);
final DateTime targetDate = new DateTime(DateTimeZone.UTC);
@@ -49,10 +52,12 @@ public class TestInvoiceJsonWithBundleKeys {
final BigDecimal balance = BigDecimal.ZERO;
final String accountId = UUID.randomUUID().toString();
final String bundleKeys = UUID.randomUUID().toString();
- final InvoiceJsonWithBundleKeys invoiceJsonSimple = new InvoiceJsonWithBundleKeys(amount, credit, invoiceId, invoiceDate,
+ final InvoiceJsonWithBundleKeys invoiceJsonSimple = new InvoiceJsonWithBundleKeys(amount, cba, creditAdj, refundAdj, invoiceId, invoiceDate,
targetDate, invoiceNumber, balance, accountId, bundleKeys);
Assert.assertEquals(invoiceJsonSimple.getAmount(), amount);
- Assert.assertEquals(invoiceJsonSimple.getCredit(), credit);
+ Assert.assertEquals(invoiceJsonSimple.getCBA(), cba);
+ Assert.assertEquals(invoiceJsonSimple.getCreditAdj(), creditAdj);
+ Assert.assertEquals(invoiceJsonSimple.getRefundAdj(), refundAdj);
Assert.assertEquals(invoiceJsonSimple.getInvoiceId(), invoiceId);
Assert.assertEquals(invoiceJsonSimple.getInvoiceDate(), invoiceDate);
Assert.assertEquals(invoiceJsonSimple.getTargetDate(), targetDate);
@@ -63,7 +68,9 @@ public class TestInvoiceJsonWithBundleKeys {
final String asJson = mapper.writeValueAsString(invoiceJsonSimple);
Assert.assertEquals(asJson, "{\"amount\":" + invoiceJsonSimple.getAmount().toString() + "," +
- "\"credit\":" + invoiceJsonSimple.getCredit().toString() + "," +
+ "\"cba\":" + invoiceJsonSimple.getCBA().toString() + "," +
+ "\"creditAdj\":" + invoiceJsonSimple.getCreditAdj().toString() + "," +
+ "\"refundAdj\":" + invoiceJsonSimple.getRefundAdj().toString() + "," +
"\"invoiceId\":\"" + invoiceJsonSimple.getInvoiceId() + "\"," +
"\"invoiceDate\":\"" + invoiceJsonSimple.getInvoiceDate().toDateTimeISO().toString() + "\"," +
"\"targetDate\":\"" + invoiceJsonSimple.getTargetDate().toDateTimeISO().toString() + "\"," +
@@ -79,8 +86,10 @@ public class TestInvoiceJsonWithBundleKeys {
@Test(groups = "fast")
public void testFromInvoice() throws Exception {
final Invoice invoice = Mockito.mock(Invoice.class);
- Mockito.when(invoice.getAmountCharged()).thenReturn(BigDecimal.TEN);
- Mockito.when(invoice.getAmountCredited()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getChargedAmount()).thenReturn(BigDecimal.TEN);
+ Mockito.when(invoice.getCBAAmount()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getCreditAdjAmount()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getRefundAdjAmount()).thenReturn(BigDecimal.ONE);
Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());
Mockito.when(invoice.getInvoiceDate()).thenReturn(new DateTime(DateTimeZone.UTC));
Mockito.when(invoice.getTargetDate()).thenReturn(new DateTime(DateTimeZone.UTC));
@@ -91,8 +100,10 @@ public class TestInvoiceJsonWithBundleKeys {
final String bundleKeys = UUID.randomUUID().toString();
final InvoiceJsonWithBundleKeys invoiceJsonWithBundleKeys = new InvoiceJsonWithBundleKeys(invoice, bundleKeys);
- Assert.assertEquals(invoiceJsonWithBundleKeys.getAmount(), invoice.getAmountCharged());
- Assert.assertEquals(invoiceJsonWithBundleKeys.getCredit(), invoice.getAmountCredited());
+ Assert.assertEquals(invoiceJsonWithBundleKeys.getAmount(), invoice.getChargedAmount());
+ Assert.assertEquals(invoiceJsonWithBundleKeys.getCBA(), invoice.getCBAAmount());
+ Assert.assertEquals(invoiceJsonWithBundleKeys.getCreditAdj(), invoice.getCreditAdjAmount());
+ Assert.assertEquals(invoiceJsonWithBundleKeys.getRefundAdj(), invoice.getRefundAdjAmount());
Assert.assertEquals(invoiceJsonWithBundleKeys.getInvoiceId(), invoice.getId().toString());
Assert.assertEquals(invoiceJsonWithBundleKeys.getInvoiceDate(), invoice.getInvoiceDate());
Assert.assertEquals(invoiceJsonWithBundleKeys.getTargetDate(), invoice.getTargetDate());
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithItems.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithItems.java
index c7bd606..8722422 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithItems.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestInvoiceJsonWithItems.java
@@ -32,8 +32,9 @@ import com.google.common.collect.ImmutableList;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceItem;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestInvoiceJsonWithItems {
+public class TestInvoiceJsonWithItems extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -44,7 +45,9 @@ public class TestInvoiceJsonWithItems {
@Test(groups = "fast")
public void testJson() throws Exception {
final BigDecimal amount = BigDecimal.TEN;
- final BigDecimal credit = BigDecimal.ONE;
+ final BigDecimal cba = BigDecimal.ONE;
+ final BigDecimal creditAdj = BigDecimal.ONE;
+ final BigDecimal refundAdj = BigDecimal.ONE;
final String invoiceId = UUID.randomUUID().toString();
final DateTime invoiceDate = new DateTime(DateTimeZone.UTC);
final DateTime targetDate = new DateTime(DateTimeZone.UTC);
@@ -52,11 +55,13 @@ public class TestInvoiceJsonWithItems {
final BigDecimal balance = BigDecimal.ZERO;
final String accountId = UUID.randomUUID().toString();
final InvoiceItemJsonSimple invoiceItemJsonSimple = createInvoiceItemJson();
- final InvoiceJsonWithItems invoiceJsonWithItems = new InvoiceJsonWithItems(amount, credit, invoiceId, invoiceDate,
+ final InvoiceJsonWithItems invoiceJsonWithItems = new InvoiceJsonWithItems(amount, cba, creditAdj, refundAdj, invoiceId, invoiceDate,
targetDate, invoiceNumber, balance, accountId,
ImmutableList.<InvoiceItemJsonSimple>of(invoiceItemJsonSimple));
Assert.assertEquals(invoiceJsonWithItems.getAmount(), amount);
- Assert.assertEquals(invoiceJsonWithItems.getCredit(), credit);
+ Assert.assertEquals(invoiceJsonWithItems.getCBA(), cba);
+ Assert.assertEquals(invoiceJsonWithItems.getCreditAdj(), creditAdj);
+ Assert.assertEquals(invoiceJsonWithItems.getRefundAdj(), refundAdj);
Assert.assertEquals(invoiceJsonWithItems.getInvoiceId(), invoiceId);
Assert.assertEquals(invoiceJsonWithItems.getInvoiceDate(), invoiceDate);
Assert.assertEquals(invoiceJsonWithItems.getTargetDate(), targetDate);
@@ -68,7 +73,9 @@ public class TestInvoiceJsonWithItems {
final String asJson = mapper.writeValueAsString(invoiceJsonWithItems);
Assert.assertEquals(asJson, "{\"amount\":" + invoiceJsonWithItems.getAmount().toString() + "," +
- "\"credit\":" + invoiceJsonWithItems.getCredit().toString() + "," +
+ "\"cba\":" + invoiceJsonWithItems.getCBA().toString() + "," +
+ "\"creditAdj\":" + invoiceJsonWithItems.getCreditAdj().toString() + "," +
+ "\"refundAdj\":" + invoiceJsonWithItems.getRefundAdj().toString() + "," +
"\"invoiceId\":\"" + invoiceJsonWithItems.getInvoiceId() + "\"," +
"\"invoiceDate\":\"" + invoiceJsonWithItems.getInvoiceDate().toDateTimeISO().toString() + "\"," +
"\"targetDate\":\"" + invoiceJsonWithItems.getTargetDate().toDateTimeISO().toString() + "\"," +
@@ -94,8 +101,7 @@ public class TestInvoiceJsonWithItems {
@Test(groups = "fast")
public void testFromInvoice() throws Exception {
final Invoice invoice = Mockito.mock(Invoice.class);
- Mockito.when(invoice.getAmountCharged()).thenReturn(BigDecimal.TEN);
- Mockito.when(invoice.getAmountCredited()).thenReturn(BigDecimal.ONE);
+ Mockito.when(invoice.getChargedAmount()).thenReturn(BigDecimal.TEN);
Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());
Mockito.when(invoice.getInvoiceDate()).thenReturn(new DateTime(DateTimeZone.UTC));
Mockito.when(invoice.getTargetDate()).thenReturn(new DateTime(DateTimeZone.UTC));
@@ -106,8 +112,7 @@ public class TestInvoiceJsonWithItems {
Mockito.when(invoice.getInvoiceItems()).thenReturn(ImmutableList.<InvoiceItem>of(invoiceItem));
final InvoiceJsonWithItems invoiceJsonWithItems = new InvoiceJsonWithItems(invoice);
- Assert.assertEquals(invoiceJsonWithItems.getAmount(), invoice.getAmountCharged());
- Assert.assertEquals(invoiceJsonWithItems.getCredit(), invoice.getAmountCredited());
+ Assert.assertEquals(invoiceJsonWithItems.getAmount(), invoice.getChargedAmount());
Assert.assertEquals(invoiceJsonWithItems.getInvoiceId(), invoice.getId().toString());
Assert.assertEquals(invoiceJsonWithItems.getInvoiceDate(), invoice.getInvoiceDate());
Assert.assertEquals(invoiceJsonWithItems.getTargetDate(), invoice.getTargetDate());
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestPlanDetailJason.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestPlanDetailJason.java
index ee7ba0d..49f7e44 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestPlanDetailJason.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestPlanDetailJason.java
@@ -30,8 +30,9 @@ import com.ning.billing.catalog.api.Plan;
import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.PriceList;
import com.ning.billing.catalog.api.Product;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestPlanDetailJason {
+public class TestPlanDetailJason extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonNoEvents.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonNoEvents.java
index 42d0794..d4e62f0 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonNoEvents.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonNoEvents.java
@@ -35,8 +35,9 @@ import com.ning.billing.catalog.api.PriceList;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestSubscriptionJsonNoEvents {
+public class TestSubscriptionJsonNoEvents extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -54,9 +55,11 @@ public class TestSubscriptionJsonNoEvents {
final String billingPeriod = UUID.randomUUID().toString();
final String priceList = UUID.randomUUID().toString();
final DateTime chargedThroughDate = new DateTime(DateTimeZone.UTC);
+ final DateTime endDate = new DateTime(DateTimeZone.UTC);
+
final SubscriptionJsonNoEvents subscriptionJsonNoEvents = new SubscriptionJsonNoEvents(subscriptionId, bundleId, startDate,
productName, productCategory, billingPeriod,
- priceList, chargedThroughDate);
+ priceList, chargedThroughDate, endDate);
Assert.assertEquals(subscriptionJsonNoEvents.getSubscriptionId(), subscriptionId);
Assert.assertEquals(subscriptionJsonNoEvents.getBundleId(), bundleId);
Assert.assertEquals(subscriptionJsonNoEvents.getStartDate(), startDate);
@@ -74,7 +77,8 @@ public class TestSubscriptionJsonNoEvents {
"\"productCategory\":\"" + subscriptionJsonNoEvents.getProductCategory() + "\"," +
"\"billingPeriod\":\"" + subscriptionJsonNoEvents.getBillingPeriod() + "\"," +
"\"priceList\":\"" + subscriptionJsonNoEvents.getPriceList() + "\"," +
- "\"chargedThroughDate\":\"" + subscriptionJsonNoEvents.getChargedThroughDate().toDateTimeISO().toString() + "\"}");
+ "\"chargedThroughDate\":\"" + subscriptionJsonNoEvents.getChargedThroughDate().toDateTimeISO().toString() + "\"," +
+ "\"cancelledDate\":\"" + subscriptionJsonNoEvents.getCancelledDate().toDateTimeISO().toString() + "\"}");
final SubscriptionJsonNoEvents fromJson = mapper.readValue(asJson, SubscriptionJsonNoEvents.class);
Assert.assertEquals(fromJson, subscriptionJsonNoEvents);
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonSimple.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonSimple.java
index de6523d..e4631f9 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonSimple.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonSimple.java
@@ -22,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestSubscriptionJsonSimple {
+public class TestSubscriptionJsonSimple extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonWithEvents.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonWithEvents.java
index 874f6bb..a0dac08 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonWithEvents.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestSubscriptionJsonWithEvents.java
@@ -35,9 +35,10 @@ import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.timeline.SubscriptionTimeline;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
import com.ning.billing.util.clock.DefaultClock;
-public class TestSubscriptionJsonWithEvents {
+public class TestSubscriptionJsonWithEvents extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
static {
@@ -64,7 +65,6 @@ public class TestSubscriptionJsonWithEvents {
null,
null);
-
final String asJson = mapper.writeValueAsString(subscriptionJsonWithEvents);
final SubscriptionJsonWithEvents.SubscriptionReadEventJson event = subscriptionJsonWithEvents.getEvents().get(0);
Assert.assertEquals(asJson, "{\"events\":[{\"eventId\":\"" + event.getEventId() + "\"," +
diff --git a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestTagDefinitionJson.java b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestTagDefinitionJson.java
index 16a2cb6..d771085 100644
--- a/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestTagDefinitionJson.java
+++ b/jaxrs/src/test/java/com/ning/billing/jaxrs/json/TestTagDefinitionJson.java
@@ -22,8 +22,9 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ning.billing.jaxrs.JaxrsTestSuite;
-public class TestTagDefinitionJson {
+public class TestTagDefinitionJson extends JaxrsTestSuite {
private static final ObjectMapper mapper = new ObjectMapper();
@Test(groups = "fast")
junction/pom.xml 2(+1 -1)
diff --git a/junction/pom.xml b/junction/pom.xml
index cc01087..5ced827 100644
--- a/junction/pom.xml
+++ b/junction/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-junction</artifactId>
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 b602820..bfce70b 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
@@ -27,9 +27,9 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.PriceList;
import com.ning.billing.catalog.api.ProductCategory;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.EntitlementUserApiException;
import com.ning.billing.entitlement.api.user.Subscription;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingApiException;
import com.ning.billing.junction.api.BlockingState;
@@ -49,18 +49,22 @@ public class BlockingSubscription implements Subscription {
this.checker = checker;
}
+ @Override
public UUID getId() {
return subscription.getId();
}
+ @Override
public boolean cancel(final DateTime requestedDate, final boolean eot, final CallContext context) throws EntitlementUserApiException {
return subscription.cancel(requestedDate, eot, context);
}
+ @Override
public boolean uncancel(final CallContext context) throws EntitlementUserApiException {
return subscription.uncancel(context);
}
+ @Override
public boolean changePlan(final String productName, final BillingPeriod term, final String planSet, final DateTime requestedDate,
final CallContext context) throws EntitlementUserApiException {
try {
@@ -71,63 +75,88 @@ public class BlockingSubscription implements Subscription {
return subscription.changePlan(productName, term, planSet, requestedDate, context);
}
+ @Override
public boolean recreate(final PlanPhaseSpecifier spec, final DateTime requestedDate, final CallContext context)
throws EntitlementUserApiException {
return subscription.recreate(spec, requestedDate, context);
}
+ @Override
public UUID getBundleId() {
return subscription.getBundleId();
}
+ @Override
public SubscriptionState getState() {
return subscription.getState();
}
+ @Override
public DateTime getStartDate() {
return subscription.getStartDate();
}
+ @Override
public DateTime getEndDate() {
return subscription.getEndDate();
}
+ @Override
+ public DateTime getFutureEndDate() {
+ return subscription.getFutureEndDate();
+ }
+
+ @Override
public Plan getCurrentPlan() {
return subscription.getCurrentPlan();
}
+ @Override
public PriceList getCurrentPriceList() {
return subscription.getCurrentPriceList();
}
+ @Override
public PlanPhase getCurrentPhase() {
return subscription.getCurrentPhase();
}
+ @Override
public DateTime getChargedThroughDate() {
return subscription.getChargedThroughDate();
}
+ @Override
public DateTime getPaidThroughDate() {
return subscription.getPaidThroughDate();
}
+ @Override
public ProductCategory getCategory() {
return subscription.getCategory();
}
- public SubscriptionEvent getPendingTransition() {
+ @Override
+ public EffectiveSubscriptionEvent getPendingTransition() {
return subscription.getPendingTransition();
}
- public SubscriptionEvent getPreviousTransition() {
+ @Override
+ public EffectiveSubscriptionEvent getPreviousTransition() {
return subscription.getPreviousTransition();
}
- public List<SubscriptionEvent> getBillingTransitions() {
+ @Override
+ public List<EffectiveSubscriptionEvent> getBillingTransitions() {
return subscription.getBillingTransitions();
}
+ @Override
+ public List<EffectiveSubscriptionEvent> getAllTransitions() {
+ return subscription.getAllTransitions();
+ }
+
+ @Override
public BlockingState getBlockingState() {
if (blockingState == null) {
blockingState = blockingApi.getBlockingStateFor(this);
@@ -139,5 +168,4 @@ public class BlockingSubscription implements Subscription {
return subscription;
}
-
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscriptionBundle.java b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscriptionBundle.java
index 27727e7..2a26425 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscriptionBundle.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/api/BlockingSubscriptionBundle.java
@@ -18,8 +18,6 @@ package com.ning.billing.junction.plumbing.api;
import java.util.UUID;
-import org.joda.time.DateTime;
-
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
@@ -44,10 +42,6 @@ public class BlockingSubscriptionBundle implements SubscriptionBundle {
return subscriptionBundle.getId();
}
- public DateTime getStartDate() {
- return subscriptionBundle.getStartDate();
- }
-
public String getKey() {
return subscriptionBundle.getKey();
}
@@ -64,4 +58,46 @@ public class BlockingSubscriptionBundle implements SubscriptionBundle {
return blockingState;
}
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("BlockingSubscriptionBundle");
+ sb.append("{blockingApi=").append(blockingApi);
+ sb.append(", subscriptionBundle=").append(subscriptionBundle);
+ sb.append(", blockingState=").append(blockingState);
+ sb.append('}');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final BlockingSubscriptionBundle that = (BlockingSubscriptionBundle) o;
+
+ if (blockingApi != null ? !blockingApi.equals(that.blockingApi) : that.blockingApi != null) {
+ return false;
+ }
+ if (blockingState != null ? !blockingState.equals(that.blockingState) : that.blockingState != null) {
+ return false;
+ }
+ if (subscriptionBundle != null ? !subscriptionBundle.equals(that.subscriptionBundle) : that.subscriptionBundle != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = subscriptionBundle != null ? subscriptionBundle.hashCode() : 0;
+ result = 31 * result + (blockingApi != null ? blockingApi.hashCode() : 0);
+ result = 31 * result + (blockingState != null ? blockingState.hashCode() : 0);
+ return result;
+ }
}
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BillCycleDayCalculator.java b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BillCycleDayCalculator.java
index 2b75d2c..ce98f24 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BillCycleDayCalculator.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/BillCycleDayCalculator.java
@@ -33,11 +33,11 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.Product;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.SubscriptionEvent;
public class BillCycleDayCalculator {
private static final Logger log = LoggerFactory.getLogger(BillCycleDayCalculator.class);
@@ -52,7 +52,7 @@ public class BillCycleDayCalculator {
this.entitlementApi = entitlementApi;
}
- protected int calculateBcd(final SubscriptionBundle bundle, final Subscription subscription, final SubscriptionEvent transition, final Account account)
+ protected int calculateBcd(final SubscriptionBundle bundle, final Subscription subscription, final EffectiveSubscriptionEvent transition, final Account account)
throws CatalogApiException, AccountApiException, EntitlementUserApiException {
final Catalog catalog = catalogService.getFullCatalog();
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 019acc8..3bc8f28 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
@@ -37,10 +37,10 @@ import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.ChargeThruApi;
import com.ning.billing.entitlement.api.billing.EntitlementBillingApiException;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.entitlement.api.user.Subscription;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BillingEventSet;
import com.ning.billing.util.api.TagUserApi;
@@ -111,10 +111,10 @@ public class DefaultBillingApi implements BillingApi {
private void debugLog(final SortedSet<BillingEvent> result, final String title) {
- log.debug(title);
+ log.info(title);
final Iterator<BillingEvent> i = result.iterator();
while (i.hasNext()) {
- log.debug(i.next().toString());
+ log.info(i.next().toString());
}
}
@@ -139,7 +139,7 @@ public class DefaultBillingApi implements BillingApi {
private void addBillingEventsForSubscription(final List<Subscription> subscriptions, final SubscriptionBundle bundle, final Account account, final CallContext context, final DefaultBillingEventSet result) {
for (final Subscription subscription : subscriptions) {
- for (final SubscriptionEvent transition : subscription.getBillingTransitions()) {
+ for (final EffectiveSubscriptionEvent transition : subscription.getBillingTransitions()) {
try {
final int bcd = bcdCalculator.calculateBcd(bundle, subscription, transition, account);
diff --git a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingEvent.java b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingEvent.java
index 284aa99..5364b18 100644
--- a/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingEvent.java
+++ b/junction/src/main/java/com/ning/billing/junction/plumbing/billing/DefaultBillingEvent.java
@@ -31,8 +31,8 @@ import com.ning.billing.catalog.api.PlanPhase;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.BillingModeType;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.entitlement.api.user.Subscription;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
public class DefaultBillingEvent implements BillingEvent {
private final Account account;
@@ -51,7 +51,7 @@ public class DefaultBillingEvent implements BillingEvent {
private final Long totalOrdering;
private final DateTimeZone timeZone;
- public DefaultBillingEvent(final Account account, final SubscriptionEvent transition, final Subscription subscription, final int billCycleDay, final Currency currency, final Catalog catalog) throws CatalogApiException {
+ public DefaultBillingEvent(final Account account, final EffectiveSubscriptionEvent transition, final Subscription subscription, final int billCycleDay, final Currency currency, final Catalog catalog) throws CatalogApiException {
this.account = account;
this.billCycleDay = billCycleDay;
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 b8f4343..de56229 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
@@ -16,71 +16,41 @@
package com.ning.billing.junction.api.blocking;
-import java.io.IOException;
import java.util.SortedSet;
import java.util.UUID;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.mockito.Mockito;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
-import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
+import com.ning.billing.junction.JunctionTestSuiteWithEmbeddedDB;
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;
import com.ning.billing.mock.glue.MockEntitlementModule;
import com.ning.billing.util.clock.ClockMock;
-import com.ning.billing.util.io.IOUtils;
@Guice(modules = {MockModule.class, MockEntitlementModule.class})
-public class TestBlockingApi {
- private final Logger log = LoggerFactory.getLogger(TestBlockingDao.class);
-
- @Inject
- private MysqlTestingHelper helper;
-
+public class TestBlockingApi extends JunctionTestSuiteWithEmbeddedDB {
@Inject
private BlockingApi api;
@Inject
private ClockMock clock;
- @BeforeClass(groups = {"slow"})
- public void setup() throws IOException {
- log.info("Starting set up TestBlockingApi");
-
- final String utilDdl = IOUtils.toString(TestBlockingDao.class.getResourceAsStream("/com/ning/billing/junction/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
- }
-
- @BeforeMethod(groups = {"slow"})
+ @BeforeMethod(groups = "slow")
public void clean() {
- helper.cleanupTable("blocking_states");
clock.resetDeltaFromReality();
}
- @AfterClass(groups = "slow")
- public void stopMysql() {
- helper.stopMysql();
- }
-
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testApi() {
-
final UUID uuid = UUID.randomUUID();
final String overdueStateName = "WayPassedItMan";
final String service = "TEST";
@@ -97,15 +67,14 @@ public class TestBlockingApi {
final BlockingState state2 = new DefaultBlockingState(uuid, overdueStateName2, Blockable.Type.SUBSCRIPTION_BUNDLE, service, blockChange, blockEntitlement, blockBilling);
api.setBlockingState(state2);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", uuid);
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(uuid);
Assert.assertEquals(api.getBlockingStateFor(bundle).getStateName(), overdueStateName2);
Assert.assertEquals(api.getBlockingStateFor(bundle.getId()).getStateName(), overdueStateName2);
-
}
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testApiHistory() throws Exception {
final UUID uuid = UUID.randomUUID();
final String overdueStateName = "WayPassedItMan";
@@ -124,9 +93,8 @@ public class TestBlockingApi {
final BlockingState state2 = new DefaultBlockingState(uuid, overdueStateName2, Blockable.Type.SUBSCRIPTION_BUNDLE, service, blockChange, blockEntitlement, blockBilling);
api.setBlockingState(state2);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", uuid);
-
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(uuid);
final SortedSet<BlockingState> history1 = api.getBlockingHistory(bundle);
final SortedSet<BlockingState> history2 = api.getBlockingHistory(bundle.getId());
@@ -138,7 +106,5 @@ public class TestBlockingApi {
Assert.assertEquals(history2.size(), 2);
Assert.assertEquals(history2.first().getStateName(), overdueStateName);
Assert.assertEquals(history2.last().getStateName(), overdueStateName2);
-
}
-
}
diff --git a/junction/src/test/java/com/ning/billing/junction/blocking/MockBlockingChecker.java b/junction/src/test/java/com/ning/billing/junction/blocking/MockBlockingChecker.java
index ccf372b..0fa2e8c 100644
--- a/junction/src/test/java/com/ning/billing/junction/blocking/MockBlockingChecker.java
+++ b/junction/src/test/java/com/ning/billing/junction/blocking/MockBlockingChecker.java
@@ -24,11 +24,9 @@ import com.ning.billing.junction.api.BlockingApiException;
import com.ning.billing.junction.block.BlockingChecker;
public class MockBlockingChecker implements BlockingChecker {
-
@Override
public void checkBlockedChange(final Blockable blockable) throws BlockingApiException {
// Intentionally blank
-
}
@Override
@@ -55,5 +53,4 @@ public class MockBlockingChecker implements BlockingChecker {
public void checkBlockedBilling(final UUID bundleId, final Type type) throws BlockingApiException {
// Intentionally blank
}
-
}
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 43a2e79..9959583 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
@@ -19,6 +19,7 @@ package com.ning.billing.junction.blocking;
import java.util.SortedSet;
import java.util.UUID;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -28,8 +29,10 @@ import com.google.inject.Guice;
import com.google.inject.Injector;
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.JunctionTestSuite;
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.BlockingApiException;
import com.ning.billing.junction.api.BlockingState;
@@ -37,18 +40,14 @@ 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;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.util.clock.Clock;
-public class TestBlockingChecker {
-
+public class TestBlockingChecker extends JunctionTestSuite {
private BlockingState bundleState;
private BlockingState subscriptionState;
private BlockingState accountState;
private final BlockingStateDao dao = new BlockingStateDao() {
-
@Override
public BlockingState getBlockingStateFor(final Blockable blockable) {
if (blockable.getId() == account.getId()) {
@@ -92,43 +91,44 @@ public class TestBlockingChecker {
private Account account;
private SubscriptionBundle bundle;
- @BeforeClass(groups = {"fast"})
+ @BeforeClass(groups = "fast")
public void setup() {
- account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
-
- bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getAccountId", account.getId());
- ((ZombieControl) bundle).addResult("getId", UUID.randomUUID());
- ((ZombieControl) bundle).addResult("getKey", "key");
+ final UUID accountId = UUID.randomUUID();
+ account = Mockito.mock(Account.class);
+ Mockito.when(account.getId()).thenReturn(accountId);
- subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) subscription).addResult("getId", UUID.randomUUID());
- ((ZombieControl) subscription).addResult("getBundleId", bundle.getId());
+ bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getAccountId()).thenReturn(accountId);
+ final UUID bundleId = UUID.randomUUID();
+ Mockito.when(bundle.getId()).thenReturn(bundleId);
+ Mockito.when(bundle.getKey()).thenReturn("key");
+ subscription = Mockito.mock(Subscription.class);
+ Mockito.when(subscription.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(subscription.getBundleId()).thenReturn(bundleId);
final Injector i = Guice.createInjector(new AbstractModule() {
-
@Override
protected void configure() {
bind(BlockingChecker.class).to(DefaultBlockingChecker.class).asEagerSingleton();
bind(BlockingStateDao.class).toInstance(dao);
- final EntitlementUserApi entitlementUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
+ final EntitlementUserApi entitlementUserApi = Mockito.mock(EntitlementUserApi.class);
bind(EntitlementUserApi.class).toInstance(entitlementUserApi);
- ((ZombieControl) entitlementUserApi).addResult("getBundleFromId", bundle);
-
+ try {
+ Mockito.when(entitlementUserApi.getBundleFromId(Mockito.<UUID>any())).thenReturn(bundle);
+ } catch (EntitlementUserApiException e) {
+ Assert.fail(e.toString());
+ }
}
-
});
checker = i.getInstance(BlockingChecker.class);
}
-
private void setStateBundle(final boolean bC, final boolean bE, final boolean bB) {
bundleState = new DefaultBlockingState(UUID.randomUUID(), "state", Blockable.Type.SUBSCRIPTION_BUNDLE, "test-service", bC, bE, bB);
- ((ZombieControl) bundle).addResult("getBlockingState", bundleState);
+ Mockito.when(bundle.getBlockingState()).thenReturn(bundleState);
}
private void setStateAccount(final boolean bC, final boolean bE, final boolean bB) {
@@ -137,10 +137,10 @@ public class TestBlockingChecker {
private void setStateSubscription(final boolean bC, final boolean bE, final boolean bB) {
subscriptionState = new DefaultBlockingState(UUID.randomUUID(), "state", Blockable.Type.SUBSCRIPTION_BUNDLE, "test-service", bC, bE, bB);
- ((ZombieControl) subscription).addResult("getBlockingState", subscriptionState);
+ Mockito.when(subscription.getBlockingState()).thenReturn(subscriptionState);
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testSubscriptionChecker() throws Exception {
setStateAccount(false, false, false);
setStateBundle(false, false, false);
@@ -212,7 +212,6 @@ public class TestBlockingChecker {
//Expected behavior
}
-
//BLOCKED ACCOUNT
setStateSubscription(false, false, false);
setStateBundle(false, false, false);
@@ -245,11 +244,9 @@ public class TestBlockingChecker {
} catch (BlockingApiException e) {
//Expected behavior
}
-
-
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testBundleChecker() throws Exception {
setStateAccount(false, false, false);
setStateBundle(false, false, false);
@@ -290,7 +287,6 @@ public class TestBlockingChecker {
//Expected behavior
}
-
//BLOCKED ACCOUNT
setStateSubscription(false, false, false);
setStateBundle(false, false, false);
@@ -323,11 +319,9 @@ public class TestBlockingChecker {
} catch (BlockingApiException e) {
//Expected behavior
}
-
-
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testAccountChecker() throws Exception {
setStateAccount(false, false, false);
setStateBundle(false, false, false);
@@ -368,9 +362,5 @@ public class TestBlockingChecker {
} catch (BlockingApiException e) {
//Expected behavior
}
-
-
}
-
-
}
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 4659778..17c7f18 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
@@ -16,59 +16,30 @@
package com.ning.billing.junction.dao;
-import java.io.IOException;
import java.util.SortedSet;
import java.util.UUID;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.mockito.Mockito;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
-import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
+import com.ning.billing.junction.JunctionTestSuiteWithEmbeddedDB;
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.DefaultBlockingState;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockEntitlementModule;
import com.ning.billing.util.clock.ClockMock;
-import com.ning.billing.util.io.IOUtils;
@Guice(modules = {MockModule.class, MockEntitlementModule.class})
-public class TestBlockingDao {
- private final Logger log = LoggerFactory.getLogger(TestBlockingDao.class);
-
- @Inject
- private MysqlTestingHelper helper;
-
+public class TestBlockingDao extends JunctionTestSuiteWithEmbeddedDB {
@Inject
private BlockingStateDao dao;
- @BeforeClass(groups = {"slow"})
- public void setup() throws IOException {
- log.info("Starting set up TestBlockingDao");
-
- final String utilDdl = IOUtils.toString(TestBlockingDao.class.getResourceAsStream("/com/ning/billing/junction/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
- }
-
- @AfterClass(groups = "slow")
- public void stopMysql() {
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testDao() {
final ClockMock clock = new ClockMock();
final UUID uuid = UUID.randomUUID();
@@ -87,15 +58,14 @@ public class TestBlockingDao {
final BlockingState state2 = new DefaultBlockingState(uuid, overdueStateName2, Blockable.Type.SUBSCRIPTION_BUNDLE, service, blockChange, blockEntitlement, blockBilling);
dao.setBlockingState(state2, clock);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", uuid);
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(uuid);
Assert.assertEquals(dao.getBlockingStateFor(bundle).getStateName(), state2.getStateName());
Assert.assertEquals(dao.getBlockingStateFor(bundle.getId()).getStateName(), overdueStateName2);
-
}
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testDaoHistory() throws Exception {
final ClockMock clock = new ClockMock();
final UUID uuid = UUID.randomUUID();
@@ -114,9 +84,8 @@ public class TestBlockingDao {
final BlockingState state2 = new DefaultBlockingState(uuid, overdueStateName2, Blockable.Type.SUBSCRIPTION_BUNDLE, service, blockChange, blockEntitlement, blockBilling);
dao.setBlockingState(state2, clock);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", uuid);
-
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(uuid);
final SortedSet<BlockingState> history1 = dao.getBlockingHistoryFor(bundle);
final SortedSet<BlockingState> history2 = dao.getBlockingHistoryFor(bundle.getId());
@@ -128,7 +97,5 @@ public class TestBlockingDao {
Assert.assertEquals(history2.size(), 2);
Assert.assertEquals(history2.first().getStateName(), overdueStateName);
Assert.assertEquals(history2.last().getStateName(), overdueStateName2);
-
}
-
}
diff --git a/junction/src/test/java/com/ning/billing/junction/JunctionTestSuite.java b/junction/src/test/java/com/ning/billing/junction/JunctionTestSuite.java
new file mode 100644
index 0000000..69d5ebf
--- /dev/null
+++ b/junction/src/test/java/com/ning/billing/junction/JunctionTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.junction;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class JunctionTestSuite extends KillbillTestSuite {
+}
diff --git a/junction/src/test/java/com/ning/billing/junction/JunctionTestSuiteWithEmbeddedDB.java b/junction/src/test/java/com/ning/billing/junction/JunctionTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..3089ee7
--- /dev/null
+++ b/junction/src/test/java/com/ning/billing/junction/JunctionTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.junction;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class JunctionTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/junction/src/test/java/com/ning/billing/junction/MockBlockingModule.java b/junction/src/test/java/com/ning/billing/junction/MockBlockingModule.java
index 2b7a0a9..3158d68 100644
--- a/junction/src/test/java/com/ning/billing/junction/MockBlockingModule.java
+++ b/junction/src/test/java/com/ning/billing/junction/MockBlockingModule.java
@@ -16,20 +16,18 @@
package com.ning.billing.junction;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.dao.BlockingStateDao;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
public class MockBlockingModule extends AbstractModule {
- public static final String CLEAR_STATE = "Clear";
-
@Override
protected void configure() {
- final BlockingApi BlockingApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BlockingApi.class);
- ((ZombieControl) BlockingApi).addResult("getOverdueStateNameFor", MockBlockingModule.CLEAR_STATE);
- bind(BlockingStateDao.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(BlockingStateDao.class));
- bind(BlockingApi.class).toInstance(BlockingApi);
+ bind(BlockingStateDao.class).toInstance(Mockito.mock(BlockingStateDao.class));
+
+ final BlockingApi blockingApi = Mockito.mock(BlockingApi.class);
+ bind(BlockingApi.class).toInstance(blockingApi);
}
}
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 1291437..7865bcd 100644
--- a/junction/src/test/java/com/ning/billing/junction/MockModule.java
+++ b/junction/src/test/java/com/ning/billing/junction/MockModule.java
@@ -22,10 +22,7 @@ import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.mock.glue.MockDbHelperModule;
import com.ning.billing.util.glue.CallContextModule;
-
public class MockModule extends DefaultJunctionModule {
- public static final String PLUGIN_NAME = "Booboo";
-
@Override
protected void configure() {
super.configure();
@@ -38,13 +35,10 @@ public class MockModule extends DefaultJunctionModule {
@Override
public void installBillingApi() {
- // no billinggApi
+ // no billing Api
}
@Override
public void installAccountUserApi() {
-
}
-
-
}
diff --git a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBillingApi.java b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBillingApi.java
index ae5f680..ad6522c 100644
--- a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBillingApi.java
+++ b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestBillingApi.java
@@ -16,7 +16,6 @@
package com.ning.billing.junction.plumbing.billing;
-
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
@@ -30,12 +29,14 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
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.MockCatalog;
import com.ning.billing.catalog.MockCatalogService;
@@ -53,11 +54,13 @@ import com.ning.billing.catalog.api.PriceListSet;
import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.BillingModeType;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
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.Subscription.SubscriptionState;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
+import com.ning.billing.junction.JunctionTestSuite;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BillingEventSet;
import com.ning.billing.junction.api.Blockable;
@@ -65,8 +68,8 @@ 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.lifecycle.KillbillService.ServiceException;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
+import com.ning.billing.mock.MockEffectiveSubscriptionEvent;
+import com.ning.billing.mock.MockSubscription;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.callcontext.CallContextFactory;
import com.ning.billing.util.callcontext.DefaultCallContextFactory;
@@ -82,8 +85,7 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
-public class TestBillingApi {
-
+public class TestBillingApi extends JunctionTestSuite {
class MockPrice implements InternationalPrice {
private final BigDecimal price;
@@ -100,7 +102,6 @@ public class TestBillingApi {
public Price[] getPrices() {
return new Price[]{
new Price() {
-
@Override
public Currency getCurrency() {
return Currency.USD;
@@ -110,7 +111,6 @@ public class TestBillingApi {
public BigDecimal getValue() throws CurrencyValueNull {
return price;
}
-
}
};
}
@@ -130,95 +130,65 @@ public class TestBillingApi {
private CatalogService catalogService;
- private List<SubscriptionEvent> subscriptionTransitions;
+ private List<EffectiveSubscriptionEvent> effectiveSubscriptionTransitions;
private EntitlementUserApi entitlementApi;
private final BlockingCalculator blockCalculator = new BlockingCalculator(null) {
@Override
public void insertBlockingEvents(final SortedSet<BillingEvent> billingEvents) {
-
}
-
};
-
private Clock clock;
private Subscription subscription;
private DateTime subscriptionStartDate;
private Plan subscriptionPlan;
private TagUserApi tagApi;
- @BeforeSuite(groups = {"fast", "slow"})
+ @BeforeSuite(groups = "fast")
public void setup() throws ServiceException {
catalogService = new MockCatalogService(new MockCatalog());
clock = new ClockMock();
}
- @BeforeMethod(groups = {"fast", "slow"})
- public void setupEveryTime() {
+ @BeforeMethod(groups = "fast")
+ public void setupEveryTime() throws EntitlementUserApiException {
final List<SubscriptionBundle> bundles = new ArrayList<SubscriptionBundle>();
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", bunId);
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(bunId);
//new SubscriptionBundleData( eventId,"TestKey", subId, clock.getUTCNow().minusDays(4), null);
bundles.add(bundle);
-
- subscriptionTransitions = new LinkedList<SubscriptionEvent>();
+ effectiveSubscriptionTransitions = new LinkedList<EffectiveSubscriptionEvent>();
final List<Subscription> subscriptions = new LinkedList<Subscription>();
subscriptionStartDate = clock.getUTCNow().minusDays(3);
- subscription = new MockSubscription() {
- @Override
- public List<SubscriptionEvent> getBillingTransitions() {
- return subscriptionTransitions;
- }
-
- @Override
- public Plan getCurrentPlan() {
- return subscriptionPlan;
- }
-
- @Override
- public UUID getId() {
- return subId;
- }
-
- @Override
- public UUID getBundleId() {
- return bunId;
- }
-
- @Override
- public DateTime getStartDate() {
- return subscriptionStartDate;
- }
-
-
- };
+ subscription = new MockSubscription(subId, bunId, subscriptionPlan, subscriptionStartDate, effectiveSubscriptionTransitions);
subscriptions.add(subscription);
- entitlementApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- ((ZombieControl) entitlementApi).addResult("getBundlesForAccount", bundles);
- ((ZombieControl) entitlementApi).addResult("getSubscriptionsForBundle", subscriptions);
- ((ZombieControl) entitlementApi).addResult("getSubscriptionFromId", subscription);
- ((ZombieControl) entitlementApi).addResult("getBundleFromId", bundle);
- ((ZombieControl) entitlementApi).addResult("getBaseSubscription", subscription);
+ entitlementApi = Mockito.mock(EntitlementUserApi.class);
+ Mockito.when(entitlementApi.getBundlesForAccount(Mockito.<UUID>any())).thenReturn(bundles);
+ Mockito.when(entitlementApi.getSubscriptionsForBundle(Mockito.<UUID>any())).thenReturn(subscriptions);
+ Mockito.when(entitlementApi.getSubscriptionFromId(Mockito.<UUID>any())).thenReturn(subscription);
+ Mockito.when(entitlementApi.getBundleFromId(Mockito.<UUID>any())).thenReturn(bundle);
+ Mockito.when(entitlementApi.getBaseSubscription(Mockito.<UUID>any())).thenReturn(subscription);
tagApi = mock(TagUserApi.class);
assertTrue(true);
}
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsEmpty() {
+ @Test(groups = "fast")
+ public void testBillingEventsEmpty() throws AccountApiException {
final UUID accountId = UUID.randomUUID();
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getId", accountId).addResult("getCurrency", Currency.USD);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getId()).thenReturn(accountId);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
final BillCycleDayCalculator bcdCalculator = new BillCycleDayCalculator(catalogService, entitlementApi);
final CallContextFactory factory = new DefaultCallContextFactory(clock);
@@ -229,29 +199,29 @@ public class TestBillingApi {
Assert.assertEquals(events.size(), 0);
}
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsNoBillingPeriod() throws CatalogApiException {
+ @Test(groups = "fast")
+ public void testBillingEventsNoBillingPeriod() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[0]; // The trial has no billing period
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
- subscriptionTransitions.add(t);
+ effectiveSubscriptionTransitions.add(t);
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 32);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) account).addResult("getTimeZone", DateTimeZone.UTC);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(32);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
final BillCycleDayCalculator bcdCalculator = new BillCycleDayCalculator(catalogService, entitlementApi);
final CallContextFactory factory = new DefaultCallContextFactory(clock);
@@ -262,28 +232,29 @@ public class TestBillingApi {
}
@Test(enabled = false, groups = "fast")
- public void testBillingEventsAnnual() throws CatalogApiException {
+ public void testBillingEventsAnnual() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[1];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
- subscriptionTransitions.add(t);
+ effectiveSubscriptionTransitions.add(t);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 1).addResult("getTimeZone", DateTimeZone.UTC)
- .addResult("getCurrency", Currency.USD);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(1);
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
((MockCatalog) catalogService.getFullCatalog()).setBillingAlignment(BillingAlignment.SUBSCRIPTION);
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
final BillCycleDayCalculator bcdCalculator = new BillCycleDayCalculator(catalogService, entitlementApi);
final CallContextFactory factory = new DefaultCallContextFactory(clock);
@@ -294,30 +265,29 @@ public class TestBillingApi {
checkFirstEvent(events, nextPlan, subscription.getStartDate().plusDays(30).getDayOfMonth(), subId, now, nextPhase, SubscriptionTransitionType.CREATE.toString());
}
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsMonthly() throws CatalogApiException {
+ @Test(groups = "fast")
+ public void testBillingEventsMonthly() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[1];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
+ effectiveSubscriptionTransitions.add(t);
- subscriptionTransitions.add(t);
-
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 32);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) account).addResult("getTimeZone", DateTimeZone.UTC);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(32);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
((MockCatalog) catalogService.getFullCatalog()).setBillingAlignment(BillingAlignment.ACCOUNT);
@@ -331,29 +301,30 @@ public class TestBillingApi {
}
@Test(enabled = false, groups = "fast")
- public void testBillingEventsAddOn() throws CatalogApiException {
+ public void testBillingEventsAddOn() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("Horn1USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[0];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
- subscriptionTransitions.add(t);
+ effectiveSubscriptionTransitions.add(t);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 1).addResult("getTimeZone", DateTimeZone.UTC);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) account).addResult("getTimeZone", DateTimeZone.UTC);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(1);
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
((MockCatalog) catalogService.getFullCatalog()).setBillingAlignment(BillingAlignment.BUNDLE);
@@ -368,30 +339,29 @@ public class TestBillingApi {
checkFirstEvent(events, nextPlan, subscription.getStartDate().plusDays(30).getDayOfMonth(), subId, now, nextPhase, SubscriptionTransitionType.CREATE.toString());
}
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsWithBlock() throws CatalogApiException {
+ @Test(groups = "fast")
+ public void testBillingEventsWithBlock() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[1];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
-
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
- subscriptionTransitions.add(t);
+ effectiveSubscriptionTransitions.add(t);
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 32);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getTimeZone", DateTimeZone.UTC);
- ((ZombieControl) accountApi).addResult("getAccountById", account);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(32);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
((MockCatalog) catalogService.getFullCatalog()).setBillingAlignment(BillingAlignment.ACCOUNT);
@@ -400,7 +370,6 @@ public class TestBillingApi {
blockingStates.add(new DefaultBlockingState(bunId, CLEAR_BUNDLE, Blockable.Type.SUBSCRIPTION_BUNDLE, "test", false, false, false, now.plusDays(2)));
final BlockingCalculator blockingCal = new BlockingCalculator(new BlockingApi() {
-
@Override
public <T extends Blockable> void setBlockingState(final BlockingState state) {
}
@@ -440,32 +409,30 @@ public class TestBillingApi {
checkEvent(it.next(), nextPlan, 32, subId, now, nextPhase, SubscriptionTransitionType.CREATE.toString(), nextPhase.getFixedPrice(), nextPhase.getRecurringPrice());
checkEvent(it.next(), nextPlan, 32, subId, now.plusDays(1), nextPhase, SubscriptionTransitionType.CANCEL.toString(), new MockPrice("0"), new MockPrice("0"));
checkEvent(it.next(), nextPlan, 32, subId, now.plusDays(2), nextPhase, SubscriptionTransitionType.RE_CREATE.toString(), nextPhase.getFixedPrice(), nextPhase.getRecurringPrice());
-
}
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsAutoInvoicingOffAccount() throws CatalogApiException {
+ @Test(groups = "fast")
+ public void testBillingEventsAutoInvoicingOffAccount() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[1];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
+ effectiveSubscriptionTransitions.add(t);
- subscriptionTransitions.add(t);
-
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 32);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(32);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
final Map<String, Tag> tags = new HashMap<String, Tag>();
final Tag aioTag = mock(Tag.class);
@@ -486,30 +453,28 @@ public class TestBillingApi {
assertEquals(events.size(), 0);
}
-
- @Test(enabled = true, groups = "fast")
- public void testBillingEventsAutoInvoicingOffBundle() throws CatalogApiException {
+ @Test(groups = "fast")
+ public void testBillingEventsAutoInvoicingOffBundle() throws CatalogApiException, AccountApiException {
final DateTime now = clock.getUTCNow();
final DateTime then = now.minusDays(1);
final Plan nextPlan = catalogService.getFullCatalog().findPlan("PickupTrialEvergreen10USD", now);
final PlanPhase nextPhase = nextPlan.getAllPhases()[1];
final PriceList nextPriceList = catalogService.getFullCatalog().findPriceList(PriceListSet.DEFAULT_PRICELIST_NAME, now);
- final SubscriptionEvent t = new MockSubscriptionEvent(
+ final EffectiveSubscriptionEvent t = new MockEffectiveSubscriptionEvent(
eventId, subId, bunId, then, now, null, null, null, null, SubscriptionState.ACTIVE,
nextPlan.getName(), nextPhase.getName(),
nextPriceList.getName(), 1L, null,
SubscriptionTransitionType.CREATE, 0, null);
+ effectiveSubscriptionTransitions.add(t);
- subscriptionTransitions.add(t);
-
- final AccountUserApi accountApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- ((ZombieControl) account).addResult("getBillCycleDay", 32);
- ((ZombieControl) account).addResult("getCurrency", Currency.USD);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) accountApi).addResult("getAccountById", account);
+ final AccountUserApi accountApi = Mockito.mock(AccountUserApi.class);
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getBillCycleDay()).thenReturn(32);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(accountApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
final Map<String, Tag> tags = new HashMap<String, Tag>();
final Tag aioTag = mock(Tag.class);
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 ce0b6dc..f17f681 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
@@ -27,6 +27,7 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -44,6 +45,7 @@ import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.BillingModeType;
import com.ning.billing.entitlement.api.user.Subscription;
+import com.ning.billing.junction.JunctionTestSuite;
import com.ning.billing.junction.api.Blockable;
import com.ning.billing.junction.api.Blockable.Type;
import com.ning.billing.junction.api.BlockingApi;
@@ -51,8 +53,6 @@ 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.junction.plumbing.billing.BlockingCalculator.DisabledDuration;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
@@ -60,9 +60,7 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
-
-public class TestBlockingCalculator {
-
+public class TestBlockingCalculator extends JunctionTestSuite {
private static final String DISABLED_BUNDLE = "disabled-bundle";
private static final String CLEAR_BUNDLE = "clear-bundle";
@@ -79,37 +77,29 @@ public class TestBlockingCalculator {
@BeforeClass
public void setUpBeforeClass() throws Exception {
-
clock = new ClockMock();
final Injector i = Guice.createInjector(new AbstractModule() {
-
@Override
protected void configure() {
- blockingApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BlockingApi.class);
- account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- subscription1 = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class, Comparable.class);
- subscription2 = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class, Comparable.class);
- subscription3 = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class, Comparable.class);
- subscription4 = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class, Comparable.class);
- ((ZombieControl) account).addResult("getId", UUID.randomUUID());
- ((ZombieControl) subscription1).addResult("getBundleId", bundleId1);
- ((ZombieControl) subscription2).addResult("getBundleId", bundleId1);
- ((ZombieControl) subscription3).addResult("getBundleId", bundleId1);
- ((ZombieControl) subscription4).addResult("getBundleId", bundleId2);
- ((ZombieControl) subscription1).addResult("compareTo", 1);
- ((ZombieControl) subscription2).addResult("compareTo", 1);
- ((ZombieControl) subscription3).addResult("compareTo", 1);
- ((ZombieControl) subscription4).addResult("compareTo", 1);
- ((ZombieControl) subscription1).addResult("getId", UUID.randomUUID());
- ((ZombieControl) subscription2).addResult("getId", UUID.randomUUID());
- ((ZombieControl) subscription3).addResult("getId", UUID.randomUUID());
- ((ZombieControl) subscription4).addResult("getId", UUID.randomUUID());
-
-
- bind(BlockingStateDao.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(BlockingStateDao.class));
+ blockingApi = Mockito.mock(BlockingApi.class);
+ account = Mockito.mock(Account.class);
+ subscription1 = Mockito.mock(Subscription.class);
+ subscription2 = Mockito.mock(Subscription.class);
+ subscription3 = Mockito.mock(Subscription.class);
+ subscription4 = Mockito.mock(Subscription.class);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(subscription1.getBundleId()).thenReturn(bundleId1);
+ Mockito.when(subscription2.getBundleId()).thenReturn(bundleId1);
+ Mockito.when(subscription3.getBundleId()).thenReturn(bundleId1);
+ Mockito.when(subscription4.getBundleId()).thenReturn(bundleId2);
+ Mockito.when(subscription1.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(subscription2.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(subscription3.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(subscription4.getId()).thenReturn(UUID.randomUUID());
+
+ bind(BlockingStateDao.class).toInstance(Mockito.mock(BlockingStateDao.class));
bind(BlockingApi.class).toInstance(blockingApi);
-
}
});
@@ -117,19 +107,17 @@ public class TestBlockingCalculator {
}
- @Test
// S1-S2-S3 subscriptions in B1
// B1 -----[--------]
// S1 --A-------------------------------------
// S2 --B------C------------------------------
// S3 ------------------D---------------------
-
//Result
// S1 --A--[-------]--------------------------
// S2 --B--[-------]--------------------------
// S3 ------------------D---------------------
-
+ @Test
public void testInsertBlockingEvents() {
final DateTime now = clock.getUTCNow();
final List<DisabledDuration> disabledDuration = new ArrayList<BlockingCalculator.DisabledDuration>();
@@ -149,8 +137,7 @@ public class TestBlockingCalculator {
blockingStates.add(new DefaultBlockingState(bundleId1, DISABLED_BUNDLE, Blockable.Type.SUBSCRIPTION_BUNDLE, "test", true, true, true, now));
blockingStates.add(new DefaultBlockingState(bundleId1, CLEAR_BUNDLE, Blockable.Type.SUBSCRIPTION_BUNDLE, "test", false, false, false, now.plusDays(2)));
- ((ZombieControl) blockingApi).addResult("getBlockingHistory", blockingStates);
-
+ Mockito.when(blockingApi.getBlockingHistory(Mockito.<Blockable>anyObject())).thenReturn(blockingStates);
odc.insertBlockingEvents(billingEvents);
@@ -258,7 +245,6 @@ public class TestBlockingCalculator {
billingEvents.add(e1);
billingEvents.add(e2);
-
final SortedSet<BillingEvent> results = odc.eventsToRemove(disabledDuration, billingEvents, subscription1);
assertEquals(results.size(), 1);
@@ -299,7 +285,6 @@ public class TestBlockingCalculator {
final BillingEvent e2 = createRealEvent(now.plusDays(1), subscription1);
billingEvents.add(e2);
-
final SortedSet<BillingEvent> results = odc.eventsToRemove(disabledDuration, billingEvents, subscription1);
assertEquals(results.size(), 1);
@@ -566,7 +551,6 @@ public class TestBlockingCalculator {
description, totalOrdering, type, tz);
}
-
@Test
public void testFilter() {
final SortedSet<BillingEvent> events = new TreeSet<BillingEvent>();
@@ -653,9 +637,9 @@ public class TestBlockingCalculator {
}
private BillingEvent createBillingEvent(final Subscription subscription) {
- final BillingEvent result = BrainDeadProxyFactory.createBrainDeadProxyFor(BillingEvent.class, Comparable.class);
- ((ZombieControl) result).addResult("getSubscription", subscription);
- ((ZombieControl) result).addResult("compareTo", 1);
+ final BillingEvent result = Mockito.mock(BillingEvent.class);
+ Mockito.when(result.getSubscription()).thenReturn(subscription);
+ Mockito.when(result.compareTo(Mockito.<BillingEvent>any())).thenReturn(1);
return result;
}
@@ -702,7 +686,6 @@ public class TestBlockingCalculator {
assertNotNull(pairs.get(0).getEnd());
assertEquals(pairs.get(0).getEnd(), now.plusDays(2));
-
//two or more disableds in a row
blockingEvents = new TreeSet<BlockingState>();
blockingEvents.add(new DefaultBlockingState(ovdId, CLEAR_BUNDLE, Type.SUBSCRIPTION_BUNDLE, "test", false, false, false, now));
@@ -717,7 +700,6 @@ public class TestBlockingCalculator {
assertNotNull(pairs.get(0).getEnd());
assertEquals(pairs.get(0).getEnd(), now.plusDays(3));
-
blockingEvents = new TreeSet<BlockingState>();
blockingEvents.add(new DefaultBlockingState(ovdId, CLEAR_BUNDLE, Type.SUBSCRIPTION_BUNDLE, "test", false, false, false, now));
blockingEvents.add(new DefaultBlockingState(ovdId, DISABLED_BUNDLE, Type.SUBSCRIPTION_BUNDLE, "test", true, true, true, now.plusDays(1)));
@@ -731,6 +713,5 @@ public class TestBlockingCalculator {
assertEquals(pairs.get(0).getStart(), now.plusDays(1));
assertNotNull(pairs.get(0).getEnd());
assertEquals(pairs.get(0).getEnd(), now.plusDays(4));
-
}
}
diff --git a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultBillingEvent.java b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultBillingEvent.java
index 6a6abfb..6f8ea89 100644
--- a/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultBillingEvent.java
+++ b/junction/src/test/java/com/ning/billing/junction/plumbing/billing/TestDefaultBillingEvent.java
@@ -25,6 +25,7 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
@@ -41,15 +42,14 @@ import com.ning.billing.entitlement.api.SubscriptionTransitionType;
import com.ning.billing.entitlement.api.billing.BillingEvent;
import com.ning.billing.entitlement.api.billing.BillingModeType;
import com.ning.billing.entitlement.api.user.Subscription;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
+import com.ning.billing.junction.JunctionTestSuite;
-public class TestDefaultBillingEvent {
+public class TestDefaultBillingEvent extends JunctionTestSuite {
public static final UUID ID_ZERO = new UUID(0L, 0L);
public static final UUID ID_ONE = new UUID(0L, 1L);
public static final UUID ID_TWO = new UUID(0L, 2L);
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testEventOrderingSubscription() {
final BillingEvent event0 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-31T00:02:04.000Z"), SubscriptionTransitionType.CREATE);
@@ -68,9 +68,8 @@ public class TestDefaultBillingEvent {
Assert.assertEquals(event2, it.next());
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testEventOrderingDate() {
-
final BillingEvent event0 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.CREATE);
final BillingEvent event1 = createEvent(subscription(ID_ZERO), new DateTime("2012-02-01T00:02:04.000Z"), SubscriptionTransitionType.CREATE);
final BillingEvent event2 = createEvent(subscription(ID_ZERO), new DateTime("2012-03-01T00:02:04.000Z"), SubscriptionTransitionType.CREATE);
@@ -87,9 +86,8 @@ public class TestDefaultBillingEvent {
Assert.assertEquals(event2, it.next());
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testEventTotalOrdering() {
-
final BillingEvent event0 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.CREATE, 1L);
final BillingEvent event1 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.CANCEL, 2L);
final BillingEvent event2 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.RE_CREATE, 3L);
@@ -106,9 +104,8 @@ public class TestDefaultBillingEvent {
Assert.assertEquals(event2, it.next());
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testEventOrderingMix() {
-
final BillingEvent event0 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.CREATE);
final BillingEvent event1 = createEvent(subscription(ID_ZERO), new DateTime("2012-01-02T00:02:04.000Z"), SubscriptionTransitionType.CHANGE);
final BillingEvent event2 = createEvent(subscription(ID_ONE), new DateTime("2012-01-01T00:02:04.000Z"), SubscriptionTransitionType.CANCEL);
@@ -149,9 +146,8 @@ public class TestDefaultBillingEvent {
}
private Subscription subscription(final UUID id) {
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) subscription).addResult("getId", id);
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(subscription.getId()).thenReturn(id);
return subscription;
}
-
}
overdue/pom.xml 12(+11 -1)
diff --git a/overdue/pom.xml b/overdue/pom.xml
index 3104bae..4b45e0d 100644
--- a/overdue/pom.xml
+++ b/overdue/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-overdue</artifactId>
@@ -56,6 +56,11 @@
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>com.ning.billing</groupId>
@@ -94,6 +99,11 @@
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckNotifier.java b/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckNotifier.java
index 0d58473..cf51e2b 100644
--- a/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckNotifier.java
+++ b/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckNotifier.java
@@ -35,20 +35,19 @@ import com.ning.billing.util.notificationq.NotificationQueueService.Notification
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
public class DefaultOverdueCheckNotifier implements OverdueCheckNotifier {
-
private static final Logger log = LoggerFactory.getLogger(DefaultOverdueCheckNotifier.class);
public static final String OVERDUE_CHECK_NOTIFIER_QUEUE = "overdue-check-queue";
private final NotificationQueueService notificationQueueService;
private final OverdueProperties config;
+ private final OverdueListener listener;
private NotificationQueue overdueQueue;
- private final OverdueListener listener;
@Inject
- public DefaultOverdueCheckNotifier(final NotificationQueueService notificationQueueService,
- final OverdueProperties config, final OverdueListener listener) {
+ public DefaultOverdueCheckNotifier(final NotificationQueueService notificationQueueService, final OverdueProperties config,
+ final OverdueListener listener) {
this.notificationQueueService = notificationQueueService;
this.config = config;
this.listener = listener;
@@ -56,38 +55,41 @@ public class DefaultOverdueCheckNotifier implements OverdueCheckNotifier {
@Override
public void initialize() {
- try {
- overdueQueue = notificationQueueService.createNotificationQueue(DefaultOverdueService.OVERDUE_SERVICE_NAME,
- OVERDUE_CHECK_NOTIFIER_QUEUE,
- new NotificationQueueHandler() {
- @Override
- public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate) {
- try {
- if (! (notificationKey instanceof OverdueCheckNotificationKey)) {
- log.error("Overdue service received Unexpected notificationKey {}", notificationKey.getClass().getName());
- return;
- }
- final OverdueCheckNotificationKey key = (OverdueCheckNotificationKey) notificationKey;
- processEvent(key.getUuidKey(), eventDate);
- } catch (IllegalArgumentException e) {
- log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
+ final NotificationConfig notificationConfig = new NotificationConfig() {
+ @Override
+ public boolean isNotificationProcessingOff() {
+ return config.isNotificationProcessingOff();
+ }
+
+ @Override
+ public long getSleepTimeMs() {
+ return config.getSleepTimeMs();
+ }
+ };
+
+ final NotificationQueueHandler notificationQueueHandler = new NotificationQueueHandler() {
+ @Override
+ public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDate) {
+ try {
+ if (!(notificationKey instanceof OverdueCheckNotificationKey)) {
+ log.error("Overdue service received Unexpected notificationKey {}", notificationKey.getClass().getName());
return;
}
- }
- },
- new NotificationConfig() {
- @Override
- public boolean isNotificationProcessingOff() {
- return config.isNotificationProcessingOff();
+ final OverdueCheckNotificationKey key = (OverdueCheckNotificationKey) notificationKey;
+ processEvent(key.getUuidKey(), eventDate);
+ } catch (IllegalArgumentException e) {
+ log.error("The key returned from the NextBillingNotificationQueue is not a valid UUID", e);
}
- @Override
- public long getSleepTimeMs() {
- return config.getSleepTimeMs();
- }
}
- );
+ };
+
+ try {
+ overdueQueue = notificationQueueService.createNotificationQueue(DefaultOverdueService.OVERDUE_SERVICE_NAME,
+ OVERDUE_CHECK_NOTIFIER_QUEUE,
+ notificationQueueHandler,
+ notificationConfig);
} catch (NotificationQueueAlreadyExists e) {
throw new RuntimeException(e);
}
@@ -113,6 +115,4 @@ public class DefaultOverdueCheckNotifier implements OverdueCheckNotifier {
private void processEvent(final UUID overdueableId, final DateTime eventDateTime) {
listener.handleNextOverdueCheck(overdueableId);
}
-
-
}
diff --git a/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckPoster.java b/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckPoster.java
index 79cfdf9..ad11522 100644
--- a/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckPoster.java
+++ b/overdue/src/main/java/com/ning/billing/ovedue/notification/DefaultOverdueCheckPoster.java
@@ -50,11 +50,11 @@ public class DefaultOverdueCheckPoster implements OverdueCheckPoster {
DefaultOverdueCheckNotifier.OVERDUE_CHECK_NOTIFIER_QUEUE);
log.info("Queuing overdue check notification. id: {}, timestamp: {}", overdueable.getId().toString(), futureNotificationTime.toString());
- checkOverdueQueue.recordFutureNotification(futureNotificationTime, new OverdueCheckNotificationKey(overdueable.getId()));
+ checkOverdueQueue.recordFutureNotification(futureNotificationTime, null, new OverdueCheckNotificationKey(overdueable.getId()));
} catch (NoSuchNotificationQueue e) {
log.error("Attempting to put items on a non-existent queue (DefaultOverdueCheck).", e);
} catch (IOException e) {
- log.error("Failed to serialize notifcationKey for {}", overdueable.toString());
+ log.error("Failed to serialize notifcationKey for {}", overdueable.toString());
}
}
diff --git a/overdue/src/main/java/com/ning/billing/overdue/applicator/DefaultOverdueChangeEvent.java b/overdue/src/main/java/com/ning/billing/overdue/applicator/DefaultOverdueChangeEvent.java
new file mode 100644
index 0000000..982f18a
--- /dev/null
+++ b/overdue/src/main/java/com/ning/billing/overdue/applicator/DefaultOverdueChangeEvent.java
@@ -0,0 +1,79 @@
+/*
+ * 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.overdue.applicator;
+
+import java.util.UUID;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.ning.billing.junction.api.Blockable;
+import com.ning.billing.junction.api.Blockable.Type;
+import com.ning.billing.overdue.OverdueChangeEvent;
+
+public class DefaultOverdueChangeEvent implements OverdueChangeEvent {
+ private final UUID overdueObjectId;
+ private final Blockable.Type overdueObjectType;
+ private final String previousOverdueStateName;
+ private final String nextOverdueStateName;
+ private final UUID userToken;
+
+
+ @JsonCreator
+ public DefaultOverdueChangeEvent(@JsonProperty("overdueObjectId") final UUID overdueObjectId,
+ @JsonProperty("overdueObjectType") final Blockable.Type overdueObjectType,
+ @JsonProperty("previousOverdueStateName") final String previousOverdueStateName,
+ @JsonProperty("nextOverdueStateName") final String nextOverdueStateName,
+ @JsonProperty("userToken") final UUID userToken) {
+ this.overdueObjectId = overdueObjectId;
+ this.overdueObjectType = overdueObjectType;
+ this.previousOverdueStateName = previousOverdueStateName;
+ this.nextOverdueStateName = nextOverdueStateName;
+ this.userToken = userToken;
+ }
+
+ @JsonIgnore
+ @Override
+ public BusEventType getBusEventType() {
+ return BusEventType.OVERDUE_CHANGE;
+ }
+
+ @Override
+ public UUID getUserToken() {
+ return userToken;
+ }
+ @Override
+ public String getPreviousOverdueStateName() {
+ return previousOverdueStateName;
+ }
+
+ @Override
+ public UUID getOverdueObjectId() {
+ return overdueObjectId;
+ }
+
+ @Override
+ public Type getOverdueObjectType() {
+ return overdueObjectType;
+ }
+
+ @Override
+ public String getNextOverdueStateName() {
+ return nextOverdueStateName;
+ }
+
+}
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 3f9704b..86c9a72 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
@@ -18,31 +18,39 @@ package com.ning.billing.overdue.applicator;
import org.joda.time.DateTime;
import org.joda.time.Period;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
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.BlockingApiException;
import com.ning.billing.junction.api.DefaultBlockingState;
import com.ning.billing.ovedue.notification.OverdueCheckPoster;
import com.ning.billing.overdue.OverdueApiException;
+import com.ning.billing.overdue.OverdueChangeEvent;
import com.ning.billing.overdue.OverdueService;
import com.ning.billing.overdue.OverdueState;
import com.ning.billing.overdue.config.api.OverdueError;
+import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.clock.Clock;
public class OverdueStateApplicator<T extends Blockable> {
+ private static final Logger log = LoggerFactory.getLogger(OverdueStateApplicator.class);
private final BlockingApi blockingApi;
private final Clock clock;
private final OverdueCheckPoster poster;
+ private final Bus bus;
@Inject
- public OverdueStateApplicator(final BlockingApi accessApi, final Clock clock, final OverdueCheckPoster poster) {
+ public OverdueStateApplicator(final BlockingApi accessApi, final Clock clock, final OverdueCheckPoster poster, final Bus bus) {
this.blockingApi = accessApi;
this.clock = clock;
this.poster = poster;
+ this.bus = bus;
}
public void apply(final T overdueable, final String previousOverdueStateName, final OverdueState<T> nextOverdueState) throws OverdueError {
@@ -65,9 +73,19 @@ public class OverdueStateApplicator<T extends Blockable> {
if (nextOverdueState.isClearState()) {
clear(overdueable);
}
+
+ try {
+ bus.post(createOverdueEvent(overdueable, previousOverdueStateName, nextOverdueState.getName()));
+ } catch (Exception e) {
+ log.error("Error posting overdue change event to bus",e);
+ }
}
+ private OverdueChangeEvent createOverdueEvent(T overdueable, String previousOverdueStateName, String nextOverdueStateName) throws BlockingApiException {
+ return new DefaultOverdueChangeEvent(overdueable.getId(), Blockable.Type.get(overdueable), previousOverdueStateName, nextOverdueStateName, null);
+ }
+
protected void storeNewState(final T blockable, final OverdueState<T> nextOverdueState) throws OverdueError {
try {
blockingApi.setBlockingState(new DefaultBlockingState(blockable.getId(), nextOverdueState.getName(), Blockable.Type.get(blockable),
diff --git a/overdue/src/main/java/com/ning/billing/overdue/glue/DefaultOverdueModule.java b/overdue/src/main/java/com/ning/billing/overdue/glue/DefaultOverdueModule.java
index a81e791..8536748 100644
--- a/overdue/src/main/java/com/ning/billing/overdue/glue/DefaultOverdueModule.java
+++ b/overdue/src/main/java/com/ning/billing/overdue/glue/DefaultOverdueModule.java
@@ -48,6 +48,7 @@ public class DefaultOverdueModule extends AbstractModule implements OverdueModul
bind(ExtendedOverdueService.class).to(DefaultOverdueService.class).asEagerSingleton();
bind(OverdueCheckNotifier.class).to(DefaultOverdueCheckNotifier.class).asEagerSingleton();
bind(OverdueCheckPoster.class).to(DefaultOverdueCheckPoster.class).asEagerSingleton();
+
}
protected void installOverdueService() {
diff --git a/overdue/src/test/java/com/ning/billing/overdue/applicator/OverdueBusListenerTester.java b/overdue/src/test/java/com/ning/billing/overdue/applicator/OverdueBusListenerTester.java
new file mode 100644
index 0000000..ee5e833
--- /dev/null
+++ b/overdue/src/test/java/com/ning/billing/overdue/applicator/OverdueBusListenerTester.java
@@ -0,0 +1,47 @@
+/*
+ * 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.overdue.applicator;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.eventbus.Subscribe;
+import com.ning.billing.overdue.OverdueChangeEvent;
+
+public class OverdueBusListenerTester {
+ public static final Logger log = LoggerFactory.getLogger(OverdueBusListenerTester.class);
+
+ private List<OverdueChangeEvent> eventsReceived = new ArrayList<OverdueChangeEvent>();
+
+ @Subscribe
+ public void handleOverdueChange(final OverdueChangeEvent changeEvent) {
+ log.info("Received subscription transition.");
+ eventsReceived.add(changeEvent);
+ }
+
+ public List<OverdueChangeEvent> getEventsReceived() {
+ return eventsReceived;
+ }
+
+ public void clearEventsReceived() {
+ eventsReceived.clear();
+ }
+
+}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/applicator/TestOverdueStateApplicator.java b/overdue/src/test/java/com/ning/billing/overdue/applicator/TestOverdueStateApplicator.java
index 35425d0..87347a3 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/applicator/TestOverdueStateApplicator.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/applicator/TestOverdueStateApplicator.java
@@ -16,52 +16,80 @@
package com.ning.billing.overdue.applicator;
-
import java.io.ByteArrayInputStream;
import java.io.InputStream;
+import java.util.List;
import java.util.UUID;
+import java.util.concurrent.Callable;
+import org.mockito.Mockito;
+import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import com.ning.billing.entitlement.api.user.SubscriptionBundle;
import com.ning.billing.junction.api.BlockingApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
+import com.ning.billing.overdue.OverdueChangeEvent;
import com.ning.billing.overdue.OverdueState;
import com.ning.billing.overdue.OverdueTestBase;
import com.ning.billing.overdue.config.OverdueConfig;
+import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.config.XMLLoader;
+import static com.jayway.awaitility.Awaitility.await;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
public class TestOverdueStateApplicator extends OverdueTestBase {
@Inject
OverdueStateApplicator<SubscriptionBundle> applicator;
- @Test(groups = {"slow"}, enabled = true)
+ @Inject
+ OverdueBusListenerTester listener;
+
+ @Inject
+ Bus bus;
+
+ @Test(groups = "slow")
public void testApplicator() throws Exception {
+ bus.register(listener);
+ bus.start();
final InputStream is = new ByteArrayInputStream(configXml.getBytes());
config = XMLLoader.getObjectFromStreamNoValidation(is, OverdueConfig.class);
overdueWrapperFactory.setOverdueConfig(config);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", UUID.randomUUID());
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(UUID.randomUUID());
OverdueState<SubscriptionBundle> state;
state = config.getBundleStateSet().findState("OD1");
applicator.apply(bundle, BlockingApi.CLEAR_STATE_NAME, state);
checkStateApplied(state);
-
+ checkBussEvent("OD1");
state = config.getBundleStateSet().findState("OD2");
applicator.apply(bundle, BlockingApi.CLEAR_STATE_NAME, state);
checkStateApplied(state);
+ checkBussEvent("OD2");
state = config.getBundleStateSet().findState("OD3");
applicator.apply(bundle, BlockingApi.CLEAR_STATE_NAME, state);
checkStateApplied(state);
-
+ checkBussEvent("OD3");
+ bus.stop();
}
-
+ private void checkBussEvent(final String state) throws Exception {
+ await().atMost(10, SECONDS).until(new Callable<Boolean>() {
+ @Override
+ public Boolean call() throws Exception {
+ final List<OverdueChangeEvent> events = listener.getEventsReceived();
+ return events.size() == 1;
+ }
+ });
+ final List<OverdueChangeEvent> events = listener.getEventsReceived();
+ Assert.assertEquals(1, events.size());
+ Assert.assertEquals(state, events.get(0).getNextOverdueStateName());
+ listener.clearEventsReceived();
+ }
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculator.java b/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculator.java
index 8f38f08..57426a3 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculator.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculator.java
@@ -24,6 +24,7 @@ import java.util.SortedSet;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
@@ -31,16 +32,14 @@ import com.ning.billing.entitlement.api.user.SubscriptionBundle;
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.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
+import com.ning.billing.overdue.OverdueTestSuite;
import com.ning.billing.overdue.config.api.BillingState;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
-public class TestBillingStateCalculator {
+public class TestBillingStateCalculator extends OverdueTestSuite {
Clock clock = new ClockMock();
- InvoiceUserApi invoiceApi = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceUserApi.class);
- private int hash = 0;
+ InvoiceUserApi invoiceApi = Mockito.mock(InvoiceUserApi.class);
DateTime now;
public BillingStateCalculator<SubscriptionBundle> createBSCalc() {
@@ -50,7 +49,7 @@ public class TestBillingStateCalculator {
invoices.add(createInvoice(now.plusDays(1), BigDecimal.TEN, null));
invoices.add(createInvoice(now.plusDays(2), new BigDecimal("100.0"), null));
- ((ZombieControl) invoiceApi).addResult("getUnpaidInvoicesByAccountId", invoices);
+ Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<DateTime>any())).thenReturn(invoices);
return new BillingStateCalculator<SubscriptionBundle>(invoiceApi, clock) {
@Override
@@ -62,17 +61,16 @@ public class TestBillingStateCalculator {
}
public Invoice createInvoice(final DateTime date, final BigDecimal balance, final List<InvoiceItem> invoiceItems) {
- final Invoice invoice = BrainDeadProxyFactory.createBrainDeadProxyFor(Invoice.class);
- ((ZombieControl) invoice).addResult("getBalance", balance);
- ((ZombieControl) invoice).addResult("getInvoiceDate", date);
- ((ZombieControl) invoice).addResult("hashCode", hash++);
- ((ZombieControl) invoice).addResult("getInvoiceItems", invoiceItems);
- ((ZombieControl) invoice).addResult("getId", UUID.randomUUID());
+ final Invoice invoice = Mockito.mock(Invoice.class);
+ Mockito.when(invoice.getBalance()).thenReturn(balance);
+ Mockito.when(invoice.getInvoiceDate()).thenReturn(date);
+ Mockito.when(invoice.getInvoiceItems()).thenReturn(invoiceItems);
+ Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());
return invoice;
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testUnpaidInvoices() {
final BillingStateCalculator<SubscriptionBundle> calc = createBSCalc();
final SortedSet<Invoice> invoices = calc.unpaidInvoicesForAccount(new UUID(0L, 0L));
@@ -82,21 +80,17 @@ public class TestBillingStateCalculator {
Assert.assertEquals(new BigDecimal("100.0").compareTo(invoices.last().getBalance()), 0);
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testSum() {
-
final BillingStateCalculator<SubscriptionBundle> calc = createBSCalc();
final SortedSet<Invoice> invoices = calc.unpaidInvoicesForAccount(new UUID(0L, 0L));
Assert.assertEquals(new BigDecimal("110.0").compareTo(calc.sumBalance(invoices)), 0);
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testEarliest() {
-
final BillingStateCalculator<SubscriptionBundle> calc = createBSCalc();
final SortedSet<Invoice> invoices = calc.unpaidInvoicesForAccount(new UUID(0L, 0L));
Assert.assertEquals(calc.earliest(invoices).getInvoiceDate(), now);
}
-
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculatorBundle.java b/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculatorBundle.java
index dc5b6a4..67b63ab 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculatorBundle.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/calculator/TestBillingStateCalculatorBundle.java
@@ -16,6 +16,7 @@
package com.ning.billing.overdue.calculator;
+import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@@ -23,9 +24,12 @@ import java.util.SortedSet;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
import com.ning.billing.catalog.MockPlan;
import com.ning.billing.catalog.MockPriceList;
import com.ning.billing.catalog.api.Plan;
@@ -36,27 +40,23 @@ import com.ning.billing.entitlement.api.user.SubscriptionBundle;
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.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.overdue.config.api.BillingStateBundle;
import com.ning.billing.overdue.config.api.PaymentResponse;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
public class TestBillingStateCalculatorBundle extends TestBillingStateCalculator {
-
-
private List<InvoiceItem> createInvoiceItems(final UUID[] bundleIds) {
final List<InvoiceItem> result = new ArrayList<InvoiceItem>();
for (final UUID id : bundleIds) {
- final InvoiceItem ii = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceItem.class);
- ((ZombieControl) ii).addResult("getBundleId", id);
+ final InvoiceItem ii = Mockito.mock(InvoiceItem.class);
+ Mockito.when(ii.getBundleId()).thenReturn(id);
result.add(ii);
}
return result;
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testUnpaidInvoiceForBundle() {
final UUID thisBundleId = new UUID(0L, 0L);
final UUID thatBundleId = new UUID(0L, 1L);
@@ -64,30 +64,32 @@ public class TestBillingStateCalculatorBundle extends TestBillingStateCalculator
now = new DateTime();
final List<Invoice> invoices = new ArrayList<Invoice>(5);
invoices.add(createInvoice(now, BigDecimal.ZERO, createInvoiceItems(new UUID[]{thisBundleId, thatBundleId})));
- invoices.add(createInvoice(now, BigDecimal.TEN, createInvoiceItems(new UUID[]{thatBundleId})));
- invoices.add(createInvoice(now, new BigDecimal("100.00"), createInvoiceItems(new UUID[]{thatBundleId, thisBundleId, thatBundleId})));
- invoices.add(createInvoice(now, new BigDecimal("1000.00"), createInvoiceItems(new UUID[]{thisBundleId})));
- invoices.add(createInvoice(now, new BigDecimal("10000.00"), createInvoiceItems(new UUID[]{thatBundleId, thisBundleId})));
-
+ // Will not be seen below
+ invoices.add(createInvoice(now.plusDays(1), BigDecimal.TEN, createInvoiceItems(new UUID[]{thatBundleId})));
+ invoices.add(createInvoice(now.plusDays(2), new BigDecimal("100.00"), createInvoiceItems(new UUID[]{thatBundleId, thisBundleId, thatBundleId})));
+ invoices.add(createInvoice(now.plusDays(3), new BigDecimal("1000.00"), createInvoiceItems(new UUID[]{thisBundleId})));
+ invoices.add(createInvoice(now.plusDays(4), new BigDecimal("10000.00"), createInvoiceItems(new UUID[]{thatBundleId, thisBundleId})));
final Clock clock = new ClockMock();
- final InvoiceUserApi invoiceApi = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceUserApi.class);
- final EntitlementUserApi entitlementApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- ((ZombieControl) invoiceApi).addResult("getUnpaidInvoicesByAccountId", invoices);
-
+ final InvoiceUserApi invoiceApi = Mockito.mock(InvoiceUserApi.class);
+ final EntitlementUserApi entitlementApi = Mockito.mock(EntitlementUserApi.class);
+ Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<DateTime>any())).thenReturn(Collections2.filter(invoices, new Predicate<Invoice>() {
+ @Override
+ public boolean apply(@Nullable final Invoice invoice) {
+ return invoice != null && BigDecimal.ZERO.compareTo(invoice.getBalance()) < 0;
+ }
+ }));
final BillingStateCalculatorBundle calc = new BillingStateCalculatorBundle(entitlementApi, invoiceApi, clock);
final SortedSet<Invoice> resultinvoices = calc.unpaidInvoicesForBundle(thisBundleId, new UUID(0L, 0L));
- Assert.assertEquals(resultinvoices.size(), 4);
- Assert.assertEquals(BigDecimal.ZERO.compareTo(resultinvoices.first().getBalance()), 0);
+ Assert.assertEquals(resultinvoices.size(), 3);
+ Assert.assertEquals(new BigDecimal("100.0").compareTo(resultinvoices.first().getBalance()), 0);
Assert.assertEquals(new BigDecimal("10000.0").compareTo(resultinvoices.last().getBalance()), 0);
-
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testcalculateBillingStateForBundle() throws Exception {
-
final UUID thisBundleId = new UUID(0L, 0L);
final UUID thatBundleId = new UUID(0L, 1L);
@@ -99,24 +101,23 @@ public class TestBillingStateCalculatorBundle extends TestBillingStateCalculator
invoices.add(createInvoice(now.minusDays(2), new BigDecimal("1000.00"), createInvoiceItems(new UUID[]{thisBundleId})));
invoices.add(createInvoice(now.minusDays(1), new BigDecimal("10000.00"), createInvoiceItems(new UUID[]{thatBundleId, thisBundleId})));
-
final Clock clock = new ClockMock();
- final InvoiceUserApi invoiceApi = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceUserApi.class);
- ((ZombieControl) invoiceApi).addResult("getUnpaidInvoicesByAccountId", invoices);
+ final InvoiceUserApi invoiceApi = Mockito.mock(InvoiceUserApi.class);
+ Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<DateTime>any())).thenReturn(invoices);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", thisBundleId);
- ((ZombieControl) bundle).addResult("getAccountId", UUID.randomUUID());
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(thisBundleId);
+ Mockito.when(bundle.getAccountId()).thenReturn(UUID.randomUUID());
- final EntitlementUserApi entitlementApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) entitlementApi).addResult("getBaseSubscription", subscription);
+ final EntitlementUserApi entitlementApi = Mockito.mock(EntitlementUserApi.class);
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(entitlementApi.getBaseSubscription(Mockito.<UUID>any())).thenReturn(subscription);
final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
final PriceList pricelist = new MockPriceList();
- ((ZombieControl) subscription).addResult("getCurrentPlan", plan);
- ((ZombieControl) subscription).addResult("getCurrentPriceList", pricelist);
- ((ZombieControl) subscription).addResult("getCurrentPhase", plan.getFinalPhase());
+ Mockito.when(subscription.getCurrentPlan()).thenReturn(plan);
+ Mockito.when(subscription.getCurrentPriceList()).thenReturn(pricelist);
+ Mockito.when(subscription.getCurrentPhase()).thenReturn(plan.getFinalPhase());
final BillingStateCalculatorBundle calc = new BillingStateCalculatorBundle(entitlementApi, invoiceApi, clock);
@@ -134,33 +135,30 @@ public class TestBillingStateCalculatorBundle extends TestBillingStateCalculator
}
-
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testcalculateBillingStateForBundleNoOverdueInvoices() throws Exception {
-
final UUID thisBundleId = new UUID(0L, 0L);
- final UUID thatBundleId = new UUID(0L, 1L);
now = new DateTime();
final List<Invoice> invoices = new ArrayList<Invoice>(5);
final Clock clock = new ClockMock();
- final InvoiceUserApi invoiceApi = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceUserApi.class);
- ((ZombieControl) invoiceApi).addResult("getUnpaidInvoicesByAccountId", invoices);
+ final InvoiceUserApi invoiceApi = Mockito.mock(InvoiceUserApi.class);
+ Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<DateTime>any())).thenReturn(invoices);
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
- ((ZombieControl) bundle).addResult("getId", thisBundleId);
- ((ZombieControl) bundle).addResult("getAccountId", UUID.randomUUID());
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
+ Mockito.when(bundle.getId()).thenReturn(thisBundleId);
+ Mockito.when(bundle.getAccountId()).thenReturn(UUID.randomUUID());
- final EntitlementUserApi entitlementApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) entitlementApi).addResult("getBaseSubscription", subscription);
+ final EntitlementUserApi entitlementApi = Mockito.mock(EntitlementUserApi.class);
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ Mockito.when(entitlementApi.getBaseSubscription(Mockito.<UUID>any())).thenReturn(subscription);
final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
final PriceList pricelist = new MockPriceList();
- ((ZombieControl) subscription).addResult("getCurrentPlan", plan);
- ((ZombieControl) subscription).addResult("getCurrentPriceList", pricelist);
- ((ZombieControl) subscription).addResult("getCurrentPhase", plan.getFinalPhase());
+ Mockito.when(subscription.getCurrentPlan()).thenReturn(plan);
+ Mockito.when(subscription.getCurrentPriceList()).thenReturn(pricelist);
+ Mockito.when(subscription.getCurrentPhase()).thenReturn(plan.getFinalPhase());
final BillingStateCalculatorBundle calc = new BillingStateCalculatorBundle(entitlementApi, invoiceApi, clock);
@@ -181,6 +179,4 @@ public class TestBillingStateCalculatorBundle extends TestBillingStateCalculator
public void testCorrectBehaviorForNoOverdueConfig() {
//TODO with no overdue config the system should be fine - take no action but see no NPEs
}
-
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/config/CreateOverdueConfigSchema.java b/overdue/src/test/java/com/ning/billing/overdue/config/CreateOverdueConfigSchema.java
index b801a2d..61e2fbe 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/config/CreateOverdueConfigSchema.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/config/CreateOverdueConfigSchema.java
@@ -23,10 +23,6 @@ import java.io.Writer;
import com.ning.billing.util.config.XMLSchemaGenerator;
public class CreateOverdueConfigSchema {
-
- /**
- * @param args
- */
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: <filepath>");
@@ -37,7 +33,5 @@ public class CreateOverdueConfigSchema {
final Writer w = new FileWriter(f);
w.write(XMLSchemaGenerator.xmlSchemaAsString(OverdueConfig.class));
w.close();
-
}
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/config/io/TestReadConfig.java b/overdue/src/test/java/com/ning/billing/overdue/config/io/TestReadConfig.java
index 75b3239..bc65015 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/config/io/TestReadConfig.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/config/io/TestReadConfig.java
@@ -19,13 +19,13 @@ package com.ning.billing.overdue.config.io;
import org.testng.annotations.Test;
import com.google.common.io.Resources;
+import com.ning.billing.overdue.OverdueTestSuite;
import com.ning.billing.overdue.config.OverdueConfig;
import com.ning.billing.util.config.XMLLoader;
-public class TestReadConfig {
- @Test(enabled = true)
+public class TestReadConfig extends OverdueTestSuite {
+ @Test(groups = "fast")
public void testConfigLoad() throws Exception {
XMLLoader.getObjectFromString(Resources.getResource("OverdueConfig.xml").toExternalForm(), OverdueConfig.class);
}
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/config/TestCondition.java b/overdue/src/test/java/com/ning/billing/overdue/config/TestCondition.java
index 508dcb4..dad1a9e 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/config/TestCondition.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/config/TestCondition.java
@@ -27,6 +27,7 @@ import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.junction.api.Blockable;
+import com.ning.billing.overdue.OverdueTestSuite;
import com.ning.billing.overdue.config.api.BillingState;
import com.ning.billing.overdue.config.api.PaymentResponse;
import com.ning.billing.util.config.XMLLoader;
@@ -35,12 +36,11 @@ import com.ning.billing.util.tag.DefaultControlTag;
import com.ning.billing.util.tag.DescriptiveTag;
import com.ning.billing.util.tag.Tag;
-public class TestCondition {
-
+public class TestCondition extends OverdueTestSuite {
@XmlRootElement(name = "condition")
private static class MockCondition extends DefaultCondition<Blockable> {}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testNumberOfUnpaidInvoicesEqualsOrExceeds() throws Exception {
final String xml =
"<condition>" +
@@ -59,7 +59,7 @@ public class TestCondition {
Assert.assertTrue(c.evaluate(state2, new DateTime()));
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testTotalUnpaidInvoiceBalanceEqualsOrExceeds() throws Exception {
final String xml =
"<condition>" +
@@ -78,8 +78,7 @@ public class TestCondition {
Assert.assertTrue(c.evaluate(state2, new DateTime()));
}
-
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testTimeSinceEarliestUnpaidInvoiceEqualsOrExceeds() throws Exception {
final String xml =
"<condition>" +
@@ -100,7 +99,7 @@ public class TestCondition {
Assert.assertTrue(c.evaluate(state2, now));
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testResponseForLastFailedPaymentIn() throws Exception {
final String xml =
"<condition>" +
@@ -121,7 +120,7 @@ public class TestCondition {
Assert.assertTrue(c.evaluate(state2, now));
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "fast")
public void testHasControlTag() throws Exception {
final String xml =
"<condition>" +
@@ -136,15 +135,13 @@ public class TestCondition {
final BillingState<Blockable> state0 = new BillingState<Blockable>(new UUID(0L, 1L), 0, BigDecimal.ZERO, null, unpaidInvoiceId, PaymentResponse.LOST_OR_STOLEN_CARD, new Tag[]{new DefaultControlTag(ControlTagType.AUTO_INVOICING_OFF), new DescriptiveTag("Tag")});
final BillingState<Blockable> state1 = new BillingState<Blockable>(new UUID(0L, 1L), 1, new BigDecimal("100.00"), now.minusDays(10), unpaidInvoiceId, PaymentResponse.INSUFFICIENT_FUNDS, new Tag[]{new DefaultControlTag(ControlTagType.OVERDUE_ENFORCEMENT_OFF)});
final BillingState<Blockable> state2 = new BillingState<Blockable>(new UUID(0L, 1L), 1, new BigDecimal("200.00"), now.minusDays(20), unpaidInvoiceId,
- PaymentResponse.DO_NOT_HONOR,
- new Tag[]{new DefaultControlTag(ControlTagType.OVERDUE_ENFORCEMENT_OFF),
- new DefaultControlTag(ControlTagType.AUTO_INVOICING_OFF),
- new DescriptiveTag("Tag")});
+ PaymentResponse.DO_NOT_HONOR,
+ new Tag[]{new DefaultControlTag(ControlTagType.OVERDUE_ENFORCEMENT_OFF),
+ new DefaultControlTag(ControlTagType.AUTO_INVOICING_OFF),
+ new DescriptiveTag("Tag")});
Assert.assertTrue(!c.evaluate(state0, now));
Assert.assertTrue(c.evaluate(state1, now));
Assert.assertTrue(c.evaluate(state2, now));
}
-
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/config/TestOverdueConfig.java b/overdue/src/test/java/com/ning/billing/overdue/config/TestOverdueConfig.java
index 58aabcf..2b2c264 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/config/TestOverdueConfig.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/config/TestOverdueConfig.java
@@ -21,11 +21,11 @@ import java.io.InputStream;
import org.testng.annotations.Test;
+import com.ning.billing.overdue.OverdueTestSuite;
import com.ning.billing.util.config.XMLLoader;
-public class TestOverdueConfig {
-
- @Test
+public class TestOverdueConfig extends OverdueTestSuite {
+ @Test(groups = "fast")
public void testParseConfig() throws Exception {
final String xml = "<overdueConfig>" +
" <bundleOverdueStates>" +
@@ -59,7 +59,5 @@ public class TestOverdueConfig {
"</overdueConfig>";
final InputStream is = new ByteArrayInputStream(xml.getBytes());
final OverdueConfig c = XMLLoader.getObjectFromStreamNoValidation(is, OverdueConfig.class);
-
}
-
}
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 a098a25..5965e02 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
@@ -22,6 +22,7 @@ import java.util.UUID;
import java.util.concurrent.Callable;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import org.testng.Assert;
@@ -32,6 +33,7 @@ import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.catalog.DefaultCatalogService;
import com.ning.billing.catalog.api.CatalogService;
import com.ning.billing.config.CatalogConfig;
@@ -39,11 +41,10 @@ import com.ning.billing.config.InvoiceConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.entitlement.api.billing.ChargeThruApi;
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.junction.api.Blockable;
import com.ning.billing.lifecycle.KillbillService.ServiceException;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockInvoiceModule;
import com.ning.billing.mock.glue.MockJunctionModule;
import com.ning.billing.mock.glue.MockPaymentModule;
@@ -51,6 +52,7 @@ import com.ning.billing.ovedue.notification.DefaultOverdueCheckNotifier;
import com.ning.billing.ovedue.notification.DefaultOverdueCheckPoster;
import com.ning.billing.ovedue.notification.OverdueCheckPoster;
import com.ning.billing.overdue.OverdueProperties;
+import com.ning.billing.overdue.OverdueTestSuiteWithEmbeddedDB;
import com.ning.billing.overdue.glue.DefaultOverdueModule;
import com.ning.billing.overdue.listener.OverdueListener;
import com.ning.billing.util.bus.Bus;
@@ -73,12 +75,11 @@ import com.ning.billing.util.tag.dao.TagDao;
import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.MINUTES;
-public class TestOverdueCheckNotifier {
+public class TestOverdueCheckNotifier extends OverdueTestSuiteWithEmbeddedDB {
private Clock clock;
private DefaultOverdueCheckNotifier notifier;
private Bus eventBus;
- private MysqlTestingHelper helper;
private OverdueListenerMock listener;
private NotificationQueueService notificationQueueService;
@@ -103,15 +104,11 @@ public class TestOverdueCheckNotifier {
public UUID getLatestSubscriptionId() {
return latestSubscriptionId;
}
-
}
-
- @BeforeClass(groups = {"slow"})
- public void setup() throws ServiceException, IOException, ClassNotFoundException, SQLException {
- //TestApiBase.loadSystemPropertiesFromClasspath("/entitlement.properties");
+ @BeforeClass(groups = "slow")
+ public void setup() throws ServiceException, IOException, ClassNotFoundException, SQLException, EntitlementUserApiException {
final Injector g = Guice.createInjector(Stage.PRODUCTION, new MockInvoiceModule(), new MockPaymentModule(), new BusModule(), new DefaultOverdueModule() {
-
protected void configure() {
super.configure();
bind(Clock.class).to(ClockMock.class).asEagerSingleton();
@@ -122,68 +119,52 @@ public class TestOverdueCheckNotifier {
final CatalogConfig catalogConfig = new ConfigurationObjectFactory(System.getProperties()).build(CatalogConfig.class);
bind(CatalogConfig.class).toInstance(catalogConfig);
bind(CatalogService.class).to(DefaultCatalogService.class).asEagerSingleton();
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
bind(TagDao.class).to(AuditedTagDao.class).asEagerSingleton();
bind(CustomFieldDao.class).to(AuditedCustomFieldDao.class).asEagerSingleton();
bind(GlobalLocker.class).to(MySqlGlobalLocker.class).asEagerSingleton();
- bind(ChargeThruApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class));
+ bind(ChargeThruApi.class).toInstance(Mockito.mock(ChargeThruApi.class));
install(new MockJunctionModule());
}
});
clock = g.getInstance(Clock.class);
- final IDBI dbi = g.getInstance(IDBI.class);
eventBus = g.getInstance(Bus.class);
- helper = g.getInstance(MysqlTestingHelper.class);
notificationQueueService = g.getInstance(NotificationQueueService.class);
final OverdueProperties properties = g.getInstance(OverdueProperties.class);
- final Subscription subscription = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- final EntitlementUserApi entitlementUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
- ((ZombieControl) entitlementUserApi).addResult("getSubscriptionFromId", subscription);
+ final Subscription subscription = Mockito.mock(Subscription.class);
+ final EntitlementUserApi entitlementUserApi = Mockito.mock(EntitlementUserApi.class);
+ Mockito.when(entitlementUserApi.getSubscriptionFromId(Mockito.<UUID>any())).thenReturn(subscription);
-// CallContextFactory factory = new DefaultCallContextFactory(clock);
listener = new OverdueListenerMock();
notifier = new DefaultOverdueCheckNotifier(notificationQueueService,
properties, listener);
- startMysql();
eventBus.start();
notifier.initialize();
notifier.start();
}
- private void startMysql() throws IOException, ClassNotFoundException, SQLException {
- final String ddl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- final String testDdl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
-
- helper.startMysql();
- helper.initDb(ddl);
- helper.initDb(testDdl);
- }
-
- @Test(enabled = true, groups = "slow")
+ @Test(groups = "slow")
public void test() throws Exception {
final UUID subscriptionId = new UUID(0L, 1L);
- final Blockable blockable = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) blockable).addResult("getId", subscriptionId);
+ final Blockable blockable = Mockito.mock(Subscription.class);
+ Mockito.when(blockable.getId()).thenReturn(subscriptionId);
final DateTime now = new DateTime();
final DateTime readyTime = now.plusMillis(2000);
final OverdueCheckPoster poster = new DefaultOverdueCheckPoster(notificationQueueService);
-
poster.insertOverdueCheckNotification(blockable, readyTime);
-
// Move time in the future after the notification effectiveDate
((ClockMock) clock).setDeltaFromReality(3000);
-
await().atMost(1, MINUTES).until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
@@ -193,14 +174,11 @@ public class TestOverdueCheckNotifier {
Assert.assertEquals(listener.getEventCount(), 1);
Assert.assertEquals(listener.getLatestSubscriptionId(), subscriptionId);
-
}
@AfterClass(groups = "slow")
public void tearDown() {
eventBus.stop();
notifier.stop();
- helper.stopMysql();
}
-
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/OverdueTestBase.java b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestBase.java
index f68ce0a..9a01428 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/OverdueTestBase.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestBase.java
@@ -16,13 +16,13 @@
package com.ning.billing.overdue;
-import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@@ -33,10 +33,9 @@ import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
import com.ning.billing.catalog.MockPlan;
import com.ning.billing.catalog.MockPriceList;
-import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.glue.CatalogModule;
-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.invoice.api.Invoice;
@@ -44,28 +43,24 @@ import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceUserApi;
import com.ning.billing.junction.api.BlockingApi;
import com.ning.billing.junction.api.BlockingState;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.mock.glue.MockInvoiceModule;
import com.ning.billing.mock.glue.MockPaymentModule;
import com.ning.billing.mock.glue.TestDbiModule;
import com.ning.billing.overdue.applicator.ApplicatorMockJunctionModule;
import com.ning.billing.overdue.applicator.ApplicatorMockJunctionModule.ApplicatorBlockingApi;
-import com.ning.billing.overdue.applicator.TestOverdueStateApplicator;
+import com.ning.billing.overdue.applicator.OverdueListenerTesterModule;
import com.ning.billing.overdue.config.OverdueConfig;
import com.ning.billing.overdue.glue.DefaultOverdueModule;
import com.ning.billing.overdue.service.DefaultOverdueService;
import com.ning.billing.overdue.wrapper.OverdueWrapperFactory;
import com.ning.billing.util.bus.BusService;
import com.ning.billing.util.clock.ClockMock;
-import com.ning.billing.util.glue.BusModule;
import com.ning.billing.util.glue.NotificationQueueModule;
-import com.ning.billing.util.io.IOUtils;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueAlreadyExists;
-@Guice(modules = {DefaultOverdueModule.class, MockClockModule.class, ApplicatorMockJunctionModule.class, CatalogModule.class, MockInvoiceModule.class, MockPaymentModule.class, BusModule.class, NotificationQueueModule.class, TestDbiModule.class})
-public class OverdueTestBase {
+@Guice(modules = {DefaultOverdueModule.class, OverdueListenerTesterModule.class, MockClockModule.class, ApplicatorMockJunctionModule.class, CatalogModule.class, MockInvoiceModule.class, MockPaymentModule.class, NotificationQueueModule.class, TestDbiModule.class})
+public abstract class OverdueTestBase extends OverdueTestSuiteWithEmbeddedDB {
protected final String configXml =
"<overdueConfig>" +
" <bundleOverdueStates>" +
@@ -124,36 +119,23 @@ public class OverdueTestBase {
@Inject
protected OverdueUserApi overdueApi;
-
@Inject
protected InvoiceUserApi invoiceApi;
protected Account account;
protected SubscriptionBundle bundle;
- protected String productName;
- protected BillingPeriod term;
- protected String planSetName;
@Inject
EntitlementUserApi entitlementApi;
@Inject
protected DefaultOverdueService service;
+
@Inject
protected BusService busService;
- @Inject
- protected MysqlTestingHelper helper;
-
- protected void setupMySQL() throws IOException {
- final String utilDdl = IOUtils.toString(TestOverdueStateApplicator.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- helper.startMysql();
- helper.initDb(utilDdl);
- }
@BeforeClass(groups = "slow")
public void setup() throws Exception {
-
- setupMySQL();
service.registerForBus();
try {
service.initialize();
@@ -167,21 +149,14 @@ public class OverdueTestBase {
@AfterClass(groups = "slow")
public void tearDown() throws Exception {
- helper.stopMysql();
service.stop();
}
-
@BeforeMethod(groups = "slow")
public void setupTest() throws Exception {
-
- // Pre test cleanup
- helper.cleanupAllTables();
clock.resetDeltaFromReality();
-
}
-
protected void checkStateApplied(final OverdueState<SubscriptionBundle> state) {
final BlockingState result = ((ApplicatorBlockingApi) blockingApi).getBlockingState();
checkStateApplied(result, state);
@@ -194,36 +169,33 @@ public class OverdueTestBase {
Assert.assertEquals(result.isBlockBilling(), state.disableEntitlementAndChangesBlocked());
}
-
- protected SubscriptionBundle createBundle(final DateTime dateOfLastUnPaidInvoice) {
- final SubscriptionBundle bundle = BrainDeadProxyFactory.createBrainDeadProxyFor(SubscriptionBundle.class);
+ protected SubscriptionBundle createBundle(final DateTime dateOfLastUnPaidInvoice) throws EntitlementUserApiException {
+ final SubscriptionBundle bundle = Mockito.mock(SubscriptionBundle.class);
final UUID bundleId = UUID.randomUUID();
- ((ZombieControl) bundle).addResult("getId", bundleId);
- ((ZombieControl) bundle).addResult("getAccountId", UUID.randomUUID());
+ Mockito.when(bundle.getId()).thenReturn(bundleId);
+ Mockito.when(bundle.getAccountId()).thenReturn(UUID.randomUUID());
- final Invoice invoice = BrainDeadProxyFactory.createBrainDeadProxyFor(Invoice.class);
- ((ZombieControl) invoice).addResult("getInvoiceDate", dateOfLastUnPaidInvoice);
- ((ZombieControl) invoice).addResult("getBalance", BigDecimal.TEN);
- ((ZombieControl) invoice).addResult("getId", UUID.randomUUID());
- ((ZombieControl) invoice).addResult("hashCode", UUID.randomUUID().hashCode());
+ final Invoice invoice = Mockito.mock(Invoice.class);
+ Mockito.when(invoice.getInvoiceDate()).thenReturn(dateOfLastUnPaidInvoice);
+ Mockito.when(invoice.getBalance()).thenReturn(BigDecimal.TEN);
+ Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());
- final InvoiceItem item = BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceItem.class);
- ((ZombieControl) item).addResult("getBundleId", bundleId);
+ final InvoiceItem item = Mockito.mock(InvoiceItem.class);
+ Mockito.when(item.getBundleId()).thenReturn(bundleId);
final List<InvoiceItem> items = new ArrayList<InvoiceItem>();
items.add(item);
- ((ZombieControl) invoice).addResult("getInvoiceItems", items);
+ Mockito.when(invoice.getInvoiceItems()).thenReturn(items);
final List<Invoice> invoices = new ArrayList<Invoice>();
invoices.add(invoice);
- ((ZombieControl) invoiceApi).addResult("getUnpaidInvoicesByAccountId", invoices);
-
+ Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<DateTime>any())).thenReturn(invoices);
- final Subscription base = BrainDeadProxyFactory.createBrainDeadProxyFor(Subscription.class);
- ((ZombieControl) base).addResult("getCurrentPlan", MockPlan.createBicycleNoTrialEvergreen1USD());
- ((ZombieControl) base).addResult("getCurrentPriceList", new MockPriceList());
- ((ZombieControl) base).addResult("getCurrentPhase", MockPlan.createBicycleNoTrialEvergreen1USD().getFinalPhase());
- ((ZombieControl) entitlementApi).addResult("getBaseSubscription", base);
+ final Subscription base = Mockito.mock(Subscription.class);
+ Mockito.when(base.getCurrentPlan()).thenReturn(MockPlan.createBicycleNoTrialEvergreen1USD());
+ Mockito.when(base.getCurrentPriceList()).thenReturn(new MockPriceList());
+ Mockito.when(base.getCurrentPhase()).thenReturn(MockPlan.createBicycleNoTrialEvergreen1USD().getFinalPhase());
+ Mockito.when(entitlementApi.getBaseSubscription(Mockito.<UUID>any())).thenReturn(base);
return bundle;
}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuite.java b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuite.java
new file mode 100644
index 0000000..e0fb28c
--- /dev/null
+++ b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.overdue;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class OverdueTestSuite extends KillbillTestSuite {
+}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuiteWithEmbeddedDB.java b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..17380be
--- /dev/null
+++ b/overdue/src/test/java/com/ning/billing/overdue/OverdueTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.overdue;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class OverdueTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/overdue/src/test/java/com/ning/billing/overdue/wrapper/TestOverdueWrapper.java b/overdue/src/test/java/com/ning/billing/overdue/wrapper/TestOverdueWrapper.java
index 84e7467..108a420 100644
--- a/overdue/src/test/java/com/ning/billing/overdue/wrapper/TestOverdueWrapper.java
+++ b/overdue/src/test/java/com/ning/billing/overdue/wrapper/TestOverdueWrapper.java
@@ -30,7 +30,7 @@ import com.ning.billing.overdue.config.OverdueConfig;
import com.ning.billing.util.config.XMLLoader;
public class TestOverdueWrapper extends OverdueTestBase {
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "slow")
public void testWrapperBasic() throws Exception {
final InputStream is = new ByteArrayInputStream(configXml.getBytes());
config = XMLLoader.getObjectFromStreamNoValidation(is, OverdueConfig.class);
@@ -46,7 +46,6 @@ public class TestOverdueWrapper extends OverdueTestBase {
wrapper.refresh();
checkStateApplied(state);
-
state = config.getBundleStateSet().findState("OD2");
bundle = createBundle(clock.getUTCNow().minusDays(41));
wrapper = overdueWrapperFactory.createOverdueWrapperFor(bundle);
@@ -58,15 +57,12 @@ public class TestOverdueWrapper extends OverdueTestBase {
wrapper = overdueWrapperFactory.createOverdueWrapperFor(bundle);
wrapper.refresh();
checkStateApplied(state);
-
}
- @Test(groups = {"fast"}, enabled = true)
+ @Test(groups = "slow")
public void testWrapperNoConfig() throws Exception {
-
overdueWrapperFactory.setOverdueConfig(null);
-
final SubscriptionBundle bundle;
final OverdueWrapper<SubscriptionBundle> wrapper;
final OverdueState<SubscriptionBundle> state;
@@ -78,10 +74,8 @@ public class TestOverdueWrapper extends OverdueTestBase {
wrapper = overdueWrapperFactory.createOverdueWrapperFor(bundle);
final OverdueState<SubscriptionBundle> result = wrapper.refresh();
-
Assert.assertEquals(result.getName(), state.getName());
Assert.assertEquals(result.blockChanges(), state.blockChanges());
Assert.assertEquals(result.disableEntitlementAndChangesBlocked(), state.disableEntitlementAndChangesBlocked());
-
}
}
payment/pom.xml 7(+6 -1)
diff --git a/payment/pom.xml b/payment/pom.xml
index c3a5544..8c0deb3 100644
--- a/payment/pom.xml
+++ b/payment/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-payment</artifactId>
@@ -77,6 +77,11 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
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 ad55ff9..4968a24 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
@@ -78,13 +78,34 @@ public class DefaultPaymentApi implements PaymentApi {
}
+
+ @Override
+ public Refund getRefund(UUID refundId) throws PaymentApiException {
+ return refundProcessor.getRefund(refundId);
+ }
+
@Override
- public Refund createRefund(final Account account, final UUID paymentId, final CallContext context)
+ public Refund createRefund(Account account, UUID paymentId,
+ BigDecimal refundAmount, boolean isAdjusted, CallContext context)
throws PaymentApiException {
- return refundProcessor.createRefund(account, paymentId, context);
+ return refundProcessor.createRefund(account, paymentId, refundAmount, isAdjusted, context);
+
}
@Override
+ public List<Refund> getAccountRefunds(Account account)
+ throws PaymentApiException {
+ return refundProcessor.getAccountRefunds(account);
+ }
+
+ @Override
+ public List<Refund> getPaymentRefunds(UUID paymentId)
+ throws PaymentApiException {
+ return refundProcessor.getPaymentRefunds(paymentId);
+ }
+
+
+ @Override
public Set<String> getAvailablePlugins() {
return methodProcessor.getAvailablePlugins();
}
@@ -118,6 +139,7 @@ public class DefaultPaymentApi implements PaymentApi {
return methodProcessor.getPaymentMethods(account, withPluginDetail);
}
+ @Override
public PaymentMethod getPaymentMethodById(final UUID paymentMethodId)
throws PaymentApiException {
return methodProcessor.getPaymentMethodById(paymentMethodId);
diff --git a/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentInfoEvent.java b/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentInfoEvent.java
index a34f71e..c40707c 100644
--- a/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentInfoEvent.java
+++ b/payment/src/main/java/com/ning/billing/payment/api/DefaultPaymentInfoEvent.java
@@ -36,6 +36,7 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
private final PaymentStatus status;
private final UUID userToken;
private final DateTime effectiveDate;
+ private final String extPaymentRefId;
@JsonCreator
public DefaultPaymentInfoEvent(@JsonProperty("id") final UUID id,
@@ -45,6 +46,7 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
@JsonProperty("amount") final BigDecimal amount,
@JsonProperty("paymentNumber") final Integer paymentNumber,
@JsonProperty("status") final PaymentStatus status,
+ @JsonProperty("extPaymentRefId") final String extPaymentRefId,
@JsonProperty("userToken") final UUID userToken,
@JsonProperty("effectiveDate") final DateTime effectiveDate) {
super(id);
@@ -54,6 +56,7 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
this.amount = amount;
this.paymentNumber = paymentNumber;
this.status = status;
+ this.extPaymentRefId = extPaymentRefId;
this.userToken = userToken;
this.effectiveDate = effectiveDate;
}
@@ -61,8 +64,8 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
public DefaultPaymentInfoEvent(final UUID accountId, final UUID invoiceId,
final UUID paymentId, final BigDecimal amount, final Integer paymentNumber,
- final PaymentStatus status, final UUID userToken, final DateTime effectiveDate) {
- this(UUID.randomUUID(), accountId, invoiceId, paymentId, amount, paymentNumber, status, userToken, effectiveDate);
+ final PaymentStatus status, final String extPaymentRefId, final UUID userToken, final DateTime effectiveDate) {
+ this(UUID.randomUUID(), accountId, invoiceId, paymentId, amount, paymentNumber, status, extPaymentRefId, userToken, effectiveDate);
}
public DefaultPaymentInfoEvent(final DefaultPaymentInfoEvent src) {
@@ -73,6 +76,7 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
src.amount,
src.paymentNumber,
src.status,
+ src.extPaymentRefId,
src.userToken,
src.effectiveDate);
}
@@ -132,6 +136,27 @@ public class DefaultPaymentInfoEvent extends EntityBase implements PaymentInfoEv
return status;
}
+ @Override
+ public String getExtPaymentRefId() {
+ return extPaymentRefId;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("DefaultPaymentInfoEvent");
+ sb.append("{accountId=").append(accountId);
+ sb.append(", invoiceId=").append(invoiceId);
+ sb.append(", paymentId=").append(paymentId);
+ sb.append(", amount=").append(amount);
+ sb.append(", paymentNumber=").append(paymentNumber);
+ sb.append(", status=").append(status);
+ sb.append(", userToken=").append(userToken);
+ sb.append(", effectiveDate=").append(effectiveDate);
+ sb.append(", extPaymentRefId='").append(extPaymentRefId).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
@Override
public int hashCode() {
diff --git a/payment/src/main/java/com/ning/billing/payment/api/DefaultRefund.java b/payment/src/main/java/com/ning/billing/payment/api/DefaultRefund.java
new file mode 100644
index 0000000..729e701
--- /dev/null
+++ b/payment/src/main/java/com/ning/billing/payment/api/DefaultRefund.java
@@ -0,0 +1,59 @@
+/*
+ * 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.payment.api;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.util.entity.EntityBase;
+
+public class DefaultRefund extends EntityBase implements Refund {
+
+ private final UUID paymentId;
+ private final BigDecimal amount;
+ private final Currency currency;
+ private final boolean isAdjusted;
+
+ public DefaultRefund(final UUID id, final UUID paymentId, final BigDecimal amount,
+ final Currency currency, final boolean isAdjusted) {
+ super(id);
+ this.paymentId = paymentId;
+ this.amount = amount;
+ this.currency = currency;
+ this.isAdjusted = isAdjusted;
+ }
+
+ @Override
+ public UUID getPaymentId() {
+ return paymentId;
+ }
+
+ @Override
+ public BigDecimal getRefundAmount() {
+ return amount;
+ }
+
+ @Override
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ @Override
+ public boolean isAdjusted() {
+ return isAdjusted;
+ }
+}
diff --git a/payment/src/main/java/com/ning/billing/payment/bus/InvoiceHandler.java b/payment/src/main/java/com/ning/billing/payment/bus/InvoiceHandler.java
index e94b175..527a776 100644
--- a/payment/src/main/java/com/ning/billing/payment/bus/InvoiceHandler.java
+++ b/payment/src/main/java/com/ning/billing/payment/bus/InvoiceHandler.java
@@ -16,8 +16,6 @@
package com.ning.billing.payment.bus;
-import java.util.Map;
-import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,24 +35,15 @@ 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 com.ning.billing.util.dao.ObjectType;
-import com.ning.billing.util.tag.ControlTagType;
-import com.ning.billing.util.tag.Tag;
+
public class InvoiceHandler {
public static final String PAYMENT_PROVIDER_KEY = "paymentProvider";
- /*
- private final static int NB_PAYMENT_THREADS = 3; // STEPH
- private final static String PAYMENT_GROUP_NAME = "payment-grp";
- private final static String PAYMENT_TH_NAME = "payment-th";
-*/
-
private final PaymentProcessor paymentProcessor;
private final AccountUserApi accountUserApi;
private final Clock clock;
- private final TagUserApi tagUserApi;
private static final Logger log = LoggerFactory.getLogger(InvoiceHandler.class);
@@ -66,7 +55,6 @@ public class InvoiceHandler {
final TagUserApi tagUserApi) {
this.clock = clock;
this.accountUserApi = accountUserApi;
- this.tagUserApi = tagUserApi;
this.paymentProcessor = paymentProcessor;
}
@@ -79,11 +67,9 @@ public class InvoiceHandler {
Account account = null;
try {
- account = accountUserApi.getAccountById(event.getAccountId());
- if (isAccountAutoPayOff(account.getId())) {
- return;
- }
+
final CallContext context = new DefaultCallContext("PaymentRequestProcessor", CallOrigin.INTERNAL, UserType.SYSTEM, event.getUserToken(), clock);
+ account = accountUserApi.getAccountById(event.getAccountId());
paymentProcessor.createPayment(account, event.getInvoiceId(), null, context, false);
} catch (AccountApiException e) {
log.error("Failed to process invoice payment", e);
@@ -93,16 +79,6 @@ public class InvoiceHandler {
}
}
}
-
- private boolean isAccountAutoPayOff(final UUID accountId) {
- final Map<String, Tag> accountTags = tagUserApi.getTags(accountId, ObjectType.ACCOUNT);
- for (final Tag cur : accountTags.values()) {
- if (cur.getTagDefinitionName().equals(ControlTagType.AUTO_PAY_OFF.toString())) {
- return true;
- }
- }
- return false;
- }
}
diff --git a/payment/src/main/java/com/ning/billing/payment/bus/TagHandler.java b/payment/src/main/java/com/ning/billing/payment/bus/TagHandler.java
index da66d06..53527ab 100644
--- a/payment/src/main/java/com/ning/billing/payment/bus/TagHandler.java
+++ b/payment/src/main/java/com/ning/billing/payment/bus/TagHandler.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -15,6 +15,63 @@
*/
package com.ning.billing.payment.bus;
+import java.util.UUID;
+
+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.payment.api.PaymentApiException;
+import com.ning.billing.payment.core.PaymentProcessor;
+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 com.ning.billing.util.dao.ObjectType;
+import com.ning.billing.util.tag.ControlTagType;
+import com.ning.billing.util.tag.api.ControlTagDeletionEvent;
+
public class TagHandler {
+ private static final Logger log = LoggerFactory.getLogger(TagHandler.class);
+
+ private final Clock clock;
+ private final AccountUserApi accountUserApi;
+ private final PaymentProcessor paymentProcessor;
+
+ @Inject
+ public TagHandler(final Clock clock,
+ final AccountUserApi accountUserApi,
+ final PaymentProcessor paymentProcessor) {
+ this.clock = clock;
+ this.accountUserApi = accountUserApi;
+ this.paymentProcessor = paymentProcessor;
+ }
+
+ @Subscribe
+ public void process_AUTO_PAY_OFF_removal(final ControlTagDeletionEvent event) {
+ if (event.getTagDefinition().getName().equals(ControlTagType.AUTO_PAY_OFF.toString()) && event.getObjectType() == ObjectType.ACCOUNT) {
+ final UUID accountId = event.getObjectId();
+ processUnpaid_AUTO_PAY_OFF_payments(accountId, event.getUserToken());
+ }
+ }
+
+ private void processUnpaid_AUTO_PAY_OFF_payments(final UUID accountId, final UUID userToken) {
+ try {
+ final CallContext context = new DefaultCallContext("PaymentRequestProcessor", CallOrigin.INTERNAL, UserType.SYSTEM, userToken, clock);
+ final Account account = accountUserApi.getAccountById(accountId);
+
+ paymentProcessor.process_AUTO_PAY_OFF_removal(account, context);
+
+ } catch (AccountApiException e) {
+ log.warn(String.format("Failed to process process removal AUTO_PAY_OFF for account %s", accountId), e);
+ } catch (PaymentApiException e) {
+ log.warn(String.format("Failed to process process removal AUTO_PAY_OFF for account %s", accountId), e);
+ }
+ }
}
diff --git a/payment/src/main/java/com/ning/billing/payment/core/PaymentProcessor.java b/payment/src/main/java/com/ning/billing/payment/core/PaymentProcessor.java
index 20e30b5..0167a71 100644
--- a/payment/src/main/java/com/ning/billing/payment/core/PaymentProcessor.java
+++ b/payment/src/main/java/com/ning/billing/payment/core/PaymentProcessor.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -18,9 +18,11 @@ package com.ning.billing.payment.core;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.math.RoundingMode;
+import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
@@ -46,13 +48,16 @@ import com.ning.billing.payment.api.PaymentStatus;
import com.ning.billing.payment.dao.PaymentAttemptModelDao;
import com.ning.billing.payment.dao.PaymentDao;
import com.ning.billing.payment.dao.PaymentModelDao;
+import com.ning.billing.payment.dao.PaymentSqlDao;
import com.ning.billing.payment.dispatcher.PluginDispatcher;
import com.ning.billing.payment.plugin.api.PaymentInfoPlugin;
import com.ning.billing.payment.plugin.api.PaymentPluginApi;
import com.ning.billing.payment.plugin.api.PaymentPluginApiException;
import com.ning.billing.payment.provider.PaymentProviderPluginRegistry;
+import com.ning.billing.payment.retry.AutoPayRetryService.AutoPayRetryServiceScheduler;
import com.ning.billing.payment.retry.FailedPaymentRetryService.FailedPaymentRetryServiceScheduler;
import com.ning.billing.payment.retry.PluginFailureRetryService.PluginFailureRetryServiceScheduler;
+import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.callcontext.CallContext;
@@ -60,15 +65,21 @@ import com.ning.billing.util.callcontext.CallContextFactory;
import com.ning.billing.util.callcontext.CallOrigin;
import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.clock.Clock;
+import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.globallocker.GlobalLocker;
+import com.ning.billing.util.tag.ControlTagType;
+import com.ning.billing.util.tag.Tag;
import static com.ning.billing.payment.glue.PaymentModule.PLUGIN_EXECUTOR_NAMED;
public class PaymentProcessor extends ProcessorBase {
private final InvoicePaymentApi invoicePaymentApi;
+ private final TagUserApi tagUserApi;
private final FailedPaymentRetryServiceScheduler failedPaymentRetryService;
private final PluginFailureRetryServiceScheduler pluginFailureRetryService;
+ private final AutoPayRetryServiceScheduler autoPayoffRetryService;
+
private final CallContextFactory factory;
private final Clock clock;
@@ -81,8 +92,10 @@ public class PaymentProcessor extends ProcessorBase {
public PaymentProcessor(final PaymentProviderPluginRegistry pluginRegistry,
final AccountUserApi accountUserApi,
final InvoicePaymentApi invoicePaymentApi,
+ final TagUserApi tagUserApi,
final FailedPaymentRetryServiceScheduler failedPaymentRetryService,
final PluginFailureRetryServiceScheduler pluginFailureRetryService,
+ final AutoPayRetryServiceScheduler autoPayoffRetryService,
final PaymentDao paymentDao,
final Bus eventBus,
final Clock clock,
@@ -91,8 +104,10 @@ public class PaymentProcessor extends ProcessorBase {
final CallContextFactory factory) {
super(pluginRegistry, accountUserApi, eventBus, paymentDao, locker, executor);
this.invoicePaymentApi = invoicePaymentApi;
+ this.tagUserApi = tagUserApi;
this.failedPaymentRetryService = failedPaymentRetryService;
this.pluginFailureRetryService = pluginFailureRetryService;
+ this.autoPayoffRetryService = autoPayoffRetryService;
this.clock = clock;
this.factory = factory;
this.paymentPluginDispatcher = new PluginDispatcher<Payment>(executor);
@@ -130,6 +145,53 @@ public class PaymentProcessor extends ProcessorBase {
return result;
}
+ public void process_AUTO_PAY_OFF_removal(final Account account, final CallContext context) throws PaymentApiException {
+
+ try {
+ voidPluginDispatcher.dispatchWithAccountLock(new CallableWithAccountLock<Void>(locker,
+ account.getExternalKey(),
+ new WithAccountLockCallback<Void>() {
+
+ @Override
+ public Void doOperation() throws PaymentApiException {
+
+ final List<PaymentModelDao> payments = paymentDao.getPaymentsForAccount(account.getId());
+ final Collection<PaymentModelDao> paymentsToBeCompleted = Collections2.filter(payments, new Predicate<PaymentModelDao>() {
+ @Override
+ public boolean apply(final PaymentModelDao in) {
+ // Payments left in AUTO_PAY_OFF or for which we did not retry enough
+ return (in.getPaymentStatus() == PaymentStatus.AUTO_PAY_OFF ||
+ in.getPaymentStatus() == PaymentStatus.PAYMENT_FAILURE ||
+ in.getPaymentStatus() == PaymentStatus.PLUGIN_FAILURE);
+ }
+ });
+ // Insert one retry event for each payment left in AUTO_PAY_OFF
+ for (PaymentModelDao cur : paymentsToBeCompleted) {
+ switch(cur.getPaymentStatus()) {
+ case AUTO_PAY_OFF:
+ autoPayoffRetryService.scheduleRetry(cur.getId(), clock.getUTCNow());
+ break;
+ case PAYMENT_FAILURE:
+ scheduleRetryOnPaymentFailure(cur.getId());
+ break;
+ case PLUGIN_FAILURE:
+ scheduleRetryOnPluginFailure(cur.getId());
+ break;
+ default:
+ // Impossible...
+ throw new RuntimeException("Unexpected case " + cur.getPaymentStatus());
+ }
+
+ }
+ return null;
+ }
+ }));
+ } catch (TimeoutException e) {
+ throw new PaymentApiException(ErrorCode.UNEXPECTED_ERROR, "Unexpected timeout for payment creation (AUTO_PAY_OFF)");
+ }
+ }
+
+
public Payment createPayment(final String accountKey, final UUID invoiceId, final BigDecimal inputAmount, final CallContext context, final boolean isInstantPayment)
throws PaymentApiException {
try {
@@ -142,7 +204,6 @@ public class PaymentProcessor extends ProcessorBase {
public Payment createPayment(final Account account, final UUID invoiceId, final BigDecimal inputAmount, final CallContext context, final boolean isInstantPayment)
throws PaymentApiException {
-
final PaymentPluginApi plugin = getPaymentProviderPlugin(account);
try {
@@ -152,6 +213,8 @@ public class PaymentProcessor extends ProcessorBase {
@Override
public Payment doOperation() throws PaymentApiException {
+
+
final Invoice invoice = invoicePaymentApi.getInvoice(invoiceId);
if (invoice.isMigrationInvoice()) {
@@ -160,7 +223,11 @@ public class PaymentProcessor extends ProcessorBase {
}
final BigDecimal requestedAmount = getAndValidatePaymentAmount(invoice, inputAmount, isInstantPayment);
- return processNewPaymentWithAccountLocked(plugin, account, invoice, requestedAmount, isInstantPayment, context);
+ if (isAccountAutoPayOff(account.getId())) {
+ return processNewPaymentForAutoPayOffWithAccountLocked(account, invoice, requestedAmount, context);
+ } else {
+ return processNewPaymentWithAccountLocked(plugin, account, invoice, requestedAmount, isInstantPayment, context);
+ }
}
}));
} catch (TimeoutException e) {
@@ -190,10 +257,15 @@ public class PaymentProcessor extends ProcessorBase {
throw new PaymentApiException(ErrorCode.PAYMENT_AMOUNT_DENIED,
invoice.getId(), inputAmount.floatValue(), invoice.getBalance().floatValue());
}
- return inputAmount != null ? inputAmount : invoice.getBalance();
+ BigDecimal result = inputAmount != null ? inputAmount : invoice.getBalance();
+ return result.setScale(2, RoundingMode.HALF_EVEN);
}
+ public void retryAutoPayOff(final UUID paymentId) {
+ retryFailedPaymentInternal(paymentId, PaymentStatus.AUTO_PAY_OFF);
+ }
+
public void retryPluginFailure(final UUID paymentId) {
retryFailedPaymentInternal(paymentId, PaymentStatus.PLUGIN_FAILURE, PaymentStatus.TIMEDOUT);
}
@@ -202,6 +274,17 @@ public class PaymentProcessor extends ProcessorBase {
retryFailedPaymentInternal(paymentId, PaymentStatus.PAYMENT_FAILURE);
}
+ private boolean isAccountAutoPayOff(final UUID accountId) {
+ final Map<String, Tag> accountTags = tagUserApi.getTags(accountId, ObjectType.ACCOUNT);
+ for (final Tag cur : accountTags.values()) {
+ if (cur.getTagDefinitionName().equals(ControlTagType.AUTO_PAY_OFF.toString())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
private void retryFailedPaymentInternal(final UUID paymentId, final PaymentStatus... expectedPaymentStates) {
try {
@@ -212,6 +295,11 @@ public class PaymentProcessor extends ProcessorBase {
return;
}
+ if (isAccountAutoPayOff(payment.getAccountId())) {
+ log.info(String.format("Skip retry payment %s in state %s because AUTO_PAY_OFF", payment.getId(), payment.getPaymentStatus()));
+ return;
+ }
+
final Account account = accountUserApi.getAccountById(payment.getAccountId());
final PaymentPluginApi plugin = getPaymentProviderPlugin(account);
final CallContext context = factory.createCallContext("PaymentRetry", CallOrigin.INTERNAL, UserType.SYSTEM);
@@ -223,7 +311,7 @@ public class PaymentProcessor extends ProcessorBase {
@Override
public Void doOperation() throws PaymentApiException {
- // Fetch gain with account lock this time
+ // Fetch again with account lock this time
final PaymentModelDao payment = paymentDao.getPayment(paymentId);
boolean foundExpectedState = false;
for (final PaymentStatus cur : expectedPaymentStates) {
@@ -260,22 +348,34 @@ public class PaymentProcessor extends ProcessorBase {
}
}
+ private Payment processNewPaymentForAutoPayOffWithAccountLocked(final Account account, final Invoice invoice, final BigDecimal requestedAmount, final CallContext context)
+ throws PaymentApiException {
+
+ final PaymentStatus paymentStatus = PaymentStatus.AUTO_PAY_OFF;
+
+ final PaymentModelDao paymentInfo = new PaymentModelDao(account.getId(), invoice.getId(), account.getPaymentMethodId(), requestedAmount, invoice.getCurrency(), invoice.getTargetDate(), paymentStatus);
+ final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), invoice.getId(), paymentInfo.getId(), paymentStatus, clock.getUTCNow(), requestedAmount);
+
+ paymentDao.insertPaymentWithAttempt(paymentInfo, attempt, context);
+ return new DefaultPayment(paymentInfo, Collections.singletonList(attempt));
+}
+
+
private Payment processNewPaymentWithAccountLocked(final PaymentPluginApi plugin, final Account account, final Invoice invoice,
- final BigDecimal requestedAmount, final boolean isInstantPayment, final CallContext context) throws PaymentApiException {
+ final BigDecimal requestedAmount, final boolean isInstantPayment, final CallContext context) throws PaymentApiException {
+
- final boolean scheduleRetryForPayment = !isInstantPayment;
- final PaymentModelDao payment = new PaymentModelDao(account.getId(), invoice.getId(), requestedAmount.setScale(2, RoundingMode.HALF_EVEN), invoice.getCurrency(), invoice.getTargetDate());
+ final PaymentModelDao payment = new PaymentModelDao(account.getId(), invoice.getId(), account.getPaymentMethodId(), requestedAmount.setScale(2, RoundingMode.HALF_EVEN), invoice.getCurrency(), invoice.getTargetDate());
final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), invoice.getId(), payment.getId(), clock.getUTCNow(), requestedAmount);
- final PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, scheduleRetryForPayment, context);
+ final PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, context);
return processPaymentWithAccountLocked(plugin, account, invoice, savedPayment, attempt, isInstantPayment, context);
}
private Payment processRetryPaymentWithAccountLocked(final PaymentPluginApi plugin, final Account account, final Invoice invoice, final PaymentModelDao payment,
final BigDecimal requestedAmount, final CallContext context) throws PaymentApiException {
- final boolean scheduleRetryForPayment = true;
final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), invoice.getId(), payment.getId(), clock.getUTCNow(), requestedAmount);
- paymentDao.insertNewAttemptForPayment(payment.getId(), attempt, scheduleRetryForPayment, context);
+ paymentDao.insertNewAttemptForPayment(payment.getId(), attempt, context);
return processPaymentWithAccountLocked(plugin, account, invoice, payment, attempt, false, context);
}
@@ -285,9 +385,8 @@ public class PaymentProcessor extends ProcessorBase {
BusEvent event = null;
List<PaymentAttemptModelDao> allAttempts = null;
- PaymentAttemptModelDao lastAttempt = null;
PaymentModelDao payment = null;
- PaymentStatus paymentStatus = PaymentStatus.UNKNOWN;
+ PaymentStatus paymentStatus;
try {
final PaymentInfoPlugin paymentPluginInfo = plugin.processPayment(account.getExternalKey(), paymentInput.getId(), attemptInput.getRequestedAmount());
@@ -295,38 +394,35 @@ public class PaymentProcessor extends ProcessorBase {
case PROCESSED:
// Update Payment/PaymentAttempt status
paymentStatus = PaymentStatus.SUCCESS;
- paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, null, attemptInput.getId(), context);
+ paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, null, paymentPluginInfo.getExternalReferenceId(), attemptInput.getId(), context);
// Fetch latest objects
allAttempts = paymentDao.getAttemptsForPayment(paymentInput.getId());
- lastAttempt = allAttempts.get(allAttempts.size() - 1);
- payment = paymentDao.getPayment(paymentInput.getId());
- invoicePaymentApi.notifyOfPaymentAttempt(invoice.getId(),
- paymentStatus == PaymentStatus.SUCCESS ? payment.getAmount() : null,
- paymentStatus == PaymentStatus.SUCCESS ? payment.getCurrency() : null,
- lastAttempt.getId(),
- lastAttempt.getEffectiveDate(),
- context);
+ payment = paymentDao.getPayment(paymentInput.getId());
+ invoicePaymentApi.notifyOfPayment(invoice.getId(),
+ payment.getAmount(),
+ paymentStatus == PaymentStatus.SUCCESS ? payment.getCurrency() : null,
+ payment.getId(),
+ payment.getEffectiveDate(),
+ context);
// Create Bus event
event = new DefaultPaymentInfoEvent(account.getId(),
- invoice.getId(), payment.getId(), payment.getAmount(), payment.getPaymentNumber(), paymentStatus, context.getUserToken(), payment.getEffectiveDate());
+ invoice.getId(), payment.getId(), payment.getAmount(), payment.getPaymentNumber(), paymentStatus,
+ paymentPluginInfo.getExternalReferenceId(), context.getUserToken(), payment.getEffectiveDate());
break;
case ERROR:
+ allAttempts = paymentDao.getAttemptsForPayment(paymentInput.getId());
// Schedule if non instant payment and max attempt for retry not reached yet
if (!isInstantPayment) {
- allAttempts = paymentDao.getAttemptsForPayment(paymentInput.getId());
- final int retryAttempt = getNumberAttemptsInState(paymentInput.getId(), allAttempts,
- PaymentStatus.UNKNOWN, PaymentStatus.PAYMENT_FAILURE);
- final boolean isScheduledForRetry = failedPaymentRetryService.scheduleRetry(paymentInput.getId(), retryAttempt);
- paymentStatus = isScheduledForRetry ? PaymentStatus.PAYMENT_FAILURE : PaymentStatus.PAYMENT_FAILURE_ABORTED;
+ paymentStatus = scheduleRetryOnPaymentFailure(paymentInput.getId());
} else {
paymentStatus = PaymentStatus.PAYMENT_FAILURE_ABORTED;
}
- paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, paymentPluginInfo.getGatewayError(), attemptInput.getId(), context);
+ paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, paymentPluginInfo.getGatewayError(), null, attemptInput.getId(), context);
log.info(String.format("Could not process payment for account %s, invoice %s, error = %s",
account.getId(), invoice.getId(), paymentPluginInfo.getGatewayError()));
@@ -347,9 +443,9 @@ public class PaymentProcessor extends ProcessorBase {
paymentStatus = isInstantPayment ? PaymentStatus.PAYMENT_FAILURE_ABORTED : scheduleRetryOnPluginFailure(paymentInput.getId());
// STEPH message might need truncation to fit??
- paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, e.getMessage(), attemptInput.getId(), context);
+ paymentDao.updateStatusForPaymentWithAttempt(paymentInput.getId(), paymentStatus, e.getMessage(), null, attemptInput.getId(), context);
- throw new PaymentApiException(ErrorCode.PAYMENT_CREATE_PAYMENT, account.getId(), e.getMessage());
+ throw new PaymentApiException(ErrorCode.PAYMENT_CREATE_PAYMENT, account.getId(), e.toString());
} finally {
if (event != null) {
@@ -366,6 +462,14 @@ public class PaymentProcessor extends ProcessorBase {
return isScheduledForRetry ? PaymentStatus.PLUGIN_FAILURE : PaymentStatus.PLUGIN_FAILURE_ABORTED;
}
+ private PaymentStatus scheduleRetryOnPaymentFailure(final UUID paymentId) {
+ final List<PaymentAttemptModelDao> allAttempts = paymentDao.getAttemptsForPayment(paymentId);
+ final int retryAttempt = getNumberAttemptsInState(paymentId, allAttempts,
+ PaymentStatus.UNKNOWN, PaymentStatus.PAYMENT_FAILURE);
+ final boolean isScheduledForRetry = failedPaymentRetryService.scheduleRetry(paymentId, retryAttempt);
+ return isScheduledForRetry ? PaymentStatus.PAYMENT_FAILURE : PaymentStatus.PAYMENT_FAILURE_ABORTED;
+ }
+
private int getNumberAttemptsInState(final UUID paymentId, final List<PaymentAttemptModelDao> allAttempts, final PaymentStatus... statuses) {
if (allAttempts == null || allAttempts.size() == 0) {
return 0;
diff --git a/payment/src/main/java/com/ning/billing/payment/core/ProcessorBase.java b/payment/src/main/java/com/ning/billing/payment/core/ProcessorBase.java
index 4e5c71f..9d31f67 100644
--- a/payment/src/main/java/com/ning/billing/payment/core/ProcessorBase.java
+++ b/payment/src/main/java/com/ning/billing/payment/core/ProcessorBase.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -36,7 +36,7 @@ import com.ning.billing.util.bus.Bus.EventBusException;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.globallocker.GlobalLock;
import com.ning.billing.util.globallocker.GlobalLocker;
-import com.ning.billing.util.globallocker.GlobalLocker.LockerService;
+import com.ning.billing.util.globallocker.GlobalLocker.LockerType;
import com.ning.billing.util.globallocker.LockFailedException;
public abstract class ProcessorBase {
@@ -138,7 +138,7 @@ public abstract class ProcessorBase {
throws PaymentApiException {
GlobalLock lock = null;
try {
- lock = locker.lockWithNumberOfTries(LockerService.PAYMENT, accountExternalKey, NB_LOCK_TRY);
+ lock = locker.lockWithNumberOfTries(LockerType.ACCOUNT, accountExternalKey, NB_LOCK_TRY);
return callback.doOperation();
} catch (LockFailedException e) {
final String format = String.format("Failed to lock account %s", accountExternalKey);
diff --git a/payment/src/main/java/com/ning/billing/payment/core/RefundProcessor.java b/payment/src/main/java/com/ning/billing/payment/core/RefundProcessor.java
index 4f21a9b..a7768c2 100644
--- a/payment/src/main/java/com/ning/billing/payment/core/RefundProcessor.java
+++ b/payment/src/main/java/com/ning/billing/payment/core/RefundProcessor.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -16,52 +16,233 @@
package com.ning.billing.payment.core;
import javax.inject.Inject;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
+import com.google.common.base.Function;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
import com.google.inject.name.Named;
+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.invoice.api.InvoiceApiException;
+import com.ning.billing.invoice.api.InvoicePaymentApi;
+import com.ning.billing.payment.api.DefaultRefund;
import com.ning.billing.payment.api.PaymentApiException;
+import com.ning.billing.payment.api.PaymentStatus;
import com.ning.billing.payment.api.Refund;
+import com.ning.billing.payment.dao.PaymentAttemptModelDao;
import com.ning.billing.payment.dao.PaymentDao;
+import com.ning.billing.payment.dao.RefundModelDao;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
+import com.ning.billing.payment.plugin.api.PaymentPluginApi;
+import com.ning.billing.payment.plugin.api.PaymentPluginApiException;
import com.ning.billing.payment.provider.PaymentProviderPluginRegistry;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.callcontext.CallContext;
+import com.ning.billing.util.callcontext.CallContextFactory;
+import com.ning.billing.util.callcontext.CallOrigin;
+import com.ning.billing.util.callcontext.UserType;
import com.ning.billing.util.globallocker.GlobalLocker;
import static com.ning.billing.payment.glue.PaymentModule.PLUGIN_EXECUTOR_NAMED;
public class RefundProcessor extends ProcessorBase {
+ private final static Logger log = LoggerFactory.getLogger(RefundProcessor.class);
+
+ private final InvoicePaymentApi invoicePaymentApi;
+ private final CallContextFactory factory;
+
@Inject
public RefundProcessor(final PaymentProviderPluginRegistry pluginRegistry,
- final AccountUserApi accountUserApi,
- final Bus eventBus,
- final PaymentDao paymentDao,
- final GlobalLocker locker,
- @Named(PLUGIN_EXECUTOR_NAMED) final ExecutorService executor) {
+ final AccountUserApi accountUserApi,
+ final InvoicePaymentApi invoicePaymentApi,
+ final Bus eventBus,
+ final CallContextFactory factory,
+ final PaymentDao paymentDao,
+ final GlobalLocker locker,
+ @Named(PLUGIN_EXECUTOR_NAMED) final ExecutorService executor) {
super(pluginRegistry, accountUserApi, eventBus, paymentDao, locker, executor);
+ this.invoicePaymentApi = invoicePaymentApi;
+ this.factory = factory;
}
- public Refund createRefund(final Account account, final UUID paymentId, final CallContext context)
- throws PaymentApiException {
- /*
+
+ public Refund createRefund(final Account account, final UUID paymentId, final BigDecimal refundAmount, final boolean isAdjusted, final CallContext context)
+ throws PaymentApiException {
+
+ return new WithAccountLock<Refund>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<Refund>() {
+
+ @Override
+ public Refund doOperation() throws PaymentApiException {
+ try {
+
+ final PaymentAttemptModelDao successfulAttempt = getPaymentAttempt(paymentId);
+ if (successfulAttempt == null) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_SUCCESS_PAYMENT, paymentId);
+ }
+ if (successfulAttempt.getRequestedAmount().compareTo(refundAmount) < 0) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_REFUND_AMOUNT_TOO_LARGE);
+ }
+
+ // Look for that refund entry and count any 'similar' refund left in CREATED state (same amount, same paymentId)
+ int foundPluginCompletedRefunds = 0;
+ RefundModelDao refundInfo = null;
+ List<RefundModelDao> existingRefunds = paymentDao.getRefundsForPayment(paymentId);
+ for (RefundModelDao cur : existingRefunds) {
+ if (cur.getAmount().compareTo(refundAmount) == 0) {
+ if (cur.getRefundStatus() == RefundStatus.CREATED) {
+ if (refundInfo == null) {
+ refundInfo = cur;
+ }
+ } else {
+ foundPluginCompletedRefunds++;
+ }
+ }
+ }
+ if (refundInfo == null) {
+ refundInfo = new RefundModelDao(account.getId(), paymentId, refundAmount, account.getCurrency(), isAdjusted);
+ paymentDao.insertRefund(refundInfo, context);
+ }
+
+ final PaymentPluginApi plugin = getPaymentProviderPlugin(account);
+ int nbExistingRefunds = plugin.getNbRefundForPaymentAmount(account, paymentId, refundAmount);
+ if (nbExistingRefunds > foundPluginCompletedRefunds) {
+ log.info("Found existing plugin refund for paymentId {}, skip plugin", paymentId);
+ } else {
+ // If there is no such existng refund we create it
+ plugin.processRefund(account, paymentId, refundAmount);
+ }
+ paymentDao.updateRefundStatus(refundInfo.getId(), RefundStatus.PLUGIN_COMPLETED, context);
+
+ invoicePaymentApi.createRefund(paymentId, refundAmount, isAdjusted, refundInfo.getId(), context);
+
+ paymentDao.updateRefundStatus(refundInfo.getId(), RefundStatus.COMPLETED, context);
+
+ return new DefaultRefund(refundInfo.getId(), paymentId, refundInfo.getAmount(), account.getCurrency(), isAdjusted);
+ } catch (PaymentPluginApiException e) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_CREATE_REFUND, account.getId(), e.getMessage());
+ } catch (InvoiceApiException e) {
+ throw new PaymentApiException(e);
+ }
+ }
+ });
+ }
+
+
+ public Refund getRefund(final UUID refundId)
+ throws PaymentApiException {
+ RefundModelDao result = paymentDao.getRefund(refundId);
+ if (result == null) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_REFUND, refundId);
+ }
+ List<RefundModelDao> filteredInput = filterUncompletedPluginRefund(Collections.singletonList(result));
+ if (filteredInput.size() == 0) {
+ throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_REFUND, refundId);
+ }
+
+ if (completePluginCompletedRefund(filteredInput)) {
+ result = paymentDao.getRefund(refundId);
+ }
+ return new DefaultRefund(result.getId(), result.getPaymentId(), result.getAmount(), result.getCurrency(), result.isAdjsuted());
+ }
+
+
+ public List<Refund> getAccountRefunds(final Account account)
+ throws PaymentApiException {
+ List<RefundModelDao> result = paymentDao.getRefundsForAccount(account.getId());
+ if (completePluginCompletedRefund(result)) {
+ result = paymentDao.getRefundsForAccount(account.getId());
+ }
+ List<RefundModelDao> filteredInput = filterUncompletedPluginRefund(result);
+ return toRefunds(filteredInput);
+ }
+
+ public List<Refund> getPaymentRefunds(final UUID paymentId)
+ throws PaymentApiException {
+ List<RefundModelDao> result = paymentDao.getRefundsForPayment(paymentId);
+ if (completePluginCompletedRefund(result)) {
+ result = paymentDao.getRefundsForPayment(paymentId);
+ }
+ List<RefundModelDao> filteredInput = filterUncompletedPluginRefund(result);
+ return toRefunds(filteredInput);
+ }
+
+ public List<Refund> toRefunds(final List<RefundModelDao> in) {
+ return new ArrayList<Refund>(Collections2.transform(in, new Function<RefundModelDao, Refund>() {
+ @Override
+ public Refund apply(RefundModelDao cur) {
+ return new DefaultRefund(cur.getId(), cur.getPaymentId(), cur.getAmount(), cur.getCurrency(), cur.isAdjsuted());
+ }
+ }));
+ }
+
+ private List<RefundModelDao> filterUncompletedPluginRefund(final List<RefundModelDao> input) {
+ return new ArrayList<RefundModelDao>(Collections2.filter(input, new Predicate<RefundModelDao>() {
+ @Override
+ public boolean apply(RefundModelDao in) {
+ return in.getRefundStatus() != RefundStatus.CREATED;
+ }
+ }));
+ }
+
+ private boolean completePluginCompletedRefund(final List<RefundModelDao> refunds) throws PaymentApiException {
+
+
+ final Collection<RefundModelDao> refundsToBeFixed = Collections2.filter(refunds, new Predicate<RefundModelDao>() {
+ @Override
+ public boolean apply(RefundModelDao in) {
+ return in.getRefundStatus() == RefundStatus.PLUGIN_COMPLETED;
+ }
+ });
+ if (refundsToBeFixed.size() == 0) {
+ return false;
+ }
+
try {
-
- final PaymentProviderPlugin plugin = getPaymentProviderPlugin(account);
- List<PaymentInfoPlugin> result = plugin.processRefund(account);
- List<PaymentInfoEvent> info = new LinkedList<PaymentInfoEvent>();
- int i = 0;
- for (PaymentInfoPlugin cur : result) {
- // STEPH
- //info.add(new DefaultPaymentInfoEvent(cur, account.getId(), invoiceIds.get(i)));
+ Account account = accountUserApi.getAccountById(refundsToBeFixed.iterator().next().getAccountId());
+ new WithAccountLock<Void>().processAccountWithLock(locker, account.getExternalKey(), new WithAccountLockCallback<Void>() {
+
+ @Override
+ public Void doOperation() throws PaymentApiException {
+ try {
+ final CallContext context = factory.createCallContext("RefundProcessor", CallOrigin.INTERNAL, UserType.SYSTEM);
+ for (RefundModelDao cur : refundsToBeFixed) {
+ invoicePaymentApi.createRefund(cur.getPaymentId(), cur.getAmount(), cur.isAdjsuted(), cur.getId(), context);
+ paymentDao.updateRefundStatus(cur.getId(), RefundStatus.COMPLETED, context);
+ }
+ } catch (InvoiceApiException e) {
+ throw new PaymentApiException(e);
+ }
+ return null;
+ }
+ });
+ return true;
+ } catch (AccountApiException e) {
+ throw new PaymentApiException(e);
}
- return info;
- } catch (PaymentPluginApiException e) {
- throw new PaymentApiException(ErrorCode.PAYMENT_CREATE_REFUND, account.getId(), e.getMessage());
+ }
+
+ private PaymentAttemptModelDao getPaymentAttempt(final UUID paymentId) {
+ List<PaymentAttemptModelDao> attempts = paymentDao.getAttemptsForPayment(paymentId);
+ for (PaymentAttemptModelDao cur : attempts) {
+ if (cur.getPaymentStatus() == PaymentStatus.SUCCESS) {
+ return cur;
+ }
}
- */
return null;
}
+
}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/AuditedPaymentDao.java b/payment/src/main/java/com/ning/billing/payment/dao/AuditedPaymentDao.java
index 5dad606..0a2aa27 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/AuditedPaymentDao.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/AuditedPaymentDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -25,6 +25,7 @@ import org.skife.jdbi.v2.TransactionStatus;
import com.google.inject.Inject;
import com.ning.billing.payment.api.PaymentStatus;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
import com.ning.billing.payment.retry.PluginFailureRetryService.PluginFailureRetryServiceScheduler;
import com.ning.billing.util.ChangeType;
import com.ning.billing.util.callcontext.CallContext;
@@ -34,23 +35,24 @@ import com.ning.billing.util.dao.TableName;
public class AuditedPaymentDao implements PaymentDao {
+
private final PaymentSqlDao paymentSqlDao;
private final PaymentAttemptSqlDao paymentAttemptSqlDao;
private final PaymentMethodSqlDao paymentMethodSqlDao;
- //private final TimedoutPaymentRetryServiceScheduler timedoutSchduler;
+ private final RefundSqlDao refundSqlDao;
@Inject
public AuditedPaymentDao(final IDBI dbi, final PluginFailureRetryServiceScheduler timedoutSchduler) {
this.paymentSqlDao = dbi.onDemand(PaymentSqlDao.class);
this.paymentAttemptSqlDao = dbi.onDemand(PaymentAttemptSqlDao.class);
this.paymentMethodSqlDao = dbi.onDemand(PaymentMethodSqlDao.class);
- // this.timedoutSchduler = timedoutSchduler;
+ this.refundSqlDao = dbi.onDemand(RefundSqlDao.class);
}
@Override
public PaymentAttemptModelDao insertNewAttemptForPayment(final UUID paymentId,
- final PaymentAttemptModelDao attempt, final boolean scheduleTimeoutRetry, final CallContext context) {
+ final PaymentAttemptModelDao attempt, final CallContext context) {
return paymentAttemptSqlDao.inTransaction(new Transaction<PaymentAttemptModelDao, PaymentAttemptSqlDao>() {
@Override
@@ -66,7 +68,7 @@ public class AuditedPaymentDao implements PaymentDao {
@Override
- public PaymentModelDao insertPaymentWithAttempt(final PaymentModelDao payment, final PaymentAttemptModelDao attempt, final boolean scheduleTimeoutRetry, final CallContext context) {
+ public PaymentModelDao insertPaymentWithAttempt(final PaymentModelDao payment, final PaymentAttemptModelDao attempt, final CallContext context) {
return paymentSqlDao.inTransaction(new Transaction<PaymentModelDao, PaymentSqlDao>() {
@@ -81,28 +83,6 @@ public class AuditedPaymentDao implements PaymentDao {
});
}
- /*
- private int getNbTimedoutAttemptsFromTransaction(final UUID paymentId, final PaymentAttemptSqlDao transactional) {
- List<PaymentAttemptModelDao> attempts = transactional.getPaymentAttempts(paymentId.toString());
- return Collections2.filter(attempts, new Predicate<PaymentAttemptModelDao>() {
- @Override
- public boolean apply(PaymentAttemptModelDao input) {
- return input.getPaymentStatus() == PaymentStatus.TIMEDOUT;
- }
- }).size();
- }
-
-
- private void scheduleTimeoutRetryFromTransaction(final UUID paymentId, final PaymentAttemptSqlDao transactional, final boolean scheduleTimeoutRetry) {
-
- if (scheduleTimeoutRetry) {
- int retryAttempt = getNbTimedoutAttemptsFromTransaction(paymentId, transactional) + 1;
- timedoutSchduler.scheduleRetryFromTransaction(paymentId, retryAttempt, transactional);
- }
- }
-*/
-
-
private PaymentModelDao insertPaymentFromTransaction(final PaymentModelDao payment, final CallContext context, final PaymentSqlDao transactional) {
transactional.insertPayment(payment, context);
final PaymentModelDao savedPayment = transactional.getPayment(payment.getId().toString());
@@ -139,31 +119,16 @@ public class AuditedPaymentDao implements PaymentDao {
});
}
-
- @Override
- public void updateStatusForPayment(final UUID paymentId,
- final PaymentStatus paymentStatus, final CallContext context) {
- paymentSqlDao.inTransaction(new Transaction<Void, PaymentSqlDao>() {
-
- @Override
- public Void inTransaction(final PaymentSqlDao transactional,
- final TransactionStatus status) throws Exception {
- updatePaymentStatusFromTransaction(paymentId, paymentStatus, context, transactional);
- return null;
- }
- });
- }
-
@Override
public void updateStatusForPaymentWithAttempt(final UUID paymentId,
- final PaymentStatus paymentStatus, final String paymentError, final UUID attemptId,
+ final PaymentStatus paymentStatus, final String paymentError, final String extPaymentRefId, final UUID attemptId,
final CallContext context) {
paymentSqlDao.inTransaction(new Transaction<Void, PaymentSqlDao>() {
@Override
public Void inTransaction(final PaymentSqlDao transactional,
final TransactionStatus status) throws Exception {
- updatePaymentStatusFromTransaction(paymentId, paymentStatus, context, transactional);
+ updatePaymentStatusFromTransaction(paymentId, paymentStatus, extPaymentRefId, context, transactional);
final PaymentAttemptSqlDao transPaymentAttemptSqlDao = transactional.become(PaymentAttemptSqlDao.class);
updatePaymentAttemptStatusFromTransaction(attemptId, paymentStatus, paymentError, context, transPaymentAttemptSqlDao);
return null;
@@ -182,8 +147,8 @@ public class AuditedPaymentDao implements PaymentDao {
transactional.insertAuditFromTransaction(audit, context);
}
- private void updatePaymentStatusFromTransaction(final UUID paymentId, final PaymentStatus paymentStatus, final CallContext context, final PaymentSqlDao transactional) {
- transactional.updatePaymentStatus(paymentId.toString(), paymentStatus.toString(), context);
+ private void updatePaymentStatusFromTransaction(final UUID paymentId, final PaymentStatus paymentStatus, final String extPaymentRefId, final CallContext context, final PaymentSqlDao transactional) {
+ transactional.updatePaymentStatusAndExtRef(paymentId.toString(), paymentStatus.toString(), extPaymentRefId, context);
final PaymentModelDao savedPayment = transactional.getPayment(paymentId.toString());
final Long recordId = transactional.getRecordId(savedPayment.getId().toString());
final EntityHistory<PaymentModelDao> history = new EntityHistory<PaymentModelDao>(savedPayment.getId(), recordId, savedPayment, ChangeType.UPDATE);
@@ -225,6 +190,90 @@ public class AuditedPaymentDao implements PaymentDao {
}
@Override
+ public RefundModelDao insertRefund(final RefundModelDao refundInfo, final CallContext context) {
+ return refundSqlDao.inTransaction(new Transaction<RefundModelDao, RefundSqlDao>() {
+
+ @Override
+ public RefundModelDao inTransaction(RefundSqlDao transactional,
+ TransactionStatus status) throws Exception {
+
+ transactional.insertRefund(refundInfo, context);
+ final RefundModelDao savedRefund = transactional.getRefund(refundInfo.getId().toString());
+ final Long recordId = transactional.getRecordId(savedRefund.getId().toString());
+ final EntityHistory<RefundModelDao> history = new EntityHistory<RefundModelDao>(savedRefund.getId(), recordId, savedRefund, ChangeType.INSERT);
+ transactional.insertHistoryFromTransaction(history, context);
+ final Long historyRecordId = transactional.getHistoryRecordId(recordId);
+ final EntityAudit audit = new EntityAudit(TableName.REFUNDS, historyRecordId, ChangeType.INSERT);
+ transactional.insertAuditFromTransaction(audit, context);
+ return savedRefund;
+ }
+ });
+ }
+
+
+ @Override
+ public void updateRefundStatus(final UUID refundId,
+ final RefundStatus refundStatus, final CallContext context) {
+ refundSqlDao.inTransaction(new Transaction<Void, RefundSqlDao>() {
+
+ @Override
+ public Void inTransaction(RefundSqlDao transactional,
+ TransactionStatus status) throws Exception {
+ transactional.updateStatus(refundId.toString(), refundStatus.toString());
+
+ final RefundModelDao savedRefund = transactional.getRefund(refundId.toString());
+ final Long recordId = transactional.getRecordId(savedRefund.getId().toString());
+ final EntityHistory<RefundModelDao> history = new EntityHistory<RefundModelDao>(savedRefund.getId(), recordId, savedRefund, ChangeType.UPDATE);
+ transactional.insertHistoryFromTransaction(history, context);
+ final Long historyRecordId = transactional.getHistoryRecordId(recordId);
+ final EntityAudit audit = new EntityAudit(TableName.REFUNDS, historyRecordId, ChangeType.UPDATE);
+ transactional.insertAuditFromTransaction(audit, context);
+ return null;
+ }
+ });
+ }
+
+ @Override
+ public RefundModelDao getRefund(final UUID refundId) {
+ return refundSqlDao.inTransaction(new Transaction<RefundModelDao, RefundSqlDao>() {
+
+ @Override
+ public RefundModelDao inTransaction(RefundSqlDao transactional,
+ TransactionStatus status) throws Exception {
+ return transactional.getRefund(refundId.toString());
+ }
+ });
+ }
+
+
+ @Override
+ public List<RefundModelDao> getRefundsForPayment(final UUID paymentId) {
+ return refundSqlDao.inTransaction(new Transaction<List<RefundModelDao>, RefundSqlDao>() {
+
+ @Override
+ public List<RefundModelDao> inTransaction(RefundSqlDao transactional,
+ TransactionStatus status) throws Exception {
+ return transactional.getRefundsForPayment(paymentId.toString());
+ }
+ });
+ }
+
+
+ @Override
+ public List<RefundModelDao> getRefundsForAccount(final UUID accountId) {
+ return refundSqlDao.inTransaction(new Transaction<List<RefundModelDao>, RefundSqlDao>() {
+
+ @Override
+ public List<RefundModelDao> inTransaction(RefundSqlDao transactional,
+ TransactionStatus status) throws Exception {
+ return transactional.getRefundsForAccount(accountId.toString());
+ }
+ });
+ }
+
+
+
+ @Override
public PaymentMethodModelDao getPaymentMethod(final UUID paymentMethodId) {
return paymentMethodSqlDao.inTransaction(new Transaction<PaymentMethodModelDao, PaymentMethodSqlDao>() {
@Override
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/PaymentAttemptModelDao.java b/payment/src/main/java/com/ning/billing/payment/dao/PaymentAttemptModelDao.java
index 9c65c80..383bd0f 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/PaymentAttemptModelDao.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/PaymentAttemptModelDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -46,6 +46,10 @@ public class PaymentAttemptModelDao extends EntityBase {
this.paymentError = paymentError;
}
+ public PaymentAttemptModelDao(final UUID accountId, final UUID invoiceId, final UUID paymentId, final PaymentStatus paymentStatus, final DateTime effectiveDate, final BigDecimal requestedAmount) {
+ this(UUID.randomUUID(), accountId, invoiceId, paymentId, paymentStatus, effectiveDate, requestedAmount, null);
+ }
+
public PaymentAttemptModelDao(final UUID accountId, final UUID invoiceId, final UUID paymentId, final DateTime effectiveDate, final BigDecimal requestedAmount) {
this(UUID.randomUUID(), accountId, invoiceId, paymentId, PaymentStatus.UNKNOWN, effectiveDate, requestedAmount, null);
}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/PaymentDao.java b/payment/src/main/java/com/ning/billing/payment/dao/PaymentDao.java
index 6580217..68a7fec 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/PaymentDao.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/PaymentDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -19,19 +19,17 @@ import java.util.List;
import java.util.UUID;
import com.ning.billing.payment.api.PaymentStatus;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
import com.ning.billing.util.callcontext.CallContext;
public interface PaymentDao {
// STEPH do we need object returned?
- public PaymentModelDao insertPaymentWithAttempt(final PaymentModelDao paymentInfo, final PaymentAttemptModelDao attempt, final boolean scheduleTimeoutRetry, final CallContext context);
+ public PaymentModelDao insertPaymentWithAttempt(final PaymentModelDao paymentInfo, final PaymentAttemptModelDao attempt, final CallContext context);
- public PaymentAttemptModelDao insertNewAttemptForPayment(final UUID paymentId, final PaymentAttemptModelDao attempt, final boolean scheduleTimeoutRetry, final CallContext context);
+ public PaymentAttemptModelDao insertNewAttemptForPayment(final UUID paymentId, final PaymentAttemptModelDao attempt, final CallContext context);
-
- public void updateStatusForPayment(final UUID paymentId, final PaymentStatus paymentStatus, final CallContext context);
-
- public void updateStatusForPaymentWithAttempt(final UUID paymentId, final PaymentStatus paymentStatus, final String paymentError, final UUID attemptId, final CallContext context);
+ public void updateStatusForPaymentWithAttempt(final UUID paymentId, final PaymentStatus paymentStatus, final String paymentError, final String extPaymentRefId, final UUID attemptId, final CallContext context);
public PaymentAttemptModelDao getPaymentAttempt(final UUID attemptId);
@@ -43,6 +41,16 @@ public interface PaymentDao {
public List<PaymentAttemptModelDao> getAttemptsForPayment(final UUID paymentId);
+ public RefundModelDao insertRefund(RefundModelDao refundInfo, final CallContext context);
+
+ public void updateRefundStatus(UUID refundId, RefundStatus status, final CallContext context);
+
+ public RefundModelDao getRefund(UUID refundId);
+
+ public List<RefundModelDao> getRefundsForPayment(final UUID paymentId);
+
+ public List<RefundModelDao> getRefundsForAccount(final UUID accountId);
+
public PaymentMethodModelDao insertPaymentMethod(final PaymentMethodModelDao paymentMethod, final CallContext context);
public PaymentMethodModelDao getPaymentMethod(final UUID paymentMethodId);
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/PaymentHistoryBinder.java b/payment/src/main/java/com/ning/billing/payment/dao/PaymentHistoryBinder.java
index a68de8c..d47cf05 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/PaymentHistoryBinder.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/PaymentHistoryBinder.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -49,6 +49,7 @@ public @interface PaymentHistoryBinder {
q.bind("amount", payment.getAmount());
q.bind("currency", payment.getCurrency().toString());
q.bind("paymentStatus", payment.getPaymentStatus().toString());
+ q.bind("externalPaymentRefId", payment.getExtPaymentRefId());
q.bind("effectiveDate", getDate(payment.getEffectiveDate()));
}
};
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/PaymentModelDao.java b/payment/src/main/java/com/ning/billing/payment/dao/PaymentModelDao.java
index 6ee7ea1..24a9f74 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/PaymentModelDao.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/PaymentModelDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -36,11 +36,11 @@ public class PaymentModelDao extends EntityBase {
private final DateTime effectiveDate;
private final Integer paymentNumber;
private final PaymentStatus paymentStatus;
-
+ private final String extPaymentRefId;
public PaymentModelDao(final UUID id, final UUID accountId, final UUID invoiceId, final UUID paymentMethodId,
final Integer paymentNumber, final BigDecimal amount, final Currency currency,
- final PaymentStatus paymentStatus, final DateTime effectiveDate) {
+ final PaymentStatus paymentStatus, final DateTime effectiveDate, final String extPaymentRefId) {
super(id);
this.accountId = accountId;
this.invoiceId = invoiceId;
@@ -50,16 +50,21 @@ public class PaymentModelDao extends EntityBase {
this.currency = currency;
this.paymentStatus = paymentStatus;
this.effectiveDate = effectiveDate;
+ this.extPaymentRefId = extPaymentRefId;
+ }
+
+ public PaymentModelDao(final UUID accountId, final UUID invoiceId, final UUID paymentMethodId,
+ final BigDecimal amount, final Currency currency, final DateTime effectiveDate, final PaymentStatus paymentStatus) {
+ this(UUID.randomUUID(), accountId, invoiceId, paymentMethodId, INVALID_PAYMENT_NUMBER, amount, currency, paymentStatus, effectiveDate, null);
}
- public PaymentModelDao(final UUID accountId, final UUID invoiceId,
- final BigDecimal amount, final Currency currency, final DateTime effectiveDate) {
- this(UUID.randomUUID(), accountId, invoiceId, null, INVALID_PAYMENT_NUMBER, amount, currency, PaymentStatus.UNKNOWN, effectiveDate);
+ public PaymentModelDao(final UUID accountId, final UUID invoiceId, final UUID paymentMethodId,
+ final BigDecimal amount, final Currency currency, final DateTime effectiveDate) {
+ this(UUID.randomUUID(), accountId, invoiceId, paymentMethodId, INVALID_PAYMENT_NUMBER, amount, currency, PaymentStatus.UNKNOWN, effectiveDate, null);
}
public PaymentModelDao(final PaymentModelDao src, final PaymentStatus newPaymentStatus) {
- this(src.getId(), src.getAccountId(), src.getInvoiceId(), null, src.getPaymentNumber(), src.getAmount(), src.getCurrency(), newPaymentStatus, src.getEffectiveDate())
- ;
+ this(src.getId(), src.getAccountId(), src.getInvoiceId(), src.getPaymentMethodId(), src.getPaymentNumber(), src.getAmount(), src.getCurrency(), newPaymentStatus, src.getEffectiveDate(), null);
}
public UUID getAccountId() {
@@ -93,4 +98,8 @@ public class PaymentModelDao extends EntityBase {
public DateTime getEffectiveDate() {
return effectiveDate;
}
+
+ public String getExtPaymentRefId() {
+ return extPaymentRefId;
+ }
}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/PaymentSqlDao.java b/payment/src/main/java/com/ning/billing/payment/dao/PaymentSqlDao.java
index 4173ac2..7946673 100644
--- a/payment/src/main/java/com/ning/billing/payment/dao/PaymentSqlDao.java
+++ b/payment/src/main/java/com/ning/billing/payment/dao/PaymentSqlDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -53,8 +53,8 @@ public interface PaymentSqlDao extends Transactional<PaymentSqlDao>, UpdatableEn
@CallContextBinder final CallContext context);
@SqlUpdate
- void updatePaymentStatus(@Bind("id") final String paymentId, @Bind("paymentStatus") final String paymentStatus,
- @CallContextBinder final CallContext context);
+ void updatePaymentStatusAndExtRef(@Bind("id") final String paymentId, @Bind("paymentStatus") final String paymentStatus,
+ @Bind("externalPaymentRefId") final String externalPaymentRefId, @CallContextBinder final CallContext context);
@SqlUpdate
void updatePaymentAmount(@Bind("id") final String paymentId, @Bind("amount") final BigDecimal amount,
@@ -82,11 +82,12 @@ public interface PaymentSqlDao extends Transactional<PaymentSqlDao>, UpdatableEn
stmt.bind("id", payment.getId().toString());
stmt.bind("accountId", payment.getAccountId().toString());
stmt.bind("invoiceId", payment.getInvoiceId().toString());
- stmt.bind("paymentMethodId", "");
+ stmt.bind("paymentMethodId", payment.getPaymentMethodId().toString());
stmt.bind("amount", payment.getAmount());
stmt.bind("currency", payment.getCurrency().toString());
stmt.bind("effectiveDate", getDate(payment.getEffectiveDate()));
stmt.bind("paymentStatus", payment.getPaymentStatus().toString());
+ stmt.bind("externalPaymentRefId", payment.getExtPaymentRefId());
}
}
@@ -98,14 +99,15 @@ public interface PaymentSqlDao extends Transactional<PaymentSqlDao>, UpdatableEn
final UUID id = getUUID(rs, "id");
final UUID accountId = getUUID(rs, "account_id");
final UUID invoiceId = getUUID(rs, "invoice_id");
- final UUID paymentMethodId = null; //getUUID(rs, "payment_method_id"); // STEPH needs to be fixed!
+ final UUID paymentMethodId = getUUID(rs, "payment_method_id");
final Integer paymentNumber = rs.getInt("payment_number");
final BigDecimal amount = rs.getBigDecimal("amount");
final DateTime effectiveDate = getDate(rs, "effective_date");
final Currency currency = Currency.valueOf(rs.getString("currency"));
final PaymentStatus paymentStatus = PaymentStatus.valueOf(rs.getString("payment_status"));
+ final String extPaymentRefId = rs.getString("external_payment_ref_id");
- return new PaymentModelDao(id, accountId, invoiceId, paymentMethodId, paymentNumber, amount, currency, paymentStatus, effectiveDate);
+ return new PaymentModelDao(id, accountId, invoiceId, paymentMethodId, paymentNumber, amount, currency, paymentStatus, effectiveDate, extPaymentRefId);
}
}
}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/RefundHistoryBinder.java b/payment/src/main/java/com/ning/billing/payment/dao/RefundHistoryBinder.java
new file mode 100644
index 0000000..3110b2f
--- /dev/null
+++ b/payment/src/main/java/com/ning/billing/payment/dao/RefundHistoryBinder.java
@@ -0,0 +1,59 @@
+/*
+ * 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.payment.dao;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.skife.jdbi.v2.SQLStatement;
+import org.skife.jdbi.v2.sqlobject.Binder;
+import org.skife.jdbi.v2.sqlobject.BinderFactory;
+import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
+
+import com.ning.billing.util.dao.BinderBase;
+import com.ning.billing.util.dao.EntityHistory;
+
+
+@BindingAnnotation(RefundHistoryBinder.RefundHistoryBinderFactory.class)
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.PARAMETER})
+public @interface RefundHistoryBinder {
+
+
+ public static class RefundHistoryBinderFactory extends BinderBase implements BinderFactory {
+ @Override
+ public Binder<RefundHistoryBinder, EntityHistory<RefundModelDao>> build(final Annotation annotation) {
+ return new Binder<RefundHistoryBinder, EntityHistory<RefundModelDao>>() {
+ @Override
+ public void bind(final SQLStatement<?> q, final RefundHistoryBinder bind, final EntityHistory<RefundModelDao> history) {
+ q.bind("recordId", history.getValue());
+ q.bind("changeType", history.getChangeType().toString());
+ final RefundModelDao refund = history.getEntity();
+ q.bind("id", refund.getId().toString());
+ q.bind("accountId", refund.getAccountId().toString());
+ q.bind("paymentId", refund.getPaymentId().toString());
+ q.bind("amount", refund.getAmount());
+ q.bind("currency", refund.getCurrency().toString());
+ q.bind("isAdjusted", refund.isAdjsuted());
+ q.bind("refundStatus", refund.getRefundStatus().toString());
+ }
+ };
+ }
+ }
+}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/RefundModelDao.java b/payment/src/main/java/com/ning/billing/payment/dao/RefundModelDao.java
new file mode 100644
index 0000000..286fe51
--- /dev/null
+++ b/payment/src/main/java/com/ning/billing/payment/dao/RefundModelDao.java
@@ -0,0 +1,79 @@
+/*
+ * 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.payment.dao;
+
+import java.math.BigDecimal;
+import java.util.UUID;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.util.entity.EntityBase;
+
+
+public class RefundModelDao extends EntityBase {
+
+ private final UUID accountId;
+ private final UUID paymentId;
+ private final BigDecimal amount;
+ private final Currency currency;
+ private final boolean isAdjusted;
+ private final RefundStatus refundStatus;
+
+ public RefundModelDao(final UUID accountId, final UUID paymentId,
+ final BigDecimal amount, final Currency currency, final boolean isAdjusted) {
+ this(UUID.randomUUID(), accountId, paymentId, amount, currency, isAdjusted, RefundStatus.CREATED);
+ }
+
+ public RefundModelDao(final UUID id, final UUID accountId, final UUID paymentId,
+ final BigDecimal amount, final Currency currency, final boolean isAdjusted, final RefundStatus refundStatus) {
+ super(id);
+ this.accountId = accountId;
+ this.paymentId = paymentId;
+ this.amount = amount;
+ this.currency = currency;
+ this.refundStatus = refundStatus;
+ this.isAdjusted = isAdjusted;
+ }
+
+ public UUID getAccountId() {
+ return accountId;
+ }
+
+ public UUID getPaymentId() {
+ return paymentId;
+ }
+
+ public BigDecimal getAmount() {
+ return amount;
+ }
+
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public RefundStatus getRefundStatus() {
+ return refundStatus;
+ }
+
+ public boolean isAdjsuted() {
+ return isAdjusted;
+ }
+
+ public enum RefundStatus {
+ CREATED,
+ PLUGIN_COMPLETED,
+ COMPLETED,
+ }
+}
diff --git a/payment/src/main/java/com/ning/billing/payment/dao/RefundSqlDao.java b/payment/src/main/java/com/ning/billing/payment/dao/RefundSqlDao.java
new file mode 100644
index 0000000..e6bea41
--- /dev/null
+++ b/payment/src/main/java/com/ning/billing/payment/dao/RefundSqlDao.java
@@ -0,0 +1,102 @@
+/*
+ * 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.payment.dao;
+
+import java.math.BigDecimal;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.UUID;
+
+import org.skife.jdbi.v2.SQLStatement;
+import org.skife.jdbi.v2.StatementContext;
+import org.skife.jdbi.v2.sqlobject.Bind;
+import org.skife.jdbi.v2.sqlobject.Binder;
+import org.skife.jdbi.v2.sqlobject.SqlQuery;
+import org.skife.jdbi.v2.sqlobject.SqlUpdate;
+import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
+import org.skife.jdbi.v2.sqlobject.mixins.CloseMe;
+import org.skife.jdbi.v2.sqlobject.mixins.Transactional;
+import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
+import org.skife.jdbi.v2.sqlobject.stringtemplate.ExternalizedSqlViaStringTemplate3;
+import org.skife.jdbi.v2.tweak.ResultSetMapper;
+
+import com.ning.billing.catalog.api.Currency;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
+import com.ning.billing.util.callcontext.CallContext;
+import com.ning.billing.util.callcontext.CallContextBinder;
+import com.ning.billing.util.dao.BinderBase;
+import com.ning.billing.util.dao.EntityHistory;
+import com.ning.billing.util.dao.MapperBase;
+import com.ning.billing.util.entity.dao.UpdatableEntitySqlDao;
+
+
+@ExternalizedSqlViaStringTemplate3()
+@RegisterMapper(RefundSqlDao.RefundModelDaoMapper.class)
+public interface RefundSqlDao extends Transactional<RefundSqlDao>, UpdatableEntitySqlDao<RefundModelDao>, Transmogrifier, CloseMe {
+
+
+ @SqlUpdate
+ void insertRefund(@Bind(binder = RefundModelDaoBinder.class) final RefundModelDao refundInfo,
+ @CallContextBinder final CallContext context);
+
+ @SqlUpdate
+ void updateStatus(@Bind("id") final String refundId, @Bind("refundStatus") final String status);
+
+ @SqlQuery
+ RefundModelDao getRefund(@Bind("id") final String refundId);
+
+ @SqlQuery
+ List<RefundModelDao> getRefundsForPayment(@Bind("paymentId") final String paymentId);
+
+ @SqlQuery
+ List<RefundModelDao> getRefundsForAccount(@Bind("accountId") final String accountId);
+
+ @Override
+ @SqlUpdate
+ public void insertHistoryFromTransaction(@RefundHistoryBinder final EntityHistory<RefundModelDao> payment,
+ @CallContextBinder final CallContext context);
+
+
+ public static final class RefundModelDaoBinder extends BinderBase implements Binder<Bind, RefundModelDao> {
+ @Override
+ public void bind(@SuppressWarnings("rawtypes") final SQLStatement stmt, final Bind bind, final RefundModelDao refund) {
+ stmt.bind("id", refund.getId().toString());
+ stmt.bind("accountId", refund.getAccountId().toString());
+ stmt.bind("paymentId", refund.getPaymentId().toString());
+ stmt.bind("amount", refund.getAmount());
+ stmt.bind("currency", refund.getCurrency().toString());
+ stmt.bind("isAdjusted", refund.isAdjsuted());
+ stmt.bind("refundStatus", refund.getRefundStatus().toString());
+ }
+ }
+
+ public static class RefundModelDaoMapper extends MapperBase implements ResultSetMapper<RefundModelDao> {
+
+ @Override
+ public RefundModelDao map(final int index, final ResultSet rs, final StatementContext ctx)
+ throws SQLException {
+ final UUID id = getUUID(rs, "id");
+ final UUID accountId = getUUID(rs, "account_id");
+ final UUID paymentId = getUUID(rs, "payment_id");
+ final BigDecimal amount = rs.getBigDecimal("amount");
+ final boolean isAdjusted = rs.getBoolean("is_adjusted");
+ final Currency currency = Currency.valueOf(rs.getString("currency"));
+ final RefundStatus refundStatus = RefundStatus.valueOf(rs.getString("refund_status"));
+ return new RefundModelDao(id, accountId, paymentId, amount, currency, isAdjusted, refundStatus);
+ }
+ }
+}
diff --git a/payment/src/main/java/com/ning/billing/payment/glue/DefaultPaymentService.java b/payment/src/main/java/com/ning/billing/payment/glue/DefaultPaymentService.java
index 9bd547b..cc97e10 100644
--- a/payment/src/main/java/com/ning/billing/payment/glue/DefaultPaymentService.java
+++ b/payment/src/main/java/com/ning/billing/payment/glue/DefaultPaymentService.java
@@ -25,6 +25,8 @@ import com.ning.billing.lifecycle.LifecycleHandlerType.LifecycleLevel;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentService;
import com.ning.billing.payment.bus.InvoiceHandler;
+import com.ning.billing.payment.bus.TagHandler;
+import com.ning.billing.payment.retry.AutoPayRetryService;
import com.ning.billing.payment.retry.FailedPaymentRetryService;
import com.ning.billing.payment.retry.PluginFailureRetryService;
import com.ning.billing.util.bus.Bus;
@@ -35,23 +37,30 @@ public class DefaultPaymentService implements PaymentService {
private static final Logger log = LoggerFactory.getLogger(DefaultPaymentService.class);
- // STEPH for retry crappiness
public static final String SERVICE_NAME = "payment-service";
- private final InvoiceHandler requestProcessor;
+ private final InvoiceHandler invoiceHandler;
+ private final TagHandler tagHandler;
private final Bus eventBus;
private final PaymentApi api;
private final FailedPaymentRetryService failedRetryService;
private final PluginFailureRetryService timedoutRetryService;
+ private final AutoPayRetryService autoPayoffRetryService;
@Inject
- public DefaultPaymentService(final InvoiceHandler requestProcessor, final PaymentApi api, final Bus eventBus,
- final FailedPaymentRetryService failedRetryService, final PluginFailureRetryService timedoutRetryService) {
- this.requestProcessor = requestProcessor;
+ public DefaultPaymentService(final InvoiceHandler invoiceHandler,
+ final TagHandler tagHandler,
+ final PaymentApi api, final Bus eventBus,
+ final FailedPaymentRetryService failedRetryService,
+ final PluginFailureRetryService timedoutRetryService,
+ final AutoPayRetryService autoPayoffRetryService) {
+ this.invoiceHandler = invoiceHandler;
+ this.tagHandler = tagHandler;
this.eventBus = eventBus;
this.api = api;
this.failedRetryService = failedRetryService;
this.timedoutRetryService = timedoutRetryService;
+ this.autoPayoffRetryService = autoPayoffRetryService;
}
@Override
@@ -63,12 +72,14 @@ public class DefaultPaymentService implements PaymentService {
public void initialize() throws NotificationQueueAlreadyExists {
failedRetryService.initialize(SERVICE_NAME);
timedoutRetryService.initialize(SERVICE_NAME);
+ autoPayoffRetryService.initialize(SERVICE_NAME);
}
@LifecycleHandlerType(LifecycleHandlerType.LifecycleLevel.REGISTER_EVENTS)
public void registerForNotifications() {
try {
- eventBus.register(requestProcessor);
+ eventBus.register(invoiceHandler);
+ eventBus.register(tagHandler);
} catch (Bus.EventBusException e) {
log.error("Unable to register with the EventBus!", e);
}
@@ -78,12 +89,14 @@ public class DefaultPaymentService implements PaymentService {
public void start() {
failedRetryService.start();
timedoutRetryService.start();
+ autoPayoffRetryService.start();
}
@LifecycleHandlerType(LifecycleLevel.STOP_SERVICE)
public void stop() throws NoSuchNotificationQueue {
failedRetryService.stop();
timedoutRetryService.stop();
+ autoPayoffRetryService.stop();
}
@Override
diff --git a/payment/src/main/java/com/ning/billing/payment/glue/PaymentModule.java b/payment/src/main/java/com/ning/billing/payment/glue/PaymentModule.java
index 803b818..348a0ed 100644
--- a/payment/src/main/java/com/ning/billing/payment/glue/PaymentModule.java
+++ b/payment/src/main/java/com/ning/billing/payment/glue/PaymentModule.java
@@ -33,6 +33,7 @@ import com.ning.billing.payment.api.DefaultPaymentApi;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentService;
import com.ning.billing.payment.bus.InvoiceHandler;
+import com.ning.billing.payment.bus.TagHandler;
import com.ning.billing.payment.core.PaymentMethodProcessor;
import com.ning.billing.payment.core.PaymentProcessor;
import com.ning.billing.payment.core.RefundProcessor;
@@ -40,6 +41,8 @@ import com.ning.billing.payment.dao.AuditedPaymentDao;
import com.ning.billing.payment.dao.PaymentDao;
import com.ning.billing.payment.provider.DefaultPaymentProviderPluginRegistry;
import com.ning.billing.payment.provider.PaymentProviderPluginRegistry;
+import com.ning.billing.payment.retry.AutoPayRetryService;
+import com.ning.billing.payment.retry.AutoPayRetryService.AutoPayRetryServiceScheduler;
import com.ning.billing.payment.retry.FailedPaymentRetryService;
import com.ning.billing.payment.retry.FailedPaymentRetryService.FailedPaymentRetryServiceScheduler;
import com.ning.billing.payment.retry.PluginFailureRetryService;
@@ -76,8 +79,10 @@ public class PaymentModule extends AbstractModule {
protected void installRetryEngines() {
bind(FailedPaymentRetryService.class).asEagerSingleton();
bind(PluginFailureRetryService.class).asEagerSingleton();
+ bind(AutoPayRetryService.class).asEagerSingleton();
bind(FailedPaymentRetryServiceScheduler.class).asEagerSingleton();
bind(PluginFailureRetryServiceScheduler.class).asEagerSingleton();
+ bind(AutoPayRetryServiceScheduler.class).asEagerSingleton();
}
protected void installProcessors() {
@@ -105,6 +110,7 @@ public class PaymentModule extends AbstractModule {
bind(PaymentProviderPluginRegistry.class).to(DefaultPaymentProviderPluginRegistry.class).asEagerSingleton();
bind(PaymentApi.class).to(DefaultPaymentApi.class).asEagerSingleton();
bind(InvoiceHandler.class).asEagerSingleton();
+ bind(TagHandler.class).asEagerSingleton();
bind(PaymentService.class).to(DefaultPaymentService.class).asEagerSingleton();
installPaymentProviderPlugins(paymentConfig);
installPaymentDao();
diff --git a/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentInfoPlugin.java b/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentInfoPlugin.java
index 325d03d..e4c20f3 100644
--- a/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentInfoPlugin.java
+++ b/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentInfoPlugin.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -70,4 +70,10 @@ public class DefaultNoOpPaymentInfoPlugin implements PaymentInfoPlugin {
public String getGatewayErrorCode() {
return null;
}
+
+
+ @Override
+ public String getExternalReferenceId() {
+ return null;
+ }
}
diff --git a/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentProviderPlugin.java b/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentProviderPlugin.java
index 5591937..c43b64b 100644
--- a/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentProviderPlugin.java
+++ b/payment/src/main/java/com/ning/billing/payment/provider/DefaultNoOpPaymentProviderPlugin.java
@@ -192,8 +192,14 @@ public class DefaultNoOpPaymentProviderPlugin implements NoOpPaymentPluginApi {
}
@Override
- public List<PaymentInfoPlugin> processRefund(final Account account)
- throws PaymentPluginApiException {
- return null;
+ public void processRefund(Account account, UUID paymentId,
+ BigDecimal refundAmout) throws PaymentPluginApiException {
+ }
+
+ @Override
+ public int getNbRefundForPaymentAmount(Account account, UUID paymentId,
+ BigDecimal refundAmount) throws PaymentPluginApiException {
+ return 0;
}
+
}
diff --git a/payment/src/main/java/com/ning/billing/payment/retry/AutoPayRetryService.java b/payment/src/main/java/com/ning/billing/payment/retry/AutoPayRetryService.java
new file mode 100644
index 0000000..1ebb798
--- /dev/null
+++ b/payment/src/main/java/com/ning/billing/payment/retry/AutoPayRetryService.java
@@ -0,0 +1,78 @@
+/*
+ * 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.payment.retry;
+
+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.config.PaymentConfig;
+import com.ning.billing.payment.core.PaymentProcessor;
+import com.ning.billing.util.clock.Clock;
+import com.ning.billing.util.notificationq.NotificationQueueService;
+
+
+public class AutoPayRetryService extends BaseRetryService implements RetryService {
+
+
+ private static final Logger log = LoggerFactory.getLogger(FailedPaymentRetryService.class);
+
+ public static final String QUEUE_NAME = "autopayoff";
+
+ private final PaymentProcessor paymentProcessor;
+
+ @Inject
+ public AutoPayRetryService(final NotificationQueueService notificationQueueService,
+ final Clock clock,
+ final PaymentConfig config,
+ final PaymentProcessor paymentProcessor) {
+ super(notificationQueueService, clock, config);
+ this.paymentProcessor = paymentProcessor;
+ }
+
+
+ @Override
+ public String getQueueName() {
+ return QUEUE_NAME;
+ }
+
+ @Override
+ public void retry(final UUID paymentId) {
+ paymentProcessor.retryAutoPayOff(paymentId);
+ }
+
+ public static class AutoPayRetryServiceScheduler extends RetryServiceScheduler {
+
+
+ @Inject
+ public AutoPayRetryServiceScheduler(final NotificationQueueService notificationQueueService) {
+ super(notificationQueueService);
+ }
+
+ @Override
+ public boolean scheduleRetry(final UUID paymentId, final DateTime timeOfRetry) {
+ return super.scheduleRetry(paymentId, timeOfRetry);
+ }
+
+ @Override
+ public String getQueueName() {
+ return QUEUE_NAME;
+ }
+ }
+}
diff --git a/payment/src/main/java/com/ning/billing/payment/retry/BaseRetryService.java b/payment/src/main/java/com/ning/billing/payment/retry/BaseRetryService.java
index 292583e..cd48c67 100644
--- a/payment/src/main/java/com/ning/billing/payment/retry/BaseRetryService.java
+++ b/payment/src/main/java/com/ning/billing/payment/retry/BaseRetryService.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -66,7 +66,7 @@ public abstract class BaseRetryService implements RetryService {
},
config);
}
-
+
@Override
public void start() {
retryQueue.startQueue();
@@ -80,6 +80,7 @@ public abstract class BaseRetryService implements RetryService {
}
}
+ @Override
public abstract String getQueueName();
@@ -125,9 +126,9 @@ public abstract class BaseRetryService implements RetryService {
final NotificationKey key = new PaymentRetryNotificationKey(paymentId);
if (retryQueue != null) {
if (transactionalDao == null) {
- retryQueue.recordFutureNotification(timeOfRetry, key);
+ retryQueue.recordFutureNotification(timeOfRetry, null, key);
} else {
- retryQueue.recordFutureNotificationFromTransaction(transactionalDao, timeOfRetry, key);
+ retryQueue.recordFutureNotificationFromTransaction(transactionalDao, timeOfRetry, null, key);
}
}
} catch (NoSuchNotificationQueue e) {
diff --git a/payment/src/main/java/com/ning/billing/payment/retry/FailedPaymentRetryService.java b/payment/src/main/java/com/ning/billing/payment/retry/FailedPaymentRetryService.java
index 2259ce6..9fd3231 100644
--- a/payment/src/main/java/com/ning/billing/payment/retry/FailedPaymentRetryService.java
+++ b/payment/src/main/java/com/ning/billing/payment/retry/FailedPaymentRetryService.java
@@ -77,7 +77,7 @@ public class FailedPaymentRetryService extends BaseRetryService implements Retry
if (timeOfRetry == null) {
return false;
}
- return scheduleRetry(paymentId, timeOfRetry);
+ return super.scheduleRetry(paymentId, timeOfRetry);
}
diff --git a/payment/src/main/java/com/ning/billing/payment/retry/PluginFailureRetryService.java b/payment/src/main/java/com/ning/billing/payment/retry/PluginFailureRetryService.java
index 2fca8e0..6ea381c 100644
--- a/payment/src/main/java/com/ning/billing/payment/retry/PluginFailureRetryService.java
+++ b/payment/src/main/java/com/ning/billing/payment/retry/PluginFailureRetryService.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -78,7 +78,7 @@ public class PluginFailureRetryService extends BaseRetryService implements Retry
if (nextRetryDate == null) {
return false;
}
- return scheduleRetry(paymentId, nextRetryDate);
+ return super.scheduleRetry(paymentId, nextRetryDate);
}
public boolean scheduleRetryFromTransaction(final UUID paymentId, final int retryAttempt, final Transmogrifier transactionalDao) {
diff --git a/payment/src/main/resources/com/ning/billing/payment/dao/PaymentSqlDao.sql.stg b/payment/src/main/resources/com/ning/billing/payment/dao/PaymentSqlDao.sql.stg
index 2dc34b6..742d9f7 100644
--- a/payment/src/main/resources/com/ning/billing/payment/dao/PaymentSqlDao.sql.stg
+++ b/payment/src/main/resources/com/ning/billing/payment/dao/PaymentSqlDao.sql.stg
@@ -9,6 +9,7 @@ paymentFields(prefix) ::= <<
<prefix>effective_date,
<prefix>currency,
<prefix>payment_status,
+ <prefix>external_payment_ref_id,
<prefix>created_by,
<prefix>created_date,
<prefix>updated_by,
@@ -17,7 +18,7 @@ paymentFields(prefix) ::= <<
insertPayment() ::= <<
INSERT INTO payments (<paymentFields()>)
- VALUES (:id, :accountId, :invoiceId, :paymentMethodId, :amount, :effectiveDate, :currency, :paymentStatus, :userName, :createdDate, :userName, :createdDate);
+ VALUES (:id, :accountId, :invoiceId, :paymentMethodId, :amount, :effectiveDate, :currency, :paymentStatus, :externalPaymentRefId, :userName, :createdDate, :userName, :createdDate);
>>
getPayment() ::= <<
@@ -42,9 +43,9 @@ getPaymentsForAccount() ::= <<
>>
-updatePaymentStatus() ::= <<
+updatePaymentStatusAndExtRef() ::= <<
UPDATE payments
- SET payment_status = :paymentStatus
+ SET payment_status = :paymentStatus, external_payment_ref_id = :externalPaymentRefId
WHERE id = :id;
>>
@@ -71,6 +72,7 @@ historyFields(prefix) ::= <<
<prefix>effective_date,
<prefix>currency,
<prefix>payment_status,
+ <prefix>external_payment_ref_id,
<prefix>created_by,
<prefix>created_date,
<prefix>updated_by,
@@ -79,7 +81,7 @@ historyFields(prefix) ::= <<
insertHistoryFromTransaction() ::= <<
INSERT INTO payment_history (<historyFields()>)
- VALUES (:recordId, :id, :accountId, :invoiceId, :paymentMethodId, :amount, :effectiveDate, :currency, :paymentStatus, :userName, :createdDate, :userName, :updatedDate);
+ VALUES (:recordId, :id, :accountId, :invoiceId, :paymentMethodId, :amount, :effectiveDate, :currency, :paymentStatus, :externalPaymentRefId, :userName, :createdDate, :userName, :updatedDate);
>>
diff --git a/payment/src/main/resources/com/ning/billing/payment/dao/RefundSqlDao.sql.stg b/payment/src/main/resources/com/ning/billing/payment/dao/RefundSqlDao.sql.stg
new file mode 100644
index 0000000..d1e8719
--- /dev/null
+++ b/payment/src/main/resources/com/ning/billing/payment/dao/RefundSqlDao.sql.stg
@@ -0,0 +1,92 @@
+group RefundSqlDao;
+
+refundFields(prefix) ::= <<
+<prefix>id,
+<prefix>account_id,
+<prefix>payment_id,
+<prefix>amount,
+<prefix>currency,
+<prefix>is_adjusted,
+<prefix>refund_status,
+<prefix>created_by,
+<prefix>created_date,
+<prefix>updated_by,
+<prefix>updated_date
+>>
+
+insertRefund() ::= <<
+ INSERT INTO refunds (<refundFields()>)
+ VALUES (:id, :accountId, :paymentId, :amount, :currency, :isAdjusted, :refundStatus, :userName, :createdDate, :userName, :createdDate);
+>>
+
+updateStatus() ::= <<
+ UPDATE refunds
+ SET refund_status = :refundStatus
+ WHERE id = :id;
+>>
+
+getRefund() ::= <<
+ SELECT <refundFields()>
+ FROM refunds
+ WHERE id = :id;
+>>
+
+getRefundsForPayment() ::= <<
+ SELECT <refundFields()>
+ FROM refunds
+ WHERE payment_id = :paymentId;
+>>
+
+getRefundsForAccount() ::= <<
+ SELECT <refundFields()>
+ FROM refunds
+ WHERE account_id = :accountId;
+>>
+
+getRecordId() ::= <<
+ SELECT record_id
+ FROM refunds
+ WHERE id = :id;
+>>
+
+historyFields(prefix) ::= <<
+ <prefix>record_id,
+ <prefix>id,
+ <prefix>account_id,
+ <prefix>payment_id,
+ <prefix>amount,
+ <prefix>currency,
+ <prefix>is_adjusted,
+ <prefix>refund_status,
+ <prefix>created_by,
+ <prefix>created_date,
+ <prefix>updated_by,
+ <prefix>updated_date
+>>
+
+insertHistoryFromTransaction() ::= <<
+ INSERT INTO refund_history (<historyFields()>)
+ VALUES (:recordId, :id, :accountId, :paymentId, :amount, :currency, :isAdjusted, :refundStatus, :userName, :createdDate, :userName, :createdDate);
+>>
+
+getHistoryRecordId() ::= <<
+ SELECT MAX(history_record_id)
+ FROM payment_method_history
+ WHERE record_id = :recordId;
+>>
+
+auditFields(prefix) ::= <<
+ <prefix>table_name,
+ <prefix>record_id,
+ <prefix>change_type,
+ <prefix>change_date,
+ <prefix>changed_by,
+ <prefix>reason_code,
+ <prefix>comments,
+ <prefix>user_token
+>>
+
+insertAuditFromTransaction() ::= <<
+ INSERT INTO audit_log(<auditFields()>)
+ VALUES(:tableName, :recordId, :changeType, :createdDate, :userName, :reasonCode, :comment, :userToken);
+>>
diff --git a/payment/src/main/resources/com/ning/billing/payment/ddl.sql b/payment/src/main/resources/com/ning/billing/payment/ddl.sql
index b8fa010..a652b58 100644
--- a/payment/src/main/resources/com/ning/billing/payment/ddl.sql
+++ b/payment/src/main/resources/com/ning/billing/payment/ddl.sql
@@ -1,4 +1,5 @@
+
DROP TABLE IF EXISTS payments;
CREATE TABLE payments (
record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
@@ -9,7 +10,8 @@ CREATE TABLE payments (
amount decimal(8,2),
currency char(3),
effective_date datetime,
- payment_status varchar(50),
+ payment_status varchar(50),
+ external_payment_ref_id varchar(64),
created_by varchar(50) NOT NULL,
created_date datetime NOT NULL,
updated_by varchar(50) NOT NULL,
@@ -31,7 +33,8 @@ CREATE TABLE payment_history (
amount decimal(8,2),
currency char(3),
effective_date datetime,
- payment_status varchar(50),
+ payment_status varchar(50),
+ external_payment_ref_id varchar(64),
created_by varchar(50) NOT NULL,
created_date datetime NOT NULL,
updated_by varchar(50) NOT NULL,
@@ -112,6 +115,46 @@ CREATE TABLE payment_method_history (
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE UNIQUE INDEX payment_method_history_record_id ON payment_method_history(record_id);
+DROP TABLE IF EXISTS refunds;
+CREATE TABLE refunds (
+ record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
+ id char(36) NOT NULL,
+ account_id char(36) COLLATE utf8_bin NOT NULL,
+ payment_id char(36) COLLATE utf8_bin NOT NULL,
+ amount decimal(8,2),
+ currency char(3),
+ is_adjusted tinyint(1),
+ refund_status varchar(50),
+ created_by varchar(50) NOT NULL,
+ created_date datetime NOT NULL,
+ updated_by varchar(50) NOT NULL,
+ updated_date datetime NOT NULL,
+ PRIMARY KEY (record_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
+CREATE UNIQUE INDEX refunds_id ON refunds(id);
+CREATE INDEX refunds_pay ON refunds(payment_id);
+CREATE INDEX refunds_accnt ON refunds(account_id);
+
+DROP TABLE IF EXISTS refund_history;
+CREATE TABLE refund_history (
+ history_record_id int(11) unsigned NOT NULL AUTO_INCREMENT,
+ record_id int(11) unsigned NOT NULL,
+ id char(36) NOT NULL,
+ account_id char(36) COLLATE utf8_bin NOT NULL,
+ payment_id char(36) COLLATE utf8_bin NOT NULL,
+ amount decimal(8,2),
+ currency char(3),
+ is_adjusted tinyint(1),
+ refund_status varchar(50),
+ created_by varchar(50) NOT NULL,
+ created_date datetime NOT NULL,
+ updated_by varchar(50) NOT NULL,
+ updated_date datetime NOT NULL,
+ PRIMARY KEY (history_record_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
+CREATE INDEX refund_history_record_id ON refund_history(record_id);
+
+
diff --git a/payment/src/test/java/com/ning/billing/payment/api/TestEventJson.java b/payment/src/test/java/com/ning/billing/payment/api/TestEventJson.java
index 371f7b1..fd710e5 100644
--- a/payment/src/test/java/com/ning/billing/payment/api/TestEventJson.java
+++ b/payment/src/test/java/com/ning/billing/payment/api/TestEventJson.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.payment.api;
import java.math.BigDecimal;
@@ -22,12 +23,13 @@ import org.joda.time.DateTime;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.payment.PaymentTestSuite;
import com.ning.billing.util.jackson.ObjectMapper;
-public class TestEventJson {
+public class TestEventJson extends PaymentTestSuite {
private final ObjectMapper mapper = new ObjectMapper();
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testPaymentErrorEvent() throws Exception {
final PaymentErrorEvent e = new DefaultPaymentErrorEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "no message", UUID.randomUUID());
final String json = mapper.writeValueAsString(e);
@@ -37,9 +39,9 @@ public class TestEventJson {
Assert.assertTrue(obj.equals(e));
}
- @Test(groups = {"fast"})
+ @Test(groups = "fast")
public void testPaymentInfoEvent() throws Exception {
- final PaymentInfoEvent e = new DefaultPaymentInfoEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), new BigDecimal(12.9), new Integer(13), PaymentStatus.SUCCESS, UUID.randomUUID(), new DateTime());
+ final PaymentInfoEvent e = new DefaultPaymentInfoEvent(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), new BigDecimal(12.9), new Integer(13), PaymentStatus.SUCCESS, "ext-ref-12345", UUID.randomUUID(), new DateTime());
final String json = mapper.writeValueAsString(e);
final Class<?> clazz = Class.forName(DefaultPaymentInfoEvent.class.getName());
diff --git a/payment/src/test/java/com/ning/billing/payment/api/TestPaymentApi.java b/payment/src/test/java/com/ning/billing/payment/api/TestPaymentApi.java
index df8ef98..3d0d55a 100644
--- a/payment/src/test/java/com/ning/billing/payment/api/TestPaymentApi.java
+++ b/payment/src/test/java/com/ning/billing/payment/api/TestPaymentApi.java
@@ -23,6 +23,7 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
+import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
@@ -38,11 +39,10 @@ import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoicePaymentApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.mock.glue.MockJunctionModule;
import com.ning.billing.payment.MockRecurringInvoiceItem;
+import com.ning.billing.payment.PaymentTestSuite;
import com.ning.billing.payment.TestHelper;
import com.ning.billing.payment.api.Payment.PaymentAttempt;
import com.ning.billing.payment.glue.PaymentTestModuleWithMocks;
@@ -62,9 +62,7 @@ import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@Guice(modules = {PaymentTestModuleWithMocks.class, MockClockModule.class, MockJunctionModule.class, CallContextModule.class})
-@Test(groups = "fast")
-public class TestPaymentApi {
-
+public class TestPaymentApi extends PaymentTestSuite {
private static final Logger log = LoggerFactory.getLogger(TestPaymentApi.class);
@Inject
@@ -82,29 +80,27 @@ public class TestPaymentApi {
private Account account;
-
@Inject
public TestPaymentApi(final Clock clock) {
context = new DefaultCallContext("Payment Tests", CallOrigin.INTERNAL, UserType.SYSTEM, clock);
}
- @BeforeClass
+ @BeforeClass(groups = "fast")
public void setupClass() throws Exception {
account = testHelper.createTestAccount("yoyo.yahoo.com");
}
- @BeforeMethod(alwaysRun = true)
+ @BeforeMethod(groups = "fast")
public void setUp() throws EventBusException {
eventBus.start();
}
- @AfterMethod(alwaysRun = true)
+ @AfterMethod(groups = "fast")
public void tearDown() throws EventBusException {
eventBus.stop();
}
-
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testSimplePaymentWithNoAmount() throws Exception {
final BigDecimal invoiceAmount = new BigDecimal("10.0011");
final BigDecimal requestedAmount = null;
@@ -113,7 +109,7 @@ public class TestPaymentApi {
testSimplePayment(invoiceAmount, requestedAmount, expectedAmount);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testSimplePaymentWithInvoiceAmount() throws Exception {
final BigDecimal invoiceAmount = new BigDecimal("10.0011");
final BigDecimal requestedAmount = invoiceAmount;
@@ -122,7 +118,7 @@ public class TestPaymentApi {
testSimplePayment(invoiceAmount, requestedAmount, expectedAmount);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testSimplePaymentWithLowerAmount() throws Exception {
final BigDecimal invoiceAmount = new BigDecimal("10.0011");
final BigDecimal requestedAmount = new BigDecimal("8.0091");
@@ -131,7 +127,7 @@ public class TestPaymentApi {
testSimplePayment(invoiceAmount, requestedAmount, expectedAmount);
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testSimplePaymentWithInvalidAmount() throws Exception {
final BigDecimal invoiceAmount = new BigDecimal("10.0011");
final BigDecimal requestedAmount = new BigDecimal("80.0091");
@@ -140,18 +136,13 @@ public class TestPaymentApi {
testSimplePayment(invoiceAmount, requestedAmount, expectedAmount);
}
-
private void testSimplePayment(final BigDecimal invoiceAmount, final BigDecimal requestedAmount, final BigDecimal expectedAmount) throws Exception {
-
- ((ZombieControl) invoicePaymentApi).addResult("notifyOfPaymentAttempt", BrainDeadProxyFactory.ZOMBIE_VOID);
-
final DateTime now = new DateTime(DateTimeZone.UTC);
final Invoice invoice = testHelper.createTestInvoice(account, now, Currency.USD);
final UUID subscriptionId = UUID.randomUUID();
final UUID bundleId = UUID.randomUUID();
-
invoice.addInvoiceItem(new MockRecurringInvoiceItem(invoice.getId(), account.getId(),
subscriptionId,
bundleId,
@@ -188,20 +179,17 @@ public class TestPaymentApi {
}
}
- @Test(enabled = true)
+ @Test(groups = "fast")
public void testPaymentMethods() throws Exception {
-
List<PaymentMethod> methods = paymentApi.getPaymentMethods(account, false);
assertEquals(methods.size(), 1);
final PaymentMethod initDefaultMethod = methods.get(0);
assertEquals(initDefaultMethod.getId(), account.getPaymentMethodId());
-
- //((ZombieControl)accountApi).addResult("updateAccount", );
final PaymentMethodPlugin newPaymenrMethod = new DefaultNoOpPaymentMethodPlugin(UUID.randomUUID().toString(), true, null);
final UUID newPaymentMethodId = paymentApi.addPaymentMethod(PaymentTestModuleWithMocks.PLUGIN_TEST_NAME, account, true, newPaymenrMethod, context);
- ((ZombieControl) account).addResult("getPaymentMethodId", newPaymentMethodId);
+ Mockito.when(account.getPaymentMethodId()).thenReturn(newPaymentMethodId);
methods = paymentApi.getPaymentMethods(account, false);
assertEquals(methods.size(), 2);
@@ -220,6 +208,4 @@ public class TestPaymentApi {
methods = paymentApi.getPaymentMethods(account, false);
assertEquals(methods.size(), 1);
}
-
-
}
diff --git a/payment/src/test/java/com/ning/billing/payment/dao/MockPaymentDao.java b/payment/src/test/java/com/ning/billing/payment/dao/MockPaymentDao.java
index fb6a281..c1ff2b7 100644
--- a/payment/src/test/java/com/ning/billing/payment/dao/MockPaymentDao.java
+++ b/payment/src/test/java/com/ning/billing/payment/dao/MockPaymentDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.UUID;
import com.ning.billing.payment.api.PaymentStatus;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
import com.ning.billing.util.callcontext.CallContext;
public class MockPaymentDao implements PaymentDao {
@@ -33,7 +34,7 @@ public class MockPaymentDao implements PaymentDao {
@Override
public PaymentModelDao insertPaymentWithAttempt(final PaymentModelDao paymentInfo, final PaymentAttemptModelDao attempt,
- final boolean scheduleTimeoutRetry, final CallContext context) {
+ final CallContext context) {
synchronized (this) {
payments.put(paymentInfo.getId(), paymentInfo);
attempts.put(attempt.getId(), attempt);
@@ -43,7 +44,7 @@ public class MockPaymentDao implements PaymentDao {
@Override
public PaymentAttemptModelDao insertNewAttemptForPayment(final UUID paymentId,
- final PaymentAttemptModelDao attempt, final boolean scheduleTimeoutRetry, final CallContext context) {
+ final PaymentAttemptModelDao attempt, final CallContext context) {
synchronized (this) {
attempts.put(attempt.getId(), attempt);
}
@@ -52,7 +53,7 @@ public class MockPaymentDao implements PaymentDao {
@Override
public void updateStatusForPaymentWithAttempt(final UUID paymentId,
- final PaymentStatus paymentStatus, final String paymentError, final UUID attemptId,
+ final PaymentStatus paymentStatus, final String paymentError, final String extpaymentRefId, final UUID attemptId,
final CallContext context) {
synchronized (this) {
final PaymentModelDao entry = payments.remove(paymentId);
@@ -67,18 +68,6 @@ public class MockPaymentDao implements PaymentDao {
}
@Override
- public void updateStatusForPayment(final UUID paymentId,
- final PaymentStatus paymentStatus, final CallContext context) {
- synchronized (this) {
- final PaymentModelDao entry = payments.remove(paymentId);
- if (entry != null) {
- payments.put(paymentId, new PaymentModelDao(entry, paymentStatus));
- }
- }
- }
-
-
- @Override
public PaymentAttemptModelDao getPaymentAttempt(final UUID attemptId) {
return attempts.get(attemptId);
}
@@ -167,4 +156,36 @@ public class MockPaymentDao implements PaymentDao {
}
}
}
+
+ @Override
+ public RefundModelDao insertRefund(RefundModelDao refundInfo,
+ CallContext context) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void updateRefundStatus(UUID refundId, RefundStatus status,
+ CallContext context) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public RefundModelDao getRefund(UUID refundId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<RefundModelDao> getRefundsForPayment(UUID paymentId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List<RefundModelDao> getRefundsForAccount(UUID accountId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/payment/src/test/java/com/ning/billing/payment/dao/TestPaymentDao.java b/payment/src/test/java/com/ning/billing/payment/dao/TestPaymentDao.java
index 10c2ac5..74cd804 100644
--- a/payment/src/test/java/com/ning/billing/payment/dao/TestPaymentDao.java
+++ b/payment/src/test/java/com/ning/billing/payment/dao/TestPaymentDao.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.payment.dao;
import java.io.IOException;
@@ -29,21 +30,25 @@ import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.payment.PaymentTestSuiteWithEmbeddedDB;
import com.ning.billing.payment.api.PaymentStatus;
+import com.ning.billing.payment.dao.RefundModelDao.RefundStatus;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.TestCallContext;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.DefaultClock;
-import com.ning.billing.util.io.IOUtils;
-import static junit.framework.Assert.assertNull;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.fail;
-public class TestPaymentDao {
+public class TestPaymentDao extends PaymentTestSuiteWithEmbeddedDB {
private static final CallContext context = new TestCallContext("PaymentTests");
private PaymentDao paymentDao;
@@ -51,24 +56,17 @@ public class TestPaymentDao {
private IDBI dbi;
private Clock clock;
- @BeforeSuite(groups = {"slow"})
- public void startMysql() throws IOException {
- final String paymentddl = IOUtils.toString(MysqlTestingHelper.class.getResourceAsStream("/com/ning/billing/payment/ddl.sql"));
- final String utilddl = IOUtils.toString(MysqlTestingHelper.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
+ @BeforeSuite(groups = "slow")
+ public void setup() throws IOException {
clock = new DefaultClock();
setupDb();
- helper.startMysql();
- helper.initDb(paymentddl);
- helper.initDb(utilddl);
-
paymentDao = new AuditedPaymentDao(dbi, null);
}
private void setupDb() {
- helper = new MysqlTestingHelper();
+ helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
if (helper.isUsingLocalInstance()) {
final DbiConfig config = new ConfigurationObjectFactory(System.getProperties()).build(DbiConfig.class);
final DBIProvider provider = new DBIProvider(config);
@@ -78,34 +76,70 @@ public class TestPaymentDao {
}
}
- @AfterSuite(groups = {"slow"})
- public void stopMysql() {
- helper.stopMysql();
- }
+ @Test(groups = "slow")
+ public void testRefund() {
+ final UUID accountId = UUID.randomUUID();
+ final UUID paymentId1 = UUID.randomUUID();
+ final BigDecimal amount1 = new BigDecimal(13);
+ final Currency currency = Currency.USD;
- @BeforeTest(groups = {"slow"})
- public void cleanupDb() {
- helper.cleanupAllTables();
+ RefundModelDao refund1 = new RefundModelDao(accountId, paymentId1, amount1, currency, true);
+
+ paymentDao.insertRefund(refund1, context);
+ RefundModelDao refundCheck = paymentDao.getRefund(refund1.getId());
+ assertNotNull(refundCheck);
+ assertEquals(refundCheck.getAccountId(), accountId);
+ assertEquals(refundCheck.getPaymentId(), paymentId1);
+ assertEquals(refundCheck.getAmount().compareTo(amount1), 0);
+ assertEquals(refundCheck.getCurrency(), currency);
+ assertEquals(refundCheck.isAdjsuted(), true);
+ assertEquals(refundCheck.getRefundStatus(), RefundStatus.CREATED);
+
+ final BigDecimal amount2 = new BigDecimal(7.00);
+ final UUID paymentId2 = UUID.randomUUID();
+
+ RefundModelDao refund2 = new RefundModelDao(accountId, paymentId2, amount2, currency, true);
+ paymentDao.insertRefund(refund2, context);
+ paymentDao.updateRefundStatus(refund2.getId(), RefundStatus.COMPLETED, context);
+
+ List<RefundModelDao> refundChecks = paymentDao.getRefundsForPayment(paymentId1);
+ assertEquals(refundChecks.size(), 1);
+
+ refundChecks = paymentDao.getRefundsForPayment(paymentId2);
+ assertEquals(refundChecks.size(), 1);
+
+ refundChecks = paymentDao.getRefundsForAccount(accountId);
+ assertEquals(refundChecks.size(), 2);
+ for (RefundModelDao cur : refundChecks) {
+ if (cur.getPaymentId().equals(paymentId1)) {
+ assertEquals(cur.getAmount().compareTo(amount1), 0);
+ assertEquals(cur.getRefundStatus(), RefundStatus.CREATED);
+ } else if (cur.getPaymentId().equals(paymentId2)) {
+ assertEquals(cur.getAmount().compareTo(amount2), 0);
+ assertEquals(cur.getRefundStatus(), RefundStatus.COMPLETED);
+ } else {
+ fail("Unexpected refund");
+ }
+ }
}
-
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testUpdateStatus() {
-
final UUID accountId = UUID.randomUUID();
final UUID invoiceId = UUID.randomUUID();
+ final UUID paymentMethodId = UUID.randomUUID();
final BigDecimal amount = new BigDecimal(13);
final Currency currency = Currency.USD;
final DateTime effectiveDate = clock.getUTCNow();
- final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, amount, currency, effectiveDate);
+ final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, paymentMethodId, amount, currency, effectiveDate);
final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(accountId, invoiceId, payment.getId(), clock.getUTCNow(), amount);
- PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, true, context);
+ PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, context);
final PaymentStatus paymentStatus = PaymentStatus.SUCCESS;
final String paymentError = "No error";
- paymentDao.updateStatusForPaymentWithAttempt(payment.getId(), paymentStatus, paymentError, attempt.getId(), context);
+ paymentDao.updateStatusForPaymentWithAttempt(payment.getId(), paymentStatus, paymentError, null, attempt.getId(), context);
final List<PaymentModelDao> payments = paymentDao.getPaymentsForInvoice(invoiceId);
assertEquals(payments.size(), 1);
@@ -113,7 +147,7 @@ public class TestPaymentDao {
assertEquals(savedPayment.getId(), payment.getId());
assertEquals(savedPayment.getAccountId(), accountId);
assertEquals(savedPayment.getInvoiceId(), invoiceId);
- assertEquals(savedPayment.getPaymentMethodId(), null);
+ assertEquals(savedPayment.getPaymentMethodId(), paymentMethodId);
assertEquals(savedPayment.getAmount().compareTo(amount), 0);
assertEquals(savedPayment.getCurrency(), currency);
assertEquals(savedPayment.getEffectiveDate().compareTo(effectiveDate), 0);
@@ -131,29 +165,28 @@ public class TestPaymentDao {
assertEquals(savedAttempt.getRequestedAmount().compareTo(amount), 0);
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testPaymentWithAttempt() {
-
final UUID accountId = UUID.randomUUID();
final UUID invoiceId = UUID.randomUUID();
+ final UUID paymentMethodId = UUID.randomUUID();
final BigDecimal amount = new BigDecimal(13);
final Currency currency = Currency.USD;
final DateTime effectiveDate = clock.getUTCNow();
- final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, amount, currency, effectiveDate);
+ final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, paymentMethodId, amount, currency, effectiveDate);
final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(accountId, invoiceId, payment.getId(), clock.getUTCNow(), amount);
- PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, true, context);
+ PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, attempt, context);
assertEquals(savedPayment.getId(), payment.getId());
assertEquals(savedPayment.getAccountId(), accountId);
assertEquals(savedPayment.getInvoiceId(), invoiceId);
- assertEquals(savedPayment.getPaymentMethodId(), null);
+ assertEquals(savedPayment.getPaymentMethodId(), paymentMethodId);
assertEquals(savedPayment.getAmount().compareTo(amount), 0);
assertEquals(savedPayment.getCurrency(), currency);
assertEquals(savedPayment.getEffectiveDate().compareTo(effectiveDate), 0);
assertEquals(savedPayment.getPaymentStatus(), PaymentStatus.UNKNOWN);
-
PaymentAttemptModelDao savedAttempt = paymentDao.getPaymentAttempt(attempt.getId());
assertEquals(savedAttempt.getId(), attempt.getId());
assertEquals(savedAttempt.getPaymentId(), payment.getId());
@@ -167,7 +200,7 @@ public class TestPaymentDao {
assertEquals(savedPayment.getId(), payment.getId());
assertEquals(savedPayment.getAccountId(), accountId);
assertEquals(savedPayment.getInvoiceId(), invoiceId);
- assertEquals(savedPayment.getPaymentMethodId(), null);
+ assertEquals(savedPayment.getPaymentMethodId(), paymentMethodId);
assertEquals(savedPayment.getAmount().compareTo(amount), 0);
assertEquals(savedPayment.getCurrency(), currency);
assertEquals(savedPayment.getEffectiveDate().compareTo(effectiveDate), 0);
@@ -184,21 +217,22 @@ public class TestPaymentDao {
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testNewAttempt() {
final UUID accountId = UUID.randomUUID();
final UUID invoiceId = UUID.randomUUID();
+ final UUID paymentMethodId = UUID.randomUUID();
final BigDecimal amount = new BigDecimal(13);
final Currency currency = Currency.USD;
final DateTime effectiveDate = clock.getUTCNow();
- final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, amount, currency, effectiveDate);
+ final PaymentModelDao payment = new PaymentModelDao(accountId, invoiceId, paymentMethodId, amount, currency, effectiveDate);
final PaymentAttemptModelDao firstAttempt = new PaymentAttemptModelDao(accountId, invoiceId, payment.getId(), clock.getUTCNow(), amount);
- PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, firstAttempt, true, context);
+ PaymentModelDao savedPayment = paymentDao.insertPaymentWithAttempt(payment, firstAttempt, context);
final BigDecimal newAmount = new BigDecimal(15.23).setScale(2, RoundingMode.HALF_EVEN);
final PaymentAttemptModelDao secondAttempt = new PaymentAttemptModelDao(accountId, invoiceId, payment.getId(), clock.getUTCNow(), newAmount);
- paymentDao.insertNewAttemptForPayment(payment.getId(), secondAttempt, true, context);
+ paymentDao.insertNewAttemptForPayment(payment.getId(), secondAttempt, context);
final List<PaymentModelDao> payments = paymentDao.getPaymentsForInvoice(invoiceId);
assertEquals(payments.size(), 1);
@@ -206,7 +240,7 @@ public class TestPaymentDao {
assertEquals(savedPayment.getId(), payment.getId());
assertEquals(savedPayment.getAccountId(), accountId);
assertEquals(savedPayment.getInvoiceId(), invoiceId);
- assertEquals(savedPayment.getPaymentMethodId(), null);
+ assertEquals(savedPayment.getPaymentMethodId(), paymentMethodId);
assertEquals(savedPayment.getAmount().compareTo(newAmount), 0);
assertEquals(savedPayment.getCurrency(), currency);
assertEquals(savedPayment.getEffectiveDate().compareTo(effectiveDate), 0);
@@ -222,7 +256,6 @@ public class TestPaymentDao {
assertEquals(savedAttempt1.getPaymentError(), null);
assertEquals(savedAttempt1.getRequestedAmount().compareTo(amount), 0);
-
final PaymentAttemptModelDao savedAttempt2 = attempts.get(1);
assertEquals(savedAttempt2.getPaymentId(), payment.getId());
assertEquals(savedAttempt2.getAccountId(), accountId);
@@ -232,7 +265,7 @@ public class TestPaymentDao {
assertEquals(savedAttempt2.getRequestedAmount().compareTo(newAmount), 0);
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testPaymentMethod() {
final UUID paymentMethodId = UUID.randomUUID();
@@ -262,7 +295,5 @@ public class TestPaymentDao {
final PaymentMethodModelDao deletedPaymentMethod = paymentDao.getPaymentMethod(paymentMethodId);
assertNull(deletedPaymentMethod);
-
-
}
}
diff --git a/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithEmbeddedDb.java b/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithEmbeddedDb.java
index 4937184..1d2ed05 100644
--- a/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithEmbeddedDb.java
+++ b/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithEmbeddedDb.java
@@ -17,15 +17,17 @@
package com.ning.billing.payment.glue;
import java.util.HashMap;
+import java.util.UUID;
+
+import org.mockito.Mockito;
import com.google.inject.Provider;
import com.ning.billing.config.PaymentConfig;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.payment.provider.MockPaymentProviderPluginModule;
import com.ning.billing.util.api.TagUserApi;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.InMemoryBus;
+import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.glue.GlobalLockerModule;
import com.ning.billing.util.notificationq.DefaultNotificationQueueService;
import com.ning.billing.util.notificationq.NotificationQueueService;
@@ -35,11 +37,10 @@ public class PaymentTestModuleWithEmbeddedDb extends PaymentModule {
public static class MockTagApiProvider implements Provider<TagUserApi> {
@Override
public TagUserApi get() {
- final TagUserApi api = BrainDeadProxyFactory.createBrainDeadProxyFor(TagUserApi.class);
- ((ZombieControl) api).addResult("getTags", new HashMap<String, Tag>());
+ final TagUserApi api = Mockito.mock(TagUserApi.class);
+ Mockito.when(api.getTags(Mockito.<UUID>any(), Mockito.<ObjectType>any())).thenReturn(new HashMap<String, Tag>());
return api;
}
-
}
@Override
diff --git a/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithMocks.java b/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithMocks.java
index ca497f6..c253ff3 100644
--- a/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithMocks.java
+++ b/payment/src/test/java/com/ning/billing/payment/glue/PaymentTestModuleWithMocks.java
@@ -20,22 +20,26 @@ import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
+import java.util.UUID;
+import org.mockito.Mockito;
import org.skife.config.ConfigSource;
import org.skife.config.SimplePropertyConfigSource;
+import com.google.common.collect.ImmutableMap;
import com.ning.billing.config.PaymentConfig;
import com.ning.billing.mock.glue.MockInvoiceModule;
import com.ning.billing.mock.glue.MockNotificationQueueModule;
-import com.ning.billing.mock.glue.TestDbiModule;
import com.ning.billing.payment.dao.MockPaymentDao;
import com.ning.billing.payment.dao.PaymentDao;
import com.ning.billing.payment.provider.MockPaymentProviderPluginModule;
+import com.ning.billing.util.api.TagUserApi;
+import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.globallocker.GlobalLocker;
import com.ning.billing.util.globallocker.MockGlobalLocker;
import com.ning.billing.util.glue.BusModule;
import com.ning.billing.util.glue.BusModule.BusType;
-import com.ning.billing.util.glue.TagStoreModule;
+import com.ning.billing.util.tag.Tag;
import static org.testng.Assert.assertNotNull;
@@ -89,8 +93,11 @@ public class PaymentTestModuleWithMocks extends PaymentModule {
install(new BusModule(BusType.MEMORY));
install(new MockNotificationQueueModule());
install(new MockInvoiceModule());
- install(new TestDbiModule());
- install(new TagStoreModule());
+
+ final TagUserApi tagUserApi = Mockito.mock(TagUserApi.class);
+ bind(TagUserApi.class).toInstance(tagUserApi);
+ Mockito.when(tagUserApi.getTags(Mockito.<UUID>any(), Mockito.<ObjectType>any())).thenReturn(ImmutableMap.<String, Tag>of());
+
bind(GlobalLocker.class).to(MockGlobalLocker.class).asEagerSingleton();
}
}
diff --git a/payment/src/test/java/com/ning/billing/payment/MockInvoice.java b/payment/src/test/java/com/ning/billing/payment/MockInvoice.java
index 9cabab5..5443dcf 100644
--- a/payment/src/test/java/com/ning/billing/payment/MockInvoice.java
+++ b/payment/src/test/java/com/ning/billing/payment/MockInvoice.java
@@ -150,25 +150,25 @@ public class MockInvoice extends EntityBase implements Invoice {
}
@Override
- public DateTime getLastPaymentAttempt() {
- DateTime lastPaymentAttempt = null;
+ public DateTime getLastPaymentDate() {
+ DateTime lastPayment = null;
- for (final InvoicePayment paymentAttempt : payments) {
- final DateTime paymentAttemptDate = paymentAttempt.getPaymentAttemptDate();
- if (lastPaymentAttempt == null) {
- lastPaymentAttempt = paymentAttemptDate;
+ for (final InvoicePayment payment : payments) {
+ final DateTime paymentDate = payment.getPaymentDate();
+ if (lastPayment == null) {
+ lastPayment = paymentDate;
}
- if (lastPaymentAttempt.isBefore(paymentAttemptDate)) {
- lastPaymentAttempt = paymentAttemptDate;
+ if (lastPayment.isBefore(paymentDate)) {
+ lastPayment = paymentDate;
}
}
- return lastPaymentAttempt;
+ return lastPayment;
}
@Override
- public BigDecimal getAmountPaid() {
+ public BigDecimal getPaidAmount() {
BigDecimal amountPaid = BigDecimal.ZERO;
for (final InvoicePayment payment : payments) {
if (payment.getAmount() != null) {
@@ -179,11 +179,11 @@ public class MockInvoice extends EntityBase implements Invoice {
}
@Override
- public BigDecimal getAmountCharged() {
+ public BigDecimal getChargedAmount() {
BigDecimal result = BigDecimal.ZERO;
for (final InvoiceItem i : invoiceItems) {
- if (!i.getInvoiceItemType().equals(InvoiceItemType.CREDIT)) {
+ if (!i.getInvoiceItemType().equals(InvoiceItemType.CBA_ADJ)) {
result = result.add(i.getAmount());
}
}
@@ -191,11 +191,11 @@ public class MockInvoice extends EntityBase implements Invoice {
}
@Override
- public BigDecimal getAmountCredited() {
+ public BigDecimal getCreditAdjAmount() {
BigDecimal result = BigDecimal.ZERO;
for (final InvoiceItem i : invoiceItems) {
- if (i.getInvoiceItemType().equals(InvoiceItemType.CREDIT)) {
+ if (i.getInvoiceItemType().equals(InvoiceItemType.CBA_ADJ)) {
result = result.add(i.getAmount());
}
}
@@ -204,7 +204,7 @@ public class MockInvoice extends EntityBase implements Invoice {
@Override
public BigDecimal getBalance() {
- return getAmountCharged().subtract(getAmountPaid().subtract(getAmountCredited()));
+ return getChargedAmount().subtract(getPaidAmount());
}
@Override
@@ -213,7 +213,7 @@ public class MockInvoice extends EntityBase implements Invoice {
return false;
}
- final DateTime lastPaymentAttempt = getLastPaymentAttempt();
+ final DateTime lastPaymentAttempt = getLastPaymentDate();
if (lastPaymentAttempt == null) {
return true;
}
@@ -223,7 +223,22 @@ public class MockInvoice extends EntityBase implements Invoice {
@Override
public String toString() {
- return "DefaultInvoice [items=" + invoiceItems + ", payments=" + payments + ", id=" + id + ", accountId=" + accountId + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", currency=" + currency + ", amountPaid=" + getAmountPaid() + ", lastPaymentAttempt=" + getLastPaymentAttempt() + "]";
+ return "DefaultInvoice [items=" + invoiceItems + ", payments=" + payments + ", id=" + id + ", accountId=" + accountId + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", currency=" + currency + ", amountPaid=" + getPaidAmount() + ", lastPaymentDate=" + getLastPaymentDate() + "]";
+ }
+
+ @Override
+ public BigDecimal getCBAAmount() {
+ return null;
+ }
+
+ @Override
+ public BigDecimal getTotalAdjAmount() {
+ return null;
+ }
+
+ @Override
+ public BigDecimal getRefundAdjAmount() {
+ return null;
}
}
diff --git a/payment/src/test/java/com/ning/billing/payment/MockRecurringInvoiceItem.java b/payment/src/test/java/com/ning/billing/payment/MockRecurringInvoiceItem.java
index 534bfb2..054d995 100644
--- a/payment/src/test/java/com/ning/billing/payment/MockRecurringInvoiceItem.java
+++ b/payment/src/test/java/com/ning/billing/payment/MockRecurringInvoiceItem.java
@@ -113,6 +113,7 @@ public class MockRecurringInvoiceItem extends EntityBase implements InvoiceItem
return bundleId;
}
+ @Override
public UUID getAccountId() {
return accountId;
}
@@ -158,16 +159,12 @@ public class MockRecurringInvoiceItem extends EntityBase implements InvoiceItem
}
@Override
- public InvoiceItem asReversingItem() {
- throw new UnsupportedOperationException();
- }
-
- @Override
public String getDescription() {
return String.format("%s from %s to %s", phaseName, startDate.toString(), endDate.toString());
}
- public UUID getReversedItemId() {
+ @Override
+ public UUID getLinkedItemId() {
return reversedItemId;
}
@@ -175,6 +172,7 @@ public class MockRecurringInvoiceItem extends EntityBase implements InvoiceItem
return (reversedItemId != null);
}
+ @Override
public BigDecimal getRate() {
return rate;
}
diff --git a/payment/src/test/java/com/ning/billing/payment/PaymentTestSuite.java b/payment/src/test/java/com/ning/billing/payment/PaymentTestSuite.java
new file mode 100644
index 0000000..1baac9d
--- /dev/null
+++ b/payment/src/test/java/com/ning/billing/payment/PaymentTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.payment;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class PaymentTestSuite extends KillbillTestSuite {
+}
diff --git a/payment/src/test/java/com/ning/billing/payment/PaymentTestSuiteWithEmbeddedDB.java b/payment/src/test/java/com/ning/billing/payment/PaymentTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..50e82a6
--- /dev/null
+++ b/payment/src/test/java/com/ning/billing/payment/PaymentTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.payment;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class PaymentTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/payment/src/test/java/com/ning/billing/payment/TestHelper.java b/payment/src/test/java/com/ning/billing/payment/TestHelper.java
index 6a9e422..abeaa54 100644
--- a/payment/src/test/java/com/ning/billing/payment/TestHelper.java
+++ b/payment/src/test/java/com/ning/billing/payment/TestHelper.java
@@ -19,6 +19,7 @@ package com.ning.billing.payment;
import java.util.UUID;
import org.joda.time.DateTime;
+import org.mockito.Mockito;
import com.google.inject.Inject;
import com.ning.billing.account.api.Account;
@@ -28,8 +29,6 @@ import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoicePaymentApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.payment.api.PaymentApi;
import com.ning.billing.payment.api.PaymentMethodPlugin;
import com.ning.billing.payment.glue.PaymentTestModuleWithMocks;
@@ -57,7 +56,6 @@ public class TestHelper {
context = factory.createCallContext("Princess Buttercup", CallOrigin.TEST, UserType.TEST);
}
-
public Invoice createTestInvoice(final Account account,
final DateTime targetDate,
final Currency currency,
@@ -81,7 +79,7 @@ public class TestHelper {
}
}
- ((ZombieControl) invoicePaymentApi).addResult("getInvoice", invoice);
+ Mockito.when(invoicePaymentApi.getInvoice(invoice.getId())).thenReturn(invoice);
final InvoiceCreationEvent event = new MockInvoiceCreationEvent(invoice.getId(), invoice.getAccountId(),
invoice.getBalance(), invoice.getCurrency(),
invoice.getInvoiceDate(),
@@ -95,34 +93,20 @@ public class TestHelper {
final String name = "First" + UUID.randomUUID().toString() + " " + "Last" + UUID.randomUUID().toString();
final String externalKey = UUID.randomUUID().toString();
- final Account account = BrainDeadProxyFactory.createBrainDeadProxyFor(Account.class);
- final ZombieControl zombie = (ZombieControl) account;
- zombie.addResult("getId", UUID.randomUUID());
- zombie.addResult("getExternalKey", externalKey);
- zombie.addResult("getName", name);
- zombie.addResult("getFirstNameLength", 10);
- zombie.addResult("getPhone", "123-456-7890");
- zombie.addResult("getEmail", email);
- zombie.addResult("getCurrency", Currency.USD);
- zombie.addResult("getBillCycleDay", 1);
- zombie.addResult("isMigrated", false);
- zombie.addResult("isNotifiedForInvoices", false);
- zombie.addResult("getTimeZone", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getLocale", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getAddress1", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getAddress2", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getCompanyName", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getCity", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getStateOrProvince", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getCountry", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getPostalCode", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getPhone", BrainDeadProxyFactory.ZOMBIE_VOID);
- zombie.addResult("getPaymentMethodId", BrainDeadProxyFactory.ZOMBIE_VOID);
-
- ((ZombieControl) accountUserApi).addResult("getAccountById", account);
- ((ZombieControl) accountUserApi).addResult("getAccountByKey", account);
- ((ZombieControl) accountUserApi).addResult("updateAccount", BrainDeadProxyFactory.ZOMBIE_VOID);
- //updateAccount
+ final Account account = Mockito.mock(Account.class);
+ Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
+ Mockito.when(account.getExternalKey()).thenReturn(externalKey);
+ Mockito.when(account.getName()).thenReturn(name);
+ Mockito.when(account.getFirstNameLength()).thenReturn(10);
+ Mockito.when(account.getPhone()).thenReturn("123-456-7890");
+ Mockito.when(account.getEmail()).thenReturn(email);
+ Mockito.when(account.getCurrency()).thenReturn(Currency.USD);
+ Mockito.when(account.getBillCycleDay()).thenReturn(1);
+ Mockito.when(account.isMigrated()).thenReturn(false);
+ Mockito.when(account.isNotifiedForInvoices()).thenReturn(false);
+
+ Mockito.when(accountUserApi.getAccountById(Mockito.<UUID>any())).thenReturn(account);
+ Mockito.when(accountUserApi.getAccountByKey(Mockito.anyString())).thenReturn(account);
final PaymentMethodPlugin pm = new DefaultNoOpPaymentMethodPlugin(UUID.randomUUID().toString(), true, null);
addTestPaymentMethod(account, pm);
@@ -131,8 +115,6 @@ public class TestHelper {
private void addTestPaymentMethod(final Account account, final PaymentMethodPlugin paymentMethodInfo) throws Exception {
final UUID paymentMethodId = paymentApi.addPaymentMethod(PaymentTestModuleWithMocks.PLUGIN_TEST_NAME, account, true, paymentMethodInfo, context);
- final ZombieControl zombie = (ZombieControl) account;
- zombie.addResult("getPaymentMethodId", paymentMethodId);
+ Mockito.when(account.getPaymentMethodId()).thenReturn(paymentMethodId);
}
-
}
diff --git a/payment/src/test/java/com/ning/billing/payment/TestRetryService.java b/payment/src/test/java/com/ning/billing/payment/TestRetryService.java
index b9ab5d0..e8e1580 100644
--- a/payment/src/test/java/com/ning/billing/payment/TestRetryService.java
+++ b/payment/src/test/java/com/ning/billing/payment/TestRetryService.java
@@ -26,7 +26,6 @@ import java.util.concurrent.TimeoutException;
import org.joda.time.DateTime;
import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
@@ -37,8 +36,6 @@ import com.ning.billing.catalog.api.Currency;
import com.ning.billing.config.PaymentConfig;
import com.ning.billing.invoice.api.Invoice;
import com.ning.billing.invoice.api.InvoicePaymentApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
-import com.ning.billing.mock.BrainDeadProxyFactory.ZombieControl;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.mock.glue.MockJunctionModule;
import com.ning.billing.payment.api.Payment;
@@ -67,7 +64,7 @@ import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@Guice(modules = {PaymentTestModuleWithMocks.class, MockClockModule.class, MockJunctionModule.class, CallContextModule.class})
-public class TestRetryService {
+public class TestRetryService extends PaymentTestSuite {
@Inject
private PaymentConfig paymentConfig;
@Inject
@@ -104,7 +101,6 @@ public class TestRetryService {
mockPaymentProviderPlugin.clear();
context = new DefaultCallContext("RetryServiceTests", CallOrigin.INTERNAL, UserType.TEST, clock);
- ((ZombieControl) invoicePaymentApi).addResult("notifyOfPaymentAttempt", BrainDeadProxyFactory.ZOMBIE_VOID);
}
@AfterMethod(groups = "fast")
@@ -137,7 +133,6 @@ public class TestRetryService {
testSchedulesRetryInternal(paymentConfig.getPluginFailureRetryMaxAttempts() + 1, FailureType.PLUGIN_EXCEPTION);
}
-
@Test(groups = "fast")
public void testFailedPaymentWithOneSuccessfulRetry() throws Exception {
testSchedulesRetryInternal(1, FailureType.PAYMENT_FAILURE);
pom.xml 2(+1 -1)
diff --git a/pom.xml b/pom.xml
index aec8629..95bfa61 100644
--- a/pom.xml
+++ b/pom.xml
@@ -17,7 +17,7 @@
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
<packaging>pom</packaging>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<name>killbill</name>
<description>Library for managing recurring subscriptions and the associated billing</description>
<url>http://github.com/ning/killbill</url>
server/pom.xml 2(+1 -1)
diff --git a/server/pom.xml b/server/pom.xml
index 7feeaff..3707d38 100644
--- a/server/pom.xml
+++ b/server/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-server</artifactId>
diff --git a/server/src/main/java/com/ning/billing/server/modules/KillbillServerModule.java b/server/src/main/java/com/ning/billing/server/modules/KillbillServerModule.java
index 74ef8c3..96c8668 100644
--- a/server/src/main/java/com/ning/billing/server/modules/KillbillServerModule.java
+++ b/server/src/main/java/com/ning/billing/server/modules/KillbillServerModule.java
@@ -33,6 +33,7 @@ import com.ning.billing.jaxrs.resources.CatalogResource;
import com.ning.billing.jaxrs.resources.InvoiceResource;
import com.ning.billing.jaxrs.resources.PaymentMethodResource;
import com.ning.billing.jaxrs.resources.PaymentResource;
+import com.ning.billing.jaxrs.resources.RefundResource;
import com.ning.billing.jaxrs.resources.SubscriptionResource;
import com.ning.billing.jaxrs.resources.TagResource;
import com.ning.billing.jaxrs.util.KillbillEventHandler;
@@ -58,7 +59,7 @@ public class KillbillServerModule extends AbstractModule {
installKillbillModules();
}
-
+
protected void configureDao() {
// Load mysql driver if needed
try {
@@ -79,6 +80,7 @@ public class KillbillServerModule extends AbstractModule {
bind(CatalogResource.class).asEagerSingleton();
bind(PaymentMethodResource.class).asEagerSingleton();
bind(PaymentResource.class).asEagerSingleton();
+ bind(RefundResource.class).asEagerSingleton();
bind(KillbillEventHandler.class).asEagerSingleton();
}
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java b/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
index 3e00cdd..6ccdce6 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestAccount.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -16,13 +16,19 @@
package com.ning.billing.jaxrs;
-import javax.ws.rs.core.Response.Status;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import javax.ws.rs.core.Response.Status;
+
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,16 +44,12 @@ import com.ning.billing.jaxrs.json.BundleJsonNoSubscriptions;
import com.ning.billing.jaxrs.json.CustomFieldJson;
import com.ning.billing.jaxrs.json.PaymentJsonSimple;
import com.ning.billing.jaxrs.json.PaymentMethodJson;
+import com.ning.billing.jaxrs.json.RefundJson;
import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
import com.ning.billing.jaxrs.json.TagDefinitionJson;
import com.ning.billing.jaxrs.resources.JaxrsResource;
import com.ning.http.client.Response;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
public class TestAccount extends TestJaxrsBase {
@@ -232,7 +234,7 @@ public class TestAccount extends TestJaxrsBase {
}
@Test(groups = "slow", enabled = true)
- public void testAccountPayments() throws Exception {
+ public void testAccountPaymentsWithRefund() throws Exception {
//clock.setTime(new DateTime(2012, 4, 25, 0, 3, 42, 0));
@@ -249,13 +251,21 @@ public class TestAccount extends TestJaxrsBase {
crappyWaitForLackOfProperSynchonization();
- final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountJson.getAccountId() + "/" + JaxrsResource.PAYMENTS;
+ String uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountJson.getAccountId() + "/" + JaxrsResource.PAYMENTS;
- final Response response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Response response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
- final String baseJson = response.getResponseBody();
- final List<PaymentJsonSimple> objFromJson = mapper.readValue(baseJson, new TypeReference<List<PaymentJsonSimple>>() {});
+ String baseJson = response.getResponseBody();
+ List<PaymentJsonSimple> objFromJson = mapper.readValue(baseJson, new TypeReference<List<PaymentJsonSimple>>() {});
Assert.assertEquals(objFromJson.size(), 1);
+
+ uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountJson.getAccountId() + "/" + JaxrsResource.REFUNDS;
+ response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ baseJson = response.getResponseBody();
+ List<RefundJson> objRefundFromJson = mapper.readValue(baseJson, new TypeReference<List<RefundJson>>() {});
+ Assert.assertEquals(objRefundFromJson.size(), 0);
+
}
@Test(groups = "slow", enabled = true)
@@ -268,7 +278,7 @@ public class TestAccount extends TestJaxrsBase {
final Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(JaxrsResource.QUERY_TAGS, input.getName());
- final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + JaxrsResource.TAGS + "/" + UUID.randomUUID().toString();
+ final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + UUID.randomUUID().toString() + "/" + JaxrsResource.TAGS;
response = doPost(uri, null, queryParams, DEFAULT_HTTP_TIMEOUT_SEC);
assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode());
@@ -288,13 +298,17 @@ public class TestAccount extends TestJaxrsBase {
@Test(groups = "slow", enabled = true)
public void testCustomFields() throws Exception {
+
+ final AccountJson accountJson = createAccount("yoyoq", "gfgrqe", "yoyoq@yahoo.com");
+ assertNotNull(accountJson);
+
final List<CustomFieldJson> customFields = new LinkedList<CustomFieldJson>();
customFields.add(new CustomFieldJson("1", "value1"));
customFields.add(new CustomFieldJson("2", "value2"));
customFields.add(new CustomFieldJson("3", "value3"));
final String baseJson = mapper.writeValueAsString(customFields);
- final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + JaxrsResource.CUSTOM_FIELDS + "/" + UUID.randomUUID().toString();
+ final String uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountJson.getAccountId() + "/" + JaxrsResource.CUSTOM_FIELDS;
Response response = doPost(uri, baseJson, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode());
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestChargeback.java b/server/src/test/java/com/ning/billing/jaxrs/TestChargeback.java
index 9dc8d51..34cf968 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestChargeback.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestChargeback.java
@@ -47,7 +47,7 @@ import static org.testng.Assert.assertTrue;
public class TestChargeback extends TestJaxrsBase {
@Test(groups = "slow")
public void testAddChargeback() throws Exception {
- final PaymentJsonSimple payment = createInvoicePayment();
+ final PaymentJsonSimple payment = createAccountWithInvoiceAndPayment();
final ChargebackJson input = new ChargebackJson(null, null, BigDecimal.TEN, payment.getPaymentId(), null);
final String jsonInput = mapper.writeValueAsString(input);
@@ -124,12 +124,12 @@ public class TestChargeback extends TestJaxrsBase {
//assertEquals(response.getStatusCode(), javax.ws.rs.core.Response.Status.NO_CONTENT.getStatusCode(), response.getResponseBody());
}
- private PaymentJsonSimple createInvoicePayment() throws Exception {
- final InvoiceJsonSimple invoice = createInvoice();
+ private PaymentJsonSimple createAccountWithInvoiceAndPayment() throws Exception {
+ final InvoiceJsonSimple invoice = createAccountWithInvoice();
return getPayment(invoice);
}
- private InvoiceJsonSimple createInvoice() throws Exception {
+ private InvoiceJsonSimple createAccountWithInvoice() throws Exception {
// Create account
final AccountJson accountJson = createAccountWithDefaultPaymentMethod(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "nohup@yahoo.com");
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestInvoice.java b/server/src/test/java/com/ning/billing/jaxrs/TestInvoice.java
index 36f7b53..3d93c6d 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestInvoice.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestInvoice.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -51,7 +51,7 @@ public class TestInvoice extends TestJaxrsBase {
final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
- final AccountJson accountJson = createAccount("poupou", "qhddffrwe", "poupou@yahoo.com");
+ final AccountJson accountJson = createAccountWithDefaultPaymentMethod("poupou", "qhddffrwe", "poupou@yahoo.com");
assertNotNull(accountJson);
final BundleJsonNoSubscriptions bundleJson = createBundle(accountJson.getAccountId(), "9967599");
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestInvoiceNotification.java b/server/src/test/java/com/ning/billing/jaxrs/TestInvoiceNotification.java
index 370ce77..d1aa37f 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestInvoiceNotification.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestInvoiceNotification.java
@@ -56,7 +56,7 @@ public class TestInvoiceNotification extends TestJaxrsBase {
final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
- final AccountJson accountJson = createAccount(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
+ final AccountJson accountJson = createAccountWithDefaultPaymentMethod(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
Assert.assertNotNull(accountJson);
final BundleJsonNoSubscriptions bundleJson = createBundle(accountJson.getAccountId(), UUID.randomUUID().toString());
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java b/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
index 1b7008a..5ef2bb7 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestJaxrsBase.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -46,6 +46,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.google.inject.Module;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.account.glue.AccountModule;
import com.ning.billing.analytics.setup.AnalyticsModule;
import com.ning.billing.api.TestApiListener;
@@ -71,6 +72,7 @@ import com.ning.billing.jaxrs.resources.JaxrsResource;
import com.ning.billing.junction.glue.DefaultJunctionModule;
import com.ning.billing.payment.glue.PaymentModule;
import com.ning.billing.payment.provider.MockPaymentProviderPluginModule;
+import com.ning.billing.server.ServerTestSuiteWithEmbeddedDB;
import com.ning.billing.server.listeners.KillbillGuiceListener;
import com.ning.billing.server.modules.KillbillServerModule;
import com.ning.billing.util.clock.Clock;
@@ -95,7 +97,7 @@ import com.ning.jetty.core.server.HttpServer;
import static org.testng.Assert.assertNotNull;
-public class TestJaxrsBase {
+public class TestJaxrsBase extends ServerTestSuiteWithEmbeddedDB {
protected static final String PLUGIN_NAME = "noop";
// STEPH
@@ -110,7 +112,7 @@ public class TestJaxrsBase {
private static TestKillbillGuiceListener listener;
- private MysqlTestingHelper helper;
+ private final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
private HttpServer server;
protected CoreConfig config;
@@ -192,11 +194,12 @@ public class TestJaxrsBase {
}
}
+ @Override
protected void installKillbillModules() {
/*
* For a lack of getting module override working, copy all install modules from parent class...
- *
+ *
super.installKillbillModules();
Modules.override(new com.ning.billing.payment.setup.PaymentModule()).with(new PaymentMockModule());
*/
@@ -235,19 +238,7 @@ public class TestJaxrsBase {
@BeforeMethod(groups = "slow")
public void cleanupBeforeMethod(final Method method) {
- log.info("***************************************************************************************************");
- log.info("*** Starting test {}:{}", method.getDeclaringClass().getName(), method.getName());
- log.info("***************************************************************************************************");
-
busHandler.reset();
- helper.cleanupAllTables();
- }
-
- @AfterMethod(groups = "slow")
- public void endTest(final Method method) throws Exception {
- log.info("***************************************************************************************************");
- log.info("*** Ending test {}:{}", method.getDeclaringClass().getName(), method.getName());
- log.info("***************************************************************************************************");
}
@BeforeClass(groups = "slow")
@@ -258,33 +249,12 @@ public class TestJaxrsBase {
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
- //mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
+ //mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
busHandler = new TestApiListener(null);
- this.helper = listener.getMysqlTestingHelper();
this.clock = (ClockMock) listener.getClock();
}
- private void setupMySQL() throws IOException {
- final String accountDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/account/ddl.sql"));
- final String entitlementDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/entitlement/ddl.sql"));
- final String invoiceDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/invoice/ddl.sql"));
- final String paymentDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/payment/ddl.sql"));
- final String utilDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- final String analyticsDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/analytics/ddl.sql"));
- final String junctionDdl = IOUtils.toString(TestIntegration.class.getResourceAsStream("/com/ning/billing/junction/ddl.sql"));
-
- helper.startMysql();
-
- helper.initDb(accountDdl);
- helper.initDb(entitlementDdl);
- helper.initDb(invoiceDdl);
- helper.initDb(paymentDdl);
- helper.initDb(utilDdl);
- helper.initDb(analyticsDdl);
- helper.initDb(junctionDdl);
- }
-
private void loadConfig() {
if (config == null) {
config = new ConfigurationObjectFactory(System.getProperties()).build(CoreConfig.class);
@@ -293,11 +263,9 @@ public class TestJaxrsBase {
@BeforeSuite(groups = "slow")
public void setup() throws Exception {
-
loadSystemPropertiesFromClasspath("/killbill.properties");
loadConfig();
- this.helper = new MysqlTestingHelper();
this.clock = new ClockMock();
listener = new TestKillbillGuiceListener(helper, clock);
server = new HttpServer();
@@ -312,9 +280,6 @@ public class TestJaxrsBase {
};
server.configure(config, eventListeners, new HashMap<FilterHolder, String>());
- setupMySQL();
- helper.cleanupAllTables();
-
server.start();
}
@@ -324,10 +289,6 @@ public class TestJaxrsBase {
server.stop();
} catch (Exception ignored) {
}
-
- if (helper != null) {
- helper.stopMysql();
- }
}
protected List<PaymentMethodProperties> getPaymentMethodCCProperties() {
@@ -427,7 +388,7 @@ public class TestJaxrsBase {
protected SubscriptionJsonNoEvents createSubscription(final String bundleId, final String productName, final String productCategory, final String billingPeriod, final boolean waitCompletion) throws Exception {
- final SubscriptionJsonNoEvents input = new SubscriptionJsonNoEvents(null, bundleId, null, productName, productCategory, billingPeriod, PriceListSet.DEFAULT_PRICELIST_NAME, null);
+ final SubscriptionJsonNoEvents input = new SubscriptionJsonNoEvents(null, bundleId, null, productName, productCategory, billingPeriod, PriceListSet.DEFAULT_PRICELIST_NAME, null, null);
String baseJson = mapper.writeValueAsString(input);
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestPayment.java b/server/src/test/java/com/ning/billing/jaxrs/TestPayment.java
new file mode 100644
index 0000000..be1ec0d
--- /dev/null
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestPayment.java
@@ -0,0 +1,105 @@
+/*
+ * 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.jaxrs;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+import javax.ws.rs.core.Response.Status;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.ning.billing.catalog.api.BillingPeriod;
+import com.ning.billing.catalog.api.ProductCategory;
+import com.ning.billing.jaxrs.json.AccountJson;
+import com.ning.billing.jaxrs.json.BundleJsonNoSubscriptions;
+import com.ning.billing.jaxrs.json.PaymentJsonSimple;
+
+import com.ning.billing.jaxrs.json.RefundJson;
+import com.ning.billing.jaxrs.json.SubscriptionJsonNoEvents;
+import com.ning.billing.jaxrs.resources.JaxrsResource;
+import com.ning.http.client.Response;
+
+public class TestPayment extends TestJaxrsBase {
+
+ private static final Logger log = LoggerFactory.getLogger(TestPayment.class);
+
+ @Test(groups = "slow", enabled = true)
+ public void testPaymentWithRefund() throws Exception {
+ final AccountJson accountJson = createAccountWithDefaultPaymentMethod("eraahahildo", "sheqrgfhwe", "eraahahildo@yahoo.com");
+ assertNotNull(accountJson);
+
+ final BundleJsonNoSubscriptions bundleJson = createBundle(accountJson.getAccountId(), "317199");
+ assertNotNull(bundleJson);
+
+ final SubscriptionJsonNoEvents subscriptionJson = createSubscription(bundleJson.getBundleId(), "Shotgun", ProductCategory.BASE.toString(), BillingPeriod.MONTHLY.toString(), true);
+ assertNotNull(subscriptionJson);
+
+ clock.addMonths(1);
+ crappyWaitForLackOfProperSynchonization();
+
+
+ String uri = JaxrsResource.ACCOUNTS_PATH + "/" + accountJson.getAccountId() + "/" + JaxrsResource.PAYMENTS;
+
+ Response response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ String baseJson = response.getResponseBody();
+ List<PaymentJsonSimple> objFromJson = mapper.readValue(baseJson, new TypeReference<List<PaymentJsonSimple>>() {});
+ Assert.assertEquals(objFromJson.size(), 1);
+
+ final String paymentId = objFromJson.get(0).getPaymentId();
+ final BigDecimal paymentAmount = objFromJson.get(0).getAmount();
+
+ uri = JaxrsResource.PAYMENTS_PATH + "/" + paymentId + "/" + JaxrsResource.REFUNDS;
+ response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ baseJson = response.getResponseBody();
+ List<RefundJson> objRefundFromJson = mapper.readValue(baseJson, new TypeReference<List<RefundJson>>() {});
+ Assert.assertEquals(objRefundFromJson.size(), 0);
+
+ // Issue the refund
+
+ RefundJson refundJson = new RefundJson(null, paymentId, paymentAmount.negate(), false);
+ baseJson = mapper.writeValueAsString(refundJson);
+ response = doPost(uri, baseJson, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode());
+
+ final String locationCC = response.getHeader("Location");
+ Assert.assertNotNull(locationCC);
+
+ // Retrieves by Id based on Location returned
+ response = doGetWithUrl(locationCC, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ baseJson = response.getResponseBody();
+ final RefundJson refundJsonCheck = mapper.readValue(baseJson, RefundJson.class);
+ Assert.assertTrue(refundJsonCheck.equalsNoId(refundJson));
+
+ uri = JaxrsResource.PAYMENTS_PATH + "/" + paymentId + "/" + JaxrsResource.REFUNDS;
+ response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ baseJson = response.getResponseBody();
+ objRefundFromJson = mapper.readValue(baseJson, new TypeReference<List<RefundJson>>() {});
+ Assert.assertEquals(objRefundFromJson.size(), 1);
+
+ }
+}
diff --git a/server/src/test/java/com/ning/billing/jaxrs/TestSubscription.java b/server/src/test/java/com/ning/billing/jaxrs/TestSubscription.java
index dff76bd..9e2d92f 100644
--- a/server/src/test/java/com/ning/billing/jaxrs/TestSubscription.java
+++ b/server/src/test/java/com/ning/billing/jaxrs/TestSubscription.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -36,6 +36,7 @@ import com.ning.billing.jaxrs.resources.JaxrsResource;
import com.ning.http.client.Response;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class TestSubscription extends TestJaxrsBase {
@@ -51,7 +52,7 @@ public class TestSubscription extends TestJaxrsBase {
final DateTime initialDate = new DateTime(2012, 4, 25, 0, 3, 42, 0);
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
- final AccountJson accountJson = createAccount("xil", "shdxilhkkl", "xil@yahoo.com");
+ final AccountJson accountJson = createAccountWithDefaultPaymentMethod("xil", "shdxilhkkl", "xil@yahoo.com");
final BundleJsonNoSubscriptions bundleJson = createBundle(accountJson.getAccountId(), "99999");
final String productName = "Shotgun";
@@ -59,7 +60,7 @@ public class TestSubscription extends TestJaxrsBase {
final SubscriptionJsonNoEvents subscriptionJson = createSubscription(bundleJson.getBundleId(), productName, ProductCategory.BASE.toString(), term.toString(), true);
Assert.assertNotNull(subscriptionJson.getChargedThroughDate());
- Assert.assertEquals(subscriptionJson.getChargedThroughDate(), subscriptionJson.getStartDate().plusDays(30));
+ Assert.assertEquals(subscriptionJson.getChargedThroughDate().toString(), "2012-05-25T00:00:00.000Z");
String uri = JaxrsResource.SUBSCRIPTIONS_PATH + "/" + subscriptionJson.getSubscriptionId().toString();
@@ -80,7 +81,7 @@ public class TestSubscription extends TestJaxrsBase {
newProductName,
subscriptionJson.getProductCategory(),
subscriptionJson.getBillingPeriod(),
- subscriptionJson.getPriceList(), null);
+ subscriptionJson.getPriceList(), null, null);
baseJson = mapper.writeValueAsString(newInput);
final Map<String, String> queryParams = getQueryParamsForCallCompletion(CALL_COMPLETION_TIMEOUT_SEC);
@@ -96,12 +97,22 @@ public class TestSubscription extends TestJaxrsBase {
crappyWaitForLackOfProperSynchonization();
- //
+ //
// Cancel EOT
uri = JaxrsResource.SUBSCRIPTIONS_PATH + "/" + subscriptionJson.getSubscriptionId().toString();
response = doDelete(uri, queryParams, DEFAULT_HTTP_TIMEOUT_SEC);
assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+
+ // Retrieves to check EndDate
+ uri = JaxrsResource.SUBSCRIPTIONS_PATH + "/" + subscriptionJson.getSubscriptionId().toString();
+ response = doGet(uri, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
+ assertEquals(response.getStatusCode(), Status.OK.getStatusCode());
+ baseJson = response.getResponseBody();
+ objFromJson = mapper.readValue(baseJson, SubscriptionJsonNoEvents.class);
+ assertNotNull(objFromJson.getCancelledDate());
+ assertTrue(objFromJson.getCancelledDate().compareTo(clock.getUTCNow()) > 0);
+
// Uncancel
uri = JaxrsResource.SUBSCRIPTIONS_PATH + "/" + subscriptionJson.getSubscriptionId().toString() + "/uncancel";
response = doPut(uri, baseJson, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
@@ -111,7 +122,8 @@ public class TestSubscription extends TestJaxrsBase {
@Test(groups = "slow", enabled = true)
public void testWithNonExistentSubscription() throws Exception {
final String uri = JaxrsResource.SUBSCRIPTIONS_PATH + "/" + UUID.randomUUID().toString();
- final SubscriptionJsonNoEvents subscriptionJson = new SubscriptionJsonNoEvents(null, UUID.randomUUID().toString(), null, "Pistol", ProductCategory.BASE.toString(), BillingPeriod.MONTHLY.toString(), PriceListSet.DEFAULT_PRICELIST_NAME, null);
+ final SubscriptionJsonNoEvents subscriptionJson = new SubscriptionJsonNoEvents(null, UUID.randomUUID().toString(), null, "Pistol", ProductCategory.BASE.toString(), BillingPeriod.MONTHLY.toString(),
+ PriceListSet.DEFAULT_PRICELIST_NAME, null, null);
final String baseJson = mapper.writeValueAsString(subscriptionJson);
Response response = doPut(uri, baseJson, DEFAULT_EMPTY_QUERY, DEFAULT_HTTP_TIMEOUT_SEC);
diff --git a/server/src/test/java/com/ning/billing/server/ServerTestSuiteWithEmbeddedDB.java b/server/src/test/java/com/ning/billing/server/ServerTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..57d4044
--- /dev/null
+++ b/server/src/test/java/com/ning/billing/server/ServerTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.server;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class ServerTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
util/pom.xml 2(+1 -1)
diff --git a/util/pom.xml b/util/pom.xml
index 2d0ebc2..7507b08 100644
--- a/util/pom.xml
+++ b/util/pom.xml
@@ -13,7 +13,7 @@
<parent>
<groupId>com.ning.billing</groupId>
<artifactId>killbill</artifactId>
- <version>0.1.20-SNAPSHOT</version>
+ <version>0.1.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>killbill-util</artifactId>
diff --git a/util/src/main/java/com/ning/billing/util/bus/PersistentBus.java b/util/src/main/java/com/ning/billing/util/bus/PersistentBus.java
index b315e79..c5e5375 100644
--- a/util/src/main/java/com/ning/billing/util/bus/PersistentBus.java
+++ b/util/src/main/java/com/ning/billing/util/bus/PersistentBus.java
@@ -171,7 +171,7 @@ public class PersistentBus extends PersistentQueueBase implements Bus {
final BusEventEntry entry = new BusEventEntry(hostname, event.getClass().getName(), json);
transactional.insertBusEvent(entry);
} catch (Exception e) {
- log.error("Failed to post BusEvent " + event.toString(), e);
+ log.error("Failed to post BusEvent " + event, e);
}
}
}
diff --git a/util/src/main/java/com/ning/billing/util/dao/TableName.java b/util/src/main/java/com/ning/billing/util/dao/TableName.java
index 1620b13..a5038d5 100644
--- a/util/src/main/java/com/ning/billing/util/dao/TableName.java
+++ b/util/src/main/java/com/ning/billing/util/dao/TableName.java
@@ -21,18 +21,17 @@ public enum TableName {
ACCOUNT_HISTORY("account_history"),
ACCOUNT_EMAIL_HISTORY("account_email_history"),
BUNDLES("bundles"),
- CREDIT_INVOICE_ITEMS("credit_invoice_items"),
CUSTOM_FIELD_HISTORY("custom_field_history"),
- FIXED_INVOICE_ITEMS("fixed_invoice_items"),
+ INVOICE_ITEMS("invoice_items"),
INVOICE_PAYMENTS("invoice_payments"),
INVOICES("invoices"),
PAYMENT_ATTEMPTS("payment_attempts"),
PAYMENT_HISTORY("payment_history"),
PAYMENTS("payments"),
PAYMENT_METHODS("payment_methods"),
- RECURRING_INVOICE_ITEMS("recurring_invoice_items"),
SUBSCRIPTIONS("subscriptions"),
SUBSCRIPTION_EVENTS("subscription_events"),
+ REFUNDS("refunds"),
TAG_HISTORY("tag_history");
private final String tableName;
diff --git a/util/src/main/java/com/ning/billing/util/globallocker/GlobalLocker.java b/util/src/main/java/com/ning/billing/util/globallocker/GlobalLocker.java
index daddf1a..7c59a47 100644
--- a/util/src/main/java/com/ning/billing/util/globallocker/GlobalLocker.java
+++ b/util/src/main/java/com/ning/billing/util/globallocker/GlobalLocker.java
@@ -18,24 +18,12 @@ package com.ning.billing.util.globallocker;
public interface GlobalLocker {
- GlobalLock lockWithNumberOfTries(final LockerService service, final String lockKey, final int retry);
+ GlobalLock lockWithNumberOfTries(final LockerType service, final String lockKey, final int retry);
- Boolean isFree(final LockerService service, final String lockKey);
+ Boolean isFree(final LockerType service, final String lockKey);
- public enum LockerService {
-
- INVOICE("invoice"),
- PAYMENT("payment");
-
- private final String svcName;
-
- LockerService(final String svcName) {
- this.svcName = svcName;
- }
-
- @Override
- public String toString() {
- return svcName;
- }
+ public enum LockerType {
+ // Global ACCOUNT locking
+ ACCOUNT
}
}
diff --git a/util/src/main/java/com/ning/billing/util/globallocker/MySqlGlobalLocker.java b/util/src/main/java/com/ning/billing/util/globallocker/MySqlGlobalLocker.java
index 95e61bc..248aeef 100644
--- a/util/src/main/java/com/ning/billing/util/globallocker/MySqlGlobalLocker.java
+++ b/util/src/main/java/com/ning/billing/util/globallocker/MySqlGlobalLocker.java
@@ -27,7 +27,7 @@ public class MySqlGlobalLocker implements GlobalLocker {
private static final Logger logger = LoggerFactory.getLogger(MySqlGlobalLocker.class);
- private static final long DEFAULT_TIMEOUT = 3L; // 3 seconds
+ private static final long DEFAULT_TIMEOUT = 5L; // 5 seconds
private final IDBI dbi;
private long timeout;
@@ -43,7 +43,7 @@ public class MySqlGlobalLocker implements GlobalLocker {
}
@Override
- public GlobalLock lockWithNumberOfTries(final LockerService service, final String lockKey, final int retry) {
+ public GlobalLock lockWithNumberOfTries(final LockerType service, final String lockKey, final int retry) {
final String lockName = getLockName(service, lockKey);
int tries_left = retry;
@@ -82,7 +82,7 @@ public class MySqlGlobalLocker implements GlobalLocker {
}
@Override
- public Boolean isFree(final LockerService service, final String lockKey) {
+ public Boolean isFree(final LockerType service, final String lockKey) {
final String lockName = getLockName(service, lockKey);
final Handle h = dbi.open();
@@ -96,7 +96,7 @@ public class MySqlGlobalLocker implements GlobalLocker {
}
}
- private String getLockName(final LockerService service, final String lockKey) {
+ private String getLockName(final LockerType service, final String lockKey) {
final StringBuilder tmp = new StringBuilder()
.append(service.toString())
.append("-")
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/dao/NotificationSqlDao.java b/util/src/main/java/com/ning/billing/util/notificationq/dao/NotificationSqlDao.java
index dc3ee4d..0e56efd 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/dao/NotificationSqlDao.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/dao/NotificationSqlDao.java
@@ -51,6 +51,13 @@ public interface NotificationSqlDao extends Transactional<NotificationSqlDao>, C
@Mapper(NotificationSqlMapper.class)
public List<Notification> getReadyNotifications(@Bind("now") Date now, @Bind("owner") String owner, @Bind("max") int max, @Bind("queueName") String queueName);
+ @SqlQuery
+ @Mapper(NotificationSqlMapper.class)
+ public List<Notification> getNotificationForAccountAndDate(@Bind("accountId") final String accountId, @Bind("effectiveDate") final Date effectiveDate);
+
+ @SqlUpdate
+ public void removeNotification(@Bind("id") String id);
+
@SqlUpdate
public int claimNotification(@Bind("owner") String owner, @Bind("nextAvailable") Date nextAvailable,
@Bind("id") String id, @Bind("now") Date now);
@@ -73,7 +80,8 @@ public interface NotificationSqlDao extends Transactional<NotificationSqlDao>, C
stmt.bind("id", evt.getId().toString());
stmt.bind("createdDate", getDate(new DateTime()));
stmt.bind("creatingOwner", evt.getCreatedOwner());
- stmt.bind("className", evt.getNotificationKeyClass());
+ stmt.bind("className", evt.getNotificationKeyClass());
+ stmt.bind("accountId", evt.getAccountId() != null ? evt.getAccountId().toString() : null);
stmt.bind("notificationKey", evt.getNotificationKey());
stmt.bind("effectiveDate", getDate(evt.getEffectiveDate()));
stmt.bind("queueName", evt.getQueueName());
@@ -92,8 +100,9 @@ public interface NotificationSqlDao extends Transactional<NotificationSqlDao>, C
final Long ordering = r.getLong("record_id");
final UUID id = getUUID(r, "id");
final String createdOwner = r.getString("creating_owner");
- final String className = r.getString("class_name");
+ final String className = r.getString("class_name");
final String notificationKey = r.getString("notification_key");
+ final UUID accountId = getUUID(r, "account_id");
final String queueName = r.getString("queue_name");
final DateTime effectiveDate = getDate(r, "effective_date");
final DateTime nextAvailableDate = getDate(r, "processing_available_date");
@@ -101,7 +110,7 @@ public interface NotificationSqlDao extends Transactional<NotificationSqlDao>, C
final PersistentQueueEntryLifecycleState processingState = PersistentQueueEntryLifecycleState.valueOf(r.getString("processing_state"));
return new DefaultNotification(ordering, id, createdOwner, processingOwner, queueName, nextAvailableDate,
- processingState, className, notificationKey, effectiveDate);
+ processingState, className, notificationKey, accountId, effectiveDate);
}
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotification.java b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotification.java
index 1d74210..70c49c4 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotification.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotification.java
@@ -32,11 +32,12 @@ public class DefaultNotification extends EntityBase implements Notification {
private final String notificationKeyClass;
private final String notificationKey;
private final DateTime effectiveDate;
+ private final UUID accountId;
public DefaultNotification(final long ordering, final UUID id, final String createdOwner, final String owner, final String queueName, final DateTime nextAvailableDate,
final PersistentQueueEntryLifecycleState lifecycleState,
- final String notificationKeyClass, final String notificationKey, final DateTime effectiveDate) {
+ final String notificationKeyClass, final String notificationKey, final UUID accountId, final DateTime effectiveDate) {
super(id);
this.ordering = ordering;
this.owner = owner;
@@ -46,11 +47,12 @@ public class DefaultNotification extends EntityBase implements Notification {
this.lifecycleState = lifecycleState;
this.notificationKeyClass = notificationKeyClass;
this.notificationKey = notificationKey;
+ this.accountId = accountId;
this.effectiveDate = effectiveDate;
}
- public DefaultNotification(final String queueName, final String createdOwner, final String notificationKeyClass, final String notificationKey, final DateTime effectiveDate) {
- this(-1L, UUID.randomUUID(), createdOwner, null, queueName, null, PersistentQueueEntryLifecycleState.AVAILABLE, notificationKeyClass, notificationKey, effectiveDate);
+ public DefaultNotification(final String queueName, final String createdOwner, final String notificationKeyClass, final String notificationKey, final UUID accountId, final DateTime effectiveDate) {
+ this(-1L, UUID.randomUUID(), createdOwner, null, queueName, null, PersistentQueueEntryLifecycleState.AVAILABLE, notificationKeyClass, notificationKey, accountId, effectiveDate);
}
@Override
@@ -97,7 +99,7 @@ public class DefaultNotification extends EntityBase implements Notification {
return notificationKeyClass;
}
-
+
@Override
public String getNotificationKey() {
return notificationKey;
@@ -117,4 +119,9 @@ public class DefaultNotification extends EntityBase implements Notification {
public String getCreatedOwner() {
return createdOwner;
}
+
+ @Override
+ public UUID getAccountId() {
+ return accountId;
+ }
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueue.java b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueue.java
index 19923b3..246b187 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueue.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueue.java
@@ -20,30 +20,32 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.ning.billing.config.NotificationConfig;
-import com.ning.billing.util.bus.dao.BusEventEntry;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
import com.ning.billing.util.notificationq.dao.NotificationSqlDao;
public class DefaultNotificationQueue extends NotificationQueueBase {
+ private static final Logger log = LoggerFactory.getLogger(DefaultNotificationQueue.class);
- protected final NotificationSqlDao dao;
-
- public DefaultNotificationQueue(final IDBI dbi, final Clock clock, final String svcName, final String queueName, final NotificationQueueHandler handler, final NotificationConfig config) {
+ private final NotificationSqlDao dao;
+ public DefaultNotificationQueue(final IDBI dbi, final Clock clock, final String svcName, final String queueName,
+ final NotificationQueueHandler handler, final NotificationConfig config) {
super(clock, svcName, queueName, handler, config);
this.dao = dbi.onDemand(NotificationSqlDao.class);
}
@Override
public int doProcessEvents() {
-
logDebug("ENTER doProcessEvents");
final List<Notification> notifications = getReadyNotifications();
if (notifications.size() == 0) {
@@ -51,72 +53,76 @@ public class DefaultNotificationQueue extends NotificationQueueBase {
return 0;
}
- logDebug("START processing %d events at time %s", notifications.size(), clock.getUTCNow().toDate());
+ logDebug("START processing %d events at time %s", notifications.size(), getClock().getUTCNow().toDate());
int result = 0;
for (final Notification cur : notifications) {
- nbProcessedEvents.incrementAndGet();
- logDebug("handling notification %s, key = %s for time %s",
- cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate());
- NotificationKey key = deserializeEvent(cur.getNotificationKeyClass(), cur.getNotificationKey());
- handler.handleReadyNotification(key, cur.getEffectiveDate());
+ getNbProcessedEvents().incrementAndGet();
+ logDebug("handling notification %s, key = %s for time %s", cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate());
+ final NotificationKey key = deserializeEvent(cur.getNotificationKeyClass(), cur.getNotificationKey());
+ getHandler().handleReadyNotification(key, cur.getEffectiveDate());
result++;
clearNotification(cur);
- logDebug("done handling notification %s, key = %s for time %s",
- cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate());
+ logDebug("done handling notification %s, key = %s for time %s", cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate());
}
+
return result;
}
-
@Override
- public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationKey notificationKey) throws IOException {
- recordFutureNotificationInternal(futureNotificationTime, notificationKey, dao);
+ public void recordFutureNotification(final DateTime futureNotificationTime, final UUID accountId, final NotificationKey notificationKey) throws IOException {
+ recordFutureNotificationInternal(futureNotificationTime, accountId, notificationKey, dao);
}
@Override
public void recordFutureNotificationFromTransaction(final Transmogrifier transactionalDao,
- final DateTime futureNotificationTime, final NotificationKey notificationKey) throws IOException {
+ final DateTime futureNotificationTime,
+ final UUID accountId,
+ final NotificationKey notificationKey) throws IOException {
final NotificationSqlDao transactionalNotificationDao = transactionalDao.become(NotificationSqlDao.class);
- recordFutureNotificationInternal(futureNotificationTime, notificationKey, transactionalNotificationDao);
+ recordFutureNotificationInternal(futureNotificationTime, accountId, notificationKey, transactionalNotificationDao);
}
-
- private void recordFutureNotificationInternal(final DateTime futureNotificationTime, final NotificationKey notificationKey, final NotificationSqlDao thisDao) throws IOException {
+
+ private void recordFutureNotificationInternal(final DateTime futureNotificationTime,
+ final UUID accountId,
+ final NotificationKey notificationKey,
+
+ final NotificationSqlDao thisDao) throws IOException {
final String json = objectMapper.writeValueAsString(notificationKey);
- final Notification notification = new DefaultNotification(getFullQName(), hostname, notificationKey.getClass().getName(), json, futureNotificationTime);
+ final Notification notification = new DefaultNotification(getFullQName(), getHostname(), notificationKey.getClass().getName(), json, accountId, futureNotificationTime);
thisDao.insertNotification(notification);
}
private void clearNotification(final Notification cleared) {
- dao.clearNotification(cleared.getId().toString(), hostname);
+ dao.clearNotification(cleared.getId().toString(), getHostname());
}
private List<Notification> getReadyNotifications() {
-
- final Date now = clock.getUTCNow().toDate();
- final Date nextAvailable = clock.getUTCNow().plus(CLAIM_TIME_MS).toDate();
-
- final List<Notification> input = dao.getReadyNotifications(now, hostname, CLAIM_TIME_MS, getFullQName());
+ final Date now = getClock().getUTCNow().toDate();
+ final Date nextAvailable = getClock().getUTCNow().plus(CLAIM_TIME_MS).toDate();
+ final List<Notification> input = dao.getReadyNotifications(now, getHostname(), CLAIM_TIME_MS, getFullQName());
final List<Notification> claimedNotifications = new ArrayList<Notification>();
for (final Notification cur : input) {
logDebug("about to claim notification %s, key = %s for time %s",
cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate());
- final boolean claimed = (dao.claimNotification(hostname, nextAvailable, cur.getId().toString(), now) == 1);
+
+ final boolean claimed = (dao.claimNotification(getHostname(), nextAvailable, cur.getId().toString(), now) == 1);
logDebug("claimed notification %s, key = %s for time %s result = %s",
- cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate(), Boolean.valueOf(claimed));
+ cur.getId(), cur.getNotificationKey(), cur.getEffectiveDate(), claimed);
+
if (claimed) {
claimedNotifications.add(cur);
- dao.insertClaimedHistory(hostname, now, cur.getId().toString());
+ dao.insertClaimedHistory(getHostname(), now, cur.getId().toString());
}
}
for (final Notification cur : claimedNotifications) {
- if (cur.getOwner() != null && !cur.getOwner().equals(hostname)) {
- log.warn(String.format("NotificationQueue %s stealing notification %s from %s",
- getFullQName(), cur, cur.getOwner()));
+ if (cur.getOwner() != null && !cur.getOwner().equals(getHostname())) {
+ log.warn("NotificationQueue {} stealing notification {} from {}", new Object[]{getFullQName(), cur, cur.getOwner()});
}
}
+
return claimedNotifications;
}
@@ -130,6 +136,15 @@ public class DefaultNotificationQueue extends NotificationQueueBase {
@Override
public void removeNotificationsByKey(final NotificationKey notificationKey) {
dao.removeNotificationsByKey(notificationKey.toString());
+ }
+ @Override
+ public List<Notification> getNotificationForAccountAndDate(final UUID accountId, final DateTime effectiveDate) {
+ return dao.getNotificationForAccountAndDate(accountId.toString(), effectiveDate.toDate());
+ }
+
+ @Override
+ public void removeNotification(UUID notificationId) {
+ dao.removeNotification(notificationId.toString());
}
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueueService.java b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueueService.java
index bfa2379..9949110 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueueService.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/DefaultNotificationQueueService.java
@@ -23,7 +23,6 @@ import com.ning.billing.config.NotificationConfig;
import com.ning.billing.util.clock.Clock;
public class DefaultNotificationQueueService extends NotificationQueueServiceBase {
-
private final IDBI dbi;
@Inject
@@ -34,7 +33,8 @@ public class DefaultNotificationQueueService extends NotificationQueueServiceBas
@Override
protected NotificationQueue createNotificationQueueInternal(final String svcName,
- final String queueName, final NotificationQueueHandler handler,
+ final String queueName,
+ final NotificationQueueHandler handler,
final NotificationConfig config) {
return new DefaultNotificationQueue(dbi, clock, svcName, queueName, handler, config);
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/Notification.java b/util/src/main/java/com/ning/billing/util/notificationq/Notification.java
index 2ecea54..8e578c9 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/Notification.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/Notification.java
@@ -16,6 +16,8 @@
package com.ning.billing.util.notificationq;
+import java.util.UUID;
+
import org.joda.time.DateTime;
import com.ning.billing.util.entity.Entity;
@@ -25,10 +27,12 @@ public interface Notification extends PersistentQueueEntryLifecycle, Entity {
public Long getOrdering();
public String getNotificationKeyClass();
-
+
public String getNotificationKey();
public DateTime getEffectiveDate();
public String getQueueName();
+
+ public UUID getAccountId();
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueue.java b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueue.java
index 678da46..42cacea 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueue.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueue.java
@@ -17,6 +17,8 @@
package com.ning.billing.util.notificationq;
import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
@@ -31,7 +33,7 @@ public interface NotificationQueue extends QueueLifecycle {
* @param futureNotificationTime the time at which the notification is ready
* @param notificationKey the key for that notification
*/
- public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationKey notificationKey)
+ public void recordFutureNotification(final DateTime futureNotificationTime, final UUID accountId, final NotificationKey notificationKey)
throws IOException;
/**
@@ -42,7 +44,9 @@ public interface NotificationQueue extends QueueLifecycle {
* @param notificationKey the key for that notification
*/
public void recordFutureNotificationFromTransaction(final Transmogrifier transactionalDao,
- final DateTime futureNotificationTime, final NotificationKey notificationKey)
+ final DateTime futureNotificationTime,
+ final UUID accountId,
+ final NotificationKey notificationKey)
throws IOException;
@@ -53,6 +57,13 @@ public interface NotificationQueue extends QueueLifecycle {
*/
public void removeNotificationsByKey(final NotificationKey notificationKey);
+
+
+ public List<Notification> getNotificationForAccountAndDate(final UUID accountId, final DateTime effectiveDate);
+
+ public void removeNotification(final UUID notificationId);
+
+
/**
* This is only valid when the queue has been configured with isNotificationProcessingOff is true
* In which case, it will callback users for all the ready notifications.
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueBase.java b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueBase.java
index 38b6e3c..e26dd6a 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueBase.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueBase.java
@@ -30,32 +30,25 @@ import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.notificationq.NotificationQueueService.NotificationQueueHandler;
import com.ning.billing.util.queue.PersistentQueueBase;
-
public abstract class NotificationQueueBase extends PersistentQueueBase implements NotificationQueue {
-
- protected static final Logger log = LoggerFactory.getLogger(NotificationQueueBase.class);
+ private static final Logger log = LoggerFactory.getLogger(NotificationQueueBase.class);
public static final int CLAIM_TIME_MS = (5 * 60 * 1000); // 5 minutes
private static final String NOTIFICATION_THREAD_PREFIX = "Notification-";
private static final int NB_THREADS = 1;
-
private final String svcName;
private final String queueName;
-
- protected final NotificationQueueHandler handler;
- protected final NotificationConfig config;
-
- protected final Clock clock;
- protected final String hostname;
-
- protected AtomicLong nbProcessedEvents;
+ private final NotificationQueueHandler handler;
+ private final NotificationConfig config;
+ private final Clock clock;
+ private final String hostname;
+ private final AtomicLong nbProcessedEvents;
// Package visibility on purpose
NotificationQueueBase(final Clock clock, final String svcName, final String queueName, final NotificationQueueHandler handler, final NotificationConfig config) {
super(svcName, Executors.newFixedThreadPool(1, new ThreadFactory() {
-
@Override
public Thread newThread(final Runnable r) {
final Thread th = new Thread(r);
@@ -115,11 +108,26 @@ public abstract class NotificationQueueBase extends PersistentQueueBase implemen
return queueName;
}
-
public String getFullQName() {
return NotificationQueueServiceBase.getCompositeName(svcName, queueName);
}
+ public AtomicLong getNbProcessedEvents() {
+ return nbProcessedEvents;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ public NotificationQueueHandler getHandler() {
+ return handler;
+ }
+
+ public Clock getClock() {
+ return clock;
+ }
+
@Override
public abstract int doProcessEvents();
}
diff --git a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueServiceBase.java b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueServiceBase.java
index 03aed2c..f39fc46 100644
--- a/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueServiceBase.java
+++ b/util/src/main/java/com/ning/billing/util/notificationq/NotificationQueueServiceBase.java
@@ -31,7 +31,6 @@ import com.ning.billing.config.NotificationConfig;
import com.ning.billing.util.clock.Clock;
public abstract class NotificationQueueServiceBase implements NotificationQueueService {
-
protected final Logger log = LoggerFactory.getLogger(DefaultNotificationQueueService.class);
protected final Clock clock;
@@ -44,10 +43,10 @@ public abstract class NotificationQueueServiceBase implements NotificationQueueS
this.queues = new TreeMap<String, NotificationQueue>();
}
-
@Override
public NotificationQueue createNotificationQueue(final String svcName,
- final String queueName, final NotificationQueueHandler handler,
+ final String queueName,
+ final NotificationQueueHandler handler,
final NotificationConfig config) throws NotificationQueueAlreadyExists {
if (svcName == null || queueName == null || handler == null || config == null) {
throw new RuntimeException("Need to specify all parameters");
@@ -71,7 +70,7 @@ public abstract class NotificationQueueServiceBase implements NotificationQueueS
public NotificationQueue getNotificationQueue(final String svcName,
final String queueName) throws NoSuchNotificationQueue {
- NotificationQueue result = null;
+ NotificationQueue result;
final String compositeName = getCompositeName(svcName, queueName);
synchronized (queues) {
result = queues.get(compositeName);
@@ -83,7 +82,6 @@ public abstract class NotificationQueueServiceBase implements NotificationQueueS
return result;
}
-
public void deleteNotificationQueue(final String svcName, final String queueName)
throws NoSuchNotificationQueue {
final String compositeName = getCompositeName(svcName, queueName);
@@ -97,7 +95,6 @@ public abstract class NotificationQueueServiceBase implements NotificationQueueS
}
}
-
//
// Test ONLY
//
@@ -144,8 +141,16 @@ public abstract class NotificationQueueServiceBase implements NotificationQueueS
String queueName, NotificationQueueHandler handler,
NotificationConfig config);
-
public static String getCompositeName(final String svcName, final String queueName) {
return svcName + ":" + queueName;
}
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder();
+ sb.append("NotificationQueueServiceBase");
+ sb.append("{queues=").append(queues);
+ sb.append('}');
+ return sb.toString();
+ }
}
diff --git a/util/src/main/java/com/ning/billing/util/template/translation/DefaultCatalogTranslator.java b/util/src/main/java/com/ning/billing/util/template/translation/DefaultCatalogTranslator.java
index a6027f5..f1b0ef7 100644
--- a/util/src/main/java/com/ning/billing/util/template/translation/DefaultCatalogTranslator.java
+++ b/util/src/main/java/com/ning/billing/util/template/translation/DefaultCatalogTranslator.java
@@ -26,7 +26,7 @@ public class DefaultCatalogTranslator extends DefaultTranslatorBase {
@Override
protected String getBundlePath() {
- return "com/ning/billing/util/template/translation/CatalogTranslation";
+ return config.getCatalogBundlePath();
}
@Override
diff --git a/util/src/main/java/com/ning/billing/util/template/translation/DefaultTranslatorBase.java b/util/src/main/java/com/ning/billing/util/template/translation/DefaultTranslatorBase.java
index 2b3f62e..72d3d90 100644
--- a/util/src/main/java/com/ning/billing/util/template/translation/DefaultTranslatorBase.java
+++ b/util/src/main/java/com/ning/billing/util/template/translation/DefaultTranslatorBase.java
@@ -55,6 +55,11 @@ public abstract class DefaultTranslatorBase implements Translator {
if ((bundle != null) && (bundle.containsKey(originalText))) {
return bundle.getString(originalText);
} else {
+ if (config.getDefaultLocale() == null) {
+ log.warn(String.format(ErrorCode.MISSING_DEFAULT_TRANSLATION_RESOURCE.toString(), getTranslationType()));
+ return originalText;
+ }
+
final Locale defaultLocale = new Locale(config.getDefaultLocale());
try {
bundle = getBundle(defaultLocale, bundlePath);
@@ -102,6 +107,8 @@ public abstract class DefaultTranslatorBase implements Translator {
} else {
return new PropertyResourceBundle(inputStream);
}
+ } catch (IllegalArgumentException iae) {
+ return null;
} catch (MissingResourceException mrex) {
return null;
} catch (URISyntaxException e) {
diff --git a/util/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestBase.java b/util/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestBase.java
index 540a0ae..20ecbc4 100644
--- a/util/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestBase.java
+++ b/util/src/main/java/com/ning/billing/util/userrequest/CompletionUserRequestBase.java
@@ -22,8 +22,8 @@ import java.util.concurrent.TimeoutException;
import com.ning.billing.account.api.AccountChangeEvent;
import com.ning.billing.account.api.AccountCreationEvent;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
-import com.ning.billing.invoice.api.EmptyInvoiceEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
+import com.ning.billing.invoice.api.NullInvoiceEvent;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
import com.ning.billing.payment.api.PaymentErrorEvent;
import com.ning.billing.payment.api.PaymentInfoEvent;
@@ -103,10 +103,10 @@ public abstract class CompletionUserRequestBase implements CompletionUserRequest
onAccountChange((AccountChangeEvent) curEvent);
break;
case SUBSCRIPTION_TRANSITION:
- onSubscriptionTransition((SubscriptionEvent) curEvent);
+ onSubscriptionTransition((EffectiveSubscriptionEvent) curEvent);
break;
case INVOICE_EMPTY:
- onEmptyInvoice((EmptyInvoiceEvent) curEvent);
+ onEmptyInvoice((NullInvoiceEvent) curEvent);
break;
case INVOICE_CREATION:
onInvoiceCreation((InvoiceCreationEvent) curEvent);
@@ -135,11 +135,11 @@ public abstract class CompletionUserRequestBase implements CompletionUserRequest
}
@Override
- public void onSubscriptionTransition(final SubscriptionEvent curEvent) {
+ public void onSubscriptionTransition(final EffectiveSubscriptionEvent curEventEffective) {
}
@Override
- public void onEmptyInvoice(final EmptyInvoiceEvent curEvent) {
+ public void onEmptyInvoice(final NullInvoiceEvent curEvent) {
}
@Override
diff --git a/util/src/main/resources/com/ning/billing/util/ddl.sql b/util/src/main/resources/com/ning/billing/util/ddl.sql
index a0e7dad..acb8d69 100644
--- a/util/src/main/resources/com/ning/billing/util/ddl.sql
+++ b/util/src/main/resources/com/ning/billing/util/ddl.sql
@@ -103,6 +103,7 @@ CREATE TABLE notifications (
id char(36) NOT NULL,
created_date datetime NOT NULL,
class_name varchar(256) NOT NULL,
+ account_id char(36),
notification_key varchar(2048) NOT NULL,
creating_owner char(50) NOT NULL,
effective_date datetime NOT NULL,
diff --git a/util/src/main/resources/com/ning/billing/util/notificationq/dao/NotificationSqlDao.sql.stg b/util/src/main/resources/com/ning/billing/util/notificationq/dao/NotificationSqlDao.sql.stg
index 3c81e21..8cb0a27 100644
--- a/util/src/main/resources/com/ning/billing/util/notificationq/dao/NotificationSqlDao.sql.stg
+++ b/util/src/main/resources/com/ning/billing/util/notificationq/dao/NotificationSqlDao.sql.stg
@@ -5,6 +5,7 @@ getReadyNotifications() ::= <<
record_id
, id
, class_name
+ , account_id
, notification_key
, created_date
, creating_owner
@@ -30,6 +31,35 @@ getReadyNotifications() ::= <<
;
>>
+getNotificationForAccountAndDate() ::= <<
+ select
+ record_id
+ , id
+ , class_name
+ , account_id
+ , notification_key
+ , created_date
+ , creating_owner
+ , effective_date
+ , queue_name
+ , processing_owner
+ , processing_available_date
+ , processing_state
+ from notifications
+ where
+ account_id = :accountId AND effective_date = :effectiveDate
+ ;
+>>
+
+removeNotification() ::= <<
+ update notifications
+ set
+ processing_state = 'REMOVED'
+ where
+ id = :id
+;
+>>
+
claimNotification() ::= <<
update notifications
set
@@ -66,6 +96,7 @@ insertNotification() ::= <<
insert into notifications (
id
, class_name
+ , account_id
, notification_key
, created_date
, creating_owner
@@ -77,6 +108,7 @@ insertNotification() ::= <<
) values (
:id
, :className
+ , :accountId
, :notificationKey
, :createdDate
, :creatingOwner
diff --git a/util/src/test/java/com/ning/billing/api/TestApiListener.java b/util/src/test/java/com/ning/billing/api/TestApiListener.java
index 5fc23bc..133e883 100644
--- a/util/src/test/java/com/ning/billing/api/TestApiListener.java
+++ b/util/src/test/java/com/ning/billing/api/TestApiListener.java
@@ -1,4 +1,4 @@
-/*
+/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
@@ -26,8 +26,9 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.eventbus.Subscribe;
import com.ning.billing.entitlement.api.timeline.RepairEntitlementEvent;
-import com.ning.billing.entitlement.api.user.SubscriptionEvent;
+import com.ning.billing.entitlement.api.user.EffectiveSubscriptionEvent;
import com.ning.billing.invoice.api.InvoiceCreationEvent;
+import com.ning.billing.invoice.api.InvoiceEvent;
import com.ning.billing.payment.api.PaymentErrorEvent;
import com.ning.billing.payment.api.PaymentInfoEvent;
@@ -81,9 +82,9 @@ public class TestApiListener {
}
@Subscribe
- public void handleEntitlementEvents(final SubscriptionEvent event) {
- log.info(String.format("TestApiListener Got subscription event %s", event.toString()));
- switch (event.getTransitionType()) {
+ public void handleEntitlementEvents(final EffectiveSubscriptionEvent eventEffective) {
+ log.info(String.format("TestApiListener Got subscription event %s", eventEffective.toString()));
+ switch (eventEffective.getTransitionType()) {
case MIGRATE_ENTITLEMENT:
assertEqualsNicely(NextEvent.MIGRATE_ENTITLEMENT);
notifyIfStackEmpty();
@@ -117,7 +118,7 @@ public class TestApiListener {
notifyIfStackEmpty();
break;
default:
- throw new RuntimeException("Unexpected event type " + event.getRequestedTransitionTime());
+ throw new RuntimeException("Unexpected event type " + eventEffective.getRequestedTransitionTime());
}
}
@@ -126,7 +127,6 @@ public class TestApiListener {
log.info(String.format("TestApiListener Got Invoice event %s", event.toString()));
assertEqualsNicely(NextEvent.INVOICE);
notifyIfStackEmpty();
-
}
@Subscribe
diff --git a/util/src/test/java/com/ning/billing/dbi/LoggingOutputStream.java b/util/src/test/java/com/ning/billing/dbi/LoggingOutputStream.java
new file mode 100644
index 0000000..603b155
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/dbi/LoggingOutputStream.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright 2010-2012 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.dbi;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.slf4j.Logger;
+
+/**
+ * Adapted from http://www.mail-archive.com/user@slf4j.org/msg00674.html for slf4j.
+ * <p/>
+ * An OutputStream that flushes out to a Category.<p>
+ * <p/>
+ * Note that no data is written out to the Category until the stream is
+ * flushed or closed.<p>
+ * <p/>
+ * Example:<pre>
+ * // make sure everything sent to System.err is logged
+ * System.setErr(new PrintStream(new
+ * LoggingOutputStream(Logger.getRootCategory(),
+ * Level.WARN), true));
+ * <p/>
+ * // make sure everything sent to System.out is also logged
+ * System.setOut(new PrintStream(new
+ * LoggingOutputStream(Logger.getRootCategory(),
+ * Level.INFO), true));
+ * </pre>
+ *
+ * @author <a href="[EMAIL PROTECTED]">Jim Moore</a>
+ * @see {{http://www.mail-archive.com/user@slf4j.org/msg00674.html}}
+ */
+
+public class LoggingOutputStream extends OutputStream {
+ /**
+ * Used to maintain the contract of [EMAIL PROTECTED] #close()}.
+ */
+ private boolean hasBeenClosed = false;
+
+ /**
+ * The internal buffer where data is stored.
+ */
+ private byte[] buf;
+
+ /**
+ * The number of valid bytes in the buffer. This value is always
+ * in the range <tt>0</tt> through <tt>buf.length</tt>; elements
+ * <tt>buf[0]</tt> through <tt>buf[count-1]</tt> contain valid
+ * byte data.
+ */
+ private int count;
+
+ /**
+ * Remembers the size of the buffer for speed.
+ */
+ private int bufLength;
+
+ /**
+ * The default number of bytes in the buffer. =2048
+ */
+ public static final int DEFAULT_BUFFER_LENGTH = 2048;
+
+ /**
+ * The category to write to.
+ */
+ private final Logger logger;
+
+ /**
+ * Creates the LoggingOutputStream to flush to the given Category.
+ *
+ * @param log the Logger to write to
+ * @throws IllegalArgumentException if log == null
+ */
+ public LoggingOutputStream(final Logger log) throws IllegalArgumentException {
+ if (log == null) {
+ throw new IllegalArgumentException("log == null");
+ }
+
+ logger = log;
+ bufLength = DEFAULT_BUFFER_LENGTH;
+ buf = new byte[DEFAULT_BUFFER_LENGTH];
+ count = 0;
+ }
+
+ /**
+ * Closes this output stream and releases any system resources
+ * associated with this stream. The general contract of
+ * <code>close</code>
+ * is that it closes the output stream. A closed stream cannot
+ * perform
+ * output operations and cannot be reopened.
+ */
+ public void close() {
+ flush();
+ hasBeenClosed = true;
+ }
+
+ /**
+ * Writes the specified byte to this output stream. The general
+ * contract for <code>write</code> is that one byte is written
+ * to the output stream. The byte to be written is the eight
+ * low-order bits of the argument <code>b</code>. The 24
+ * high-order bits of <code>b</code> are ignored.
+ *
+ * @param b the <code>byte</code> to write
+ * @throws java.io.IOException if an I/O error occurs. In particular, an
+ * <code>IOException</code> may be
+ * thrown if the output stream has been closed.
+ */
+ public void write(final int b) throws IOException {
+ if (hasBeenClosed) {
+ throw new IOException("The stream has been closed.");
+ }
+
+ if (((char) b) == '\r' || ((char) b) == '\n') {
+ return;
+ }
+
+ // would this be writing past the buffer?
+
+ if (count == bufLength) {
+ // grow the buffer
+ final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH;
+ final byte[] newBuf = new byte[newBufLength];
+
+ System.arraycopy(buf, 0, newBuf, 0, bufLength);
+ buf = newBuf;
+
+ bufLength = newBufLength;
+ }
+
+ buf[count] = (byte) b;
+
+ count++;
+ }
+
+ /**
+ * Flushes this output stream and forces any buffered output bytes
+ * to be written out. The general contract of <code>flush</code> is
+ * that calling it is an indication that, if any bytes previously
+ * written have been buffered by the implementation of the output
+ * stream, such bytes should immediately be written to their
+ * intended destination.
+ */
+ public void flush() {
+ if (count == 0) {
+ return;
+ }
+
+ // don't print out blank lines; flushing from PrintStream puts
+
+ // For linux system
+
+ if (count == 1 && ((char) buf[0]) == '\n') {
+ reset();
+ return;
+ }
+
+ // For mac system
+
+ if (count == 1 && ((char) buf[0]) == '\r') {
+ reset();
+ return;
+ }
+
+ // On windows system
+
+ if (count == 2 && (char) buf[0] == '\r' && (char) buf[1] == '\n') {
+ reset();
+ return;
+ }
+
+ final byte[] theBytes = new byte[count];
+ System.arraycopy(buf, 0, theBytes, 0, count);
+ logger.debug(new String(theBytes));
+ reset();
+ }
+
+ private void reset() {
+ // not resetting the buffer -- assuming that if it grew then it will likely grow similarly again
+ count = 0;
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/dbi/MysqlTestingHelper.java b/util/src/test/java/com/ning/billing/dbi/MysqlTestingHelper.java
index f1bfc60..a1b64f4 100644
--- a/util/src/test/java/com/ning/billing/dbi/MysqlTestingHelper.java
+++ b/util/src/test/java/com/ning/billing/dbi/MysqlTestingHelper.java
@@ -19,6 +19,7 @@ package com.ning.billing.dbi;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.io.PrintStream;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.List;
@@ -33,8 +34,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
+import com.google.common.io.Resources;
import com.mysql.management.MysqldResource;
import com.mysql.management.MysqldResourceI;
+import com.ning.billing.util.io.IOUtils;
/**
* Utility class to embed MySQL for testing purposes
@@ -90,7 +93,8 @@ public class MysqlTestingHelper {
Assert.assertTrue(dataDir.delete());
Assert.assertTrue(dataDir.mkdir());
- mysqldResource = new MysqldResource(dbDir, dataDir);
+ final PrintStream out = new PrintStream(new LoggingOutputStream(log), true);
+ mysqldResource = new MysqldResource(dbDir, dataDir, null, out, out);
final Map<String, String> dbOpts = new HashMap<String, String>();
dbOpts.put(MysqldResourceI.PORT, Integer.toString(port));
@@ -115,7 +119,7 @@ public class MysqlTestingHelper {
return;
}
- log.info("Deleting table: " + table);
+ log.debug("Deleting table: " + table);
final IDBI dbi = getDBI();
dbi.withHandle(new HandleCallback<Void>() {
@Override
@@ -173,6 +177,19 @@ public class MysqlTestingHelper {
return new DBI(dbiString, USERNAME, PASSWORD);
}
+ public void initDb() throws IOException {
+ for (final String pack : new String[]{"account", "analytics", "entitlement", "util", "payment", "invoice", "junction"}) {
+ final String ddl;
+ try {
+ ddl = IOUtils.toString(Resources.getResource("com/ning/billing/" + pack + "/ddl.sql").openStream());
+ } catch (IllegalArgumentException ignored) {
+ // The test doesn't have this module ddl in the classpath - that's fine
+ continue;
+ }
+ initDb(ddl);
+ }
+ }
+
public void initDb(final String ddl) throws IOException {
if (isUsingLocalInstance()) {
return;
@@ -181,7 +198,7 @@ public class MysqlTestingHelper {
dbi.withHandle(new HandleCallback<Void>() {
@Override
public Void withHandle(final Handle handle) throws Exception {
- log.info("Executing DDL script: " + ddl);
+ log.debug("Executing DDL script: " + ddl);
handle.createScript(ddl).execute();
return null;
}
diff --git a/util/src/test/java/com/ning/billing/KillbillTestSuite.java b/util/src/test/java/com/ning/billing/KillbillTestSuite.java
new file mode 100644
index 0000000..0d8edb2
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/KillbillTestSuite.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2010-2012 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;
+
+import java.lang.reflect.Method;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.ITestResult;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+
+public class KillbillTestSuite {
+ // Use the simple name here to save screen real estate
+ private static final Logger log = LoggerFactory.getLogger(KillbillTestSuite.class.getSimpleName());
+
+ @BeforeMethod(alwaysRun = true)
+ public void startTestSuite(final Method method) throws Exception {
+ log.info("***************************************************************************************************");
+ log.info("*** Starting test {}:{}", method.getDeclaringClass().getName(), method.getName());
+ log.info("***************************************************************************************************");
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void endTestSuite(final Method method, final ITestResult result) throws Exception {
+ log.info("***************************************************************************************************");
+ log.info("*** Ending test {}:{} {} ({} s.)", new Object[]{method.getDeclaringClass().getName(), method.getName(),
+ result.isSuccess() ? "SUCCESS" : "!!! FAILURE !!!", (result.getEndMillis() - result.getStartMillis()) / 1000});
+ log.info("***************************************************************************************************");
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/mock/api/MockEntitlementUserApi.java b/util/src/test/java/com/ning/billing/mock/api/MockEntitlementUserApi.java
index d625137..0fdeeb1 100644
--- a/util/src/test/java/com/ning/billing/mock/api/MockEntitlementUserApi.java
+++ b/util/src/test/java/com/ning/billing/mock/api/MockEntitlementUserApi.java
@@ -36,6 +36,7 @@ import com.ning.billing.util.callcontext.CallContext;
public class MockEntitlementUserApi implements EntitlementUserApi {
private final Map<UUID, String> subscriptionBundles = new HashMap<UUID, String>();
private final Map<UUID, UUID> accountForBundle = new HashMap<UUID, UUID>();
+ private final Map<UUID, Subscription> subscriptionsById = new HashMap<UUID, Subscription>();
public synchronized void addBundle(final UUID bundleUUID, final String externalKey, final UUID accountId) {
subscriptionBundles.put(bundleUUID, externalKey);
@@ -61,11 +62,6 @@ public class MockEntitlementUserApi implements EntitlementUserApi {
}
@Override
- public DateTime getStartDate() {
- throw new UnsupportedOperationException();
- }
-
- @Override
public String getKey() {
return key;
}
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
index be1ade6..d1b8027 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockDbHelperModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockDbHelperModule.java
@@ -20,21 +20,19 @@ import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import com.google.inject.AbstractModule;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
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();
}
public void installMysqlTestingHelper() {
-
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
@@ -44,7 +42,5 @@ public class MockDbHelperModule extends AbstractModule {
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
}
-
}
-
}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockEntitlementModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockEntitlementModule.java
index 5037f48..d712082 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockEntitlementModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockEntitlementModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2011 Ning, Inc.
+ * Copyright 2010-2012 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
@@ -16,6 +16,8 @@
package com.ning.billing.mock.glue;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.entitlement.api.EntitlementService;
import com.ning.billing.entitlement.api.billing.ChargeThruApi;
@@ -23,41 +25,27 @@ import com.ning.billing.entitlement.api.migration.EntitlementMigrationApi;
import com.ning.billing.entitlement.api.timeline.EntitlementTimelineApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.glue.EntitlementModule;
-import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.util.glue.RealImplementation;
public class MockEntitlementModule extends AbstractModule implements EntitlementModule {
-
- /* (non-Javadoc)
- * @see com.ning.billing.mock.glue.EntitlementModule#installEntitlementService()
- */
@Override
public void installEntitlementService() {
- bind(EntitlementService.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementService.class));
+ bind(EntitlementService.class).toInstance(Mockito.mock(EntitlementService.class));
}
- /* (non-Javadoc)
- * @see com.ning.billing.mock.glue.EntitlementModule#installEntitlementUserApi()
- */
@Override
public void installEntitlementUserApi() {
- bind(EntitlementUserApi.class).annotatedWith(RealImplementation.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class));
+ bind(EntitlementUserApi.class).annotatedWith(RealImplementation.class).toInstance(Mockito.mock(EntitlementUserApi.class));
}
- /* (non-Javadoc)
- * @see com.ning.billing.mock.glue.EntitlementModule#installEntitlementMigrationApi()
- */
@Override
public void installEntitlementMigrationApi() {
- bind(EntitlementMigrationApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementMigrationApi.class));
+ bind(EntitlementMigrationApi.class).toInstance(Mockito.mock(EntitlementMigrationApi.class));
}
- /* (non-Javadoc)
- * @see com.ning.billing.mock.glue.EntitlementModule#installChargeThruApi()
- */
@Override
public void installChargeThruApi() {
- bind(ChargeThruApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(ChargeThruApi.class));
+ bind(ChargeThruApi.class).toInstance(Mockito.mock(ChargeThruApi.class));
}
@Override
@@ -71,6 +59,6 @@ public class MockEntitlementModule extends AbstractModule implements Entitlement
@Override
public void installEntitlementTimelineApi() {
- bind(EntitlementTimelineApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementTimelineApi.class));
+ bind(EntitlementTimelineApi.class).toInstance(Mockito.mock(EntitlementTimelineApi.class));
}
}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockInvoiceModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockInvoiceModule.java
index 5c34b36..ecca1cd 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockInvoiceModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockInvoiceModule.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2011 Ning, Inc.
+ * Copyright 2010-2012 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
@@ -16,34 +16,28 @@
package com.ning.billing.mock.glue;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.glue.InvoiceModule;
import com.ning.billing.invoice.api.InvoiceMigrationApi;
import com.ning.billing.invoice.api.InvoicePaymentApi;
import com.ning.billing.invoice.api.InvoiceUserApi;
-import com.ning.billing.invoice.api.test.InvoiceTestApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
public class MockInvoiceModule extends AbstractModule implements InvoiceModule {
-
@Override
public void installInvoiceUserApi() {
- bind(InvoiceUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceUserApi.class));
+ bind(InvoiceUserApi.class).toInstance(Mockito.mock(InvoiceUserApi.class));
}
@Override
public void installInvoicePaymentApi() {
- bind(InvoicePaymentApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(InvoicePaymentApi.class));
+ bind(InvoicePaymentApi.class).toInstance(Mockito.mock(InvoicePaymentApi.class));
}
@Override
public void installInvoiceMigrationApi() {
- bind(InvoiceMigrationApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceMigrationApi.class));
- }
-
- @Override
- public void installInvoiceTestApi() {
- bind(InvoiceTestApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(InvoiceTestApi.class));
+ bind(InvoiceMigrationApi.class).toInstance(Mockito.mock(InvoiceMigrationApi.class));
}
@Override
@@ -51,7 +45,5 @@ public class MockInvoiceModule extends AbstractModule implements InvoiceModule {
installInvoiceUserApi();
installInvoicePaymentApi();
installInvoiceMigrationApi();
- installInvoiceTestApi();
}
-
}
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 67769dd..fedd51e 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
@@ -16,19 +16,20 @@
package com.ning.billing.mock.glue;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.account.api.AccountUserApi;
import com.ning.billing.entitlement.api.user.EntitlementUserApi;
import com.ning.billing.glue.JunctionModule;
import com.ning.billing.junction.api.BillingApi;
import com.ning.billing.junction.api.BlockingApi;
-import com.ning.billing.mock.BrainDeadProxyFactory;
public class MockJunctionModule extends AbstractModule implements JunctionModule {
- private final BillingApi billingApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BillingApi.class);
- private final BlockingApi blockingApi = BrainDeadProxyFactory.createBrainDeadProxyFor(BlockingApi.class);
- private final AccountUserApi userApi = BrainDeadProxyFactory.createBrainDeadProxyFor(AccountUserApi.class);
- private final EntitlementUserApi entUserApi = BrainDeadProxyFactory.createBrainDeadProxyFor(EntitlementUserApi.class);
+ private final BillingApi billingApi = Mockito.mock(BillingApi.class);
+ private final BlockingApi blockingApi = Mockito.mock(BlockingApi.class);
+ private final AccountUserApi userApi = Mockito.mock(AccountUserApi.class);
+ private final EntitlementUserApi entUserApi = Mockito.mock(EntitlementUserApi.class);
@Override
protected void configure() {
@@ -43,7 +44,6 @@ public class MockJunctionModule extends AbstractModule implements JunctionModule
bind(BillingApi.class).toInstance(billingApi);
}
-
@Override
public void installAccountUserApi() {
bind(AccountUserApi.class).toInstance(userApi);
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockOverdueModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockOverdueModule.java
index 7ab87d8..013005b 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockOverdueModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockOverdueModule.java
@@ -16,21 +16,20 @@
package com.ning.billing.mock.glue;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
import com.ning.billing.glue.OverdueModule;
-import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.overdue.OverdueUserApi;
public class MockOverdueModule extends AbstractModule implements OverdueModule {
-
@Override
public void installOverdueUserApi() {
- bind(OverdueUserApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(OverdueUserApi.class));
+ bind(OverdueUserApi.class).toInstance(Mockito.mock(OverdueUserApi.class));
}
@Override
protected void configure() {
installOverdueUserApi();
}
-
}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/MockPaymentModule.java b/util/src/test/java/com/ning/billing/mock/glue/MockPaymentModule.java
index e974333..d2c7ddd 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/MockPaymentModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/MockPaymentModule.java
@@ -16,16 +16,14 @@
package com.ning.billing.mock.glue;
+import org.mockito.Mockito;
+
import com.google.inject.AbstractModule;
-import com.ning.billing.mock.BrainDeadProxyFactory;
import com.ning.billing.payment.api.PaymentApi;
public class MockPaymentModule extends AbstractModule {
-
@Override
protected void configure() {
-
- bind(PaymentApi.class).toInstance(BrainDeadProxyFactory.createBrainDeadProxyFor(PaymentApi.class));
-
+ bind(PaymentApi.class).toInstance(Mockito.mock(PaymentApi.class));
}
}
diff --git a/util/src/test/java/com/ning/billing/mock/glue/TestDbiModule.java b/util/src/test/java/com/ning/billing/mock/glue/TestDbiModule.java
index 76dea1d..634631a 100644
--- a/util/src/test/java/com/ning/billing/mock/glue/TestDbiModule.java
+++ b/util/src/test/java/com/ning/billing/mock/glue/TestDbiModule.java
@@ -20,15 +20,14 @@ import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
import com.google.inject.AbstractModule;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
public class TestDbiModule extends AbstractModule {
-
protected void configure() {
-
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
@@ -38,6 +37,5 @@ public class TestDbiModule extends AbstractModule {
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
}
-
}
}
diff --git a/util/src/test/java/com/ning/billing/mock/MockPriceList.java b/util/src/test/java/com/ning/billing/mock/MockPriceList.java
new file mode 100644
index 0000000..8903a3c
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/mock/MockPriceList.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2010-2012 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;
+
+import java.util.UUID;
+
+import com.ning.billing.catalog.api.BillingPeriod;
+import com.ning.billing.catalog.api.Plan;
+import com.ning.billing.catalog.api.PriceList;
+import com.ning.billing.catalog.api.Product;
+
+public class MockPriceList implements PriceList {
+ private final String name;
+ private final Boolean isRetired;
+ private final Plan plan;
+
+ public MockPriceList() {
+ this(false, UUID.randomUUID().toString(), new MockPlan());
+ }
+
+ public MockPriceList(final Boolean retired, final String name, final Plan plan) {
+ isRetired = retired;
+ this.name = name;
+ this.plan = plan;
+ }
+
+ @Override
+ public boolean isRetired() {
+ return isRetired;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public Plan findPlan(final Product product, final BillingPeriod period) {
+ return plan;
+ }
+
+ public Plan getPlan() {
+ return plan;
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/mock/MockProduct.java b/util/src/test/java/com/ning/billing/mock/MockProduct.java
new file mode 100644
index 0000000..ea341b0
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/mock/MockProduct.java
@@ -0,0 +1,107 @@
+/*
+ * 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;
+
+import com.ning.billing.catalog.api.Product;
+import com.ning.billing.catalog.api.ProductCategory;
+
+public class MockProduct implements Product {
+ private final String name;
+ private final ProductCategory category;
+ private final String catalogName;
+
+ public MockProduct() {
+ name = "TestProduct";
+ category = ProductCategory.BASE;
+ catalogName = "Vehicules";
+ }
+
+ public MockProduct(final String name, final ProductCategory category, final String catalogName) {
+ this.name = name;
+ this.category = category;
+ this.catalogName = catalogName;
+ }
+
+ @Override
+ public String getCatalogName() {
+ return catalogName;
+ }
+
+ @Override
+ public ProductCategory getCategory() {
+ return category;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean isRetired() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Product[] getAvailable() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Product[] getIncluded() {
+ throw new UnsupportedOperationException();
+ }
+
+ public static MockProduct createBicycle() {
+ return new MockProduct("Bicycle", ProductCategory.BASE, "Vehcles");
+ }
+
+ public static MockProduct createPickup() {
+ return new MockProduct("Pickup", ProductCategory.BASE, "Vehcles");
+ }
+
+ public static MockProduct createSportsCar() {
+ return new MockProduct("SportsCar", ProductCategory.BASE, "Vehcles");
+ }
+
+ public static MockProduct createJet() {
+ return new MockProduct("Jet", ProductCategory.BASE, "Vehcles");
+ }
+
+ public static MockProduct createHorn() {
+ return new MockProduct("Horn", ProductCategory.ADD_ON, "Vehcles");
+ }
+
+ public static MockProduct createSpotlight() {
+ return new MockProduct("spotlight", ProductCategory.ADD_ON, "Vehcles");
+ }
+
+ public static MockProduct createRedPaintJob() {
+ return new MockProduct("RedPaintJob", ProductCategory.ADD_ON, "Vehcles");
+ }
+
+ public static Product[] createAll() {
+ return new MockProduct[]{
+ createBicycle(),
+ createPickup(),
+ createSportsCar(),
+ createJet(),
+ createHorn(),
+ createRedPaintJob()
+ };
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/util/bus/TestEventBus.java b/util/src/test/java/com/ning/billing/util/bus/TestEventBus.java
index a91842d..0c92e6d 100644
--- a/util/src/test/java/com/ning/billing/util/bus/TestEventBus.java
+++ b/util/src/test/java/com/ning/billing/util/bus/TestEventBus.java
@@ -19,10 +19,7 @@ package com.ning.billing.util.bus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-@Test(groups = {"slow"})
public class TestEventBus extends TestEventBusBase {
-
-
@BeforeClass(groups = "slow")
public void setup() throws Exception {
eventBus = new InMemoryBus();
diff --git a/util/src/test/java/com/ning/billing/util/bus/TestEventBusBase.java b/util/src/test/java/com/ning/billing/util/bus/TestEventBusBase.java
index 52f06c6..2364c2c 100644
--- a/util/src/test/java/com/ning/billing/util/bus/TestEventBusBase.java
+++ b/util/src/test/java/com/ning/billing/util/bus/TestEventBusBase.java
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.util.bus;
import java.util.UUID;
@@ -28,10 +29,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.bus.BusEvent.BusEventType;
-public class TestEventBusBase {
-
+public abstract class TestEventBusBase extends UtilTestSuiteWithEmbeddedDB {
protected static final Logger log = LoggerFactory.getLogger(TestEventBusBase.class);
@Inject
@@ -47,9 +48,7 @@ public class TestEventBusBase {
eventBus.stop();
}
-
public static class MyEvent implements BusEvent {
-
private final String name;
private final Long value;
private final UUID userToken;
@@ -102,7 +101,6 @@ public class TestEventBusBase {
}
}
-
public static final class MyOtherEvent implements BusEvent {
private final String name;
@@ -110,7 +108,6 @@ public class TestEventBusBase {
private final UUID userToken;
private final String type;
-
@JsonCreator
public MyOtherEvent(@JsonProperty("name") final String name,
@JsonProperty("value") final Double value,
@@ -159,7 +156,6 @@ public class TestEventBusBase {
private volatile int gotEvents;
-
public MyEventHandler(final int exp) {
this.expectedEvents = exp;
this.gotEvents = 0;
@@ -206,15 +202,12 @@ public class TestEventBusBase {
eventBus.post(new MyEventWithException("my-event", 1L, UUID.randomUUID(), BusEventType.ACCOUNT_CHANGE.toString()));
Thread.sleep(50000);
- } catch (Exception e) {
-
+ } catch (Exception ignored) {
}
-
}
public void testSimple() {
try {
-
final int nbEvents = 5;
final MyEventHandler handler = new MyEventHandler(nbEvents);
eventBus.register(handler);
@@ -232,7 +225,6 @@ public class TestEventBusBase {
public void testDifferentType() {
try {
-
final MyEventHandler handler = new MyEventHandler(1);
eventBus.register(handler);
@@ -246,6 +238,5 @@ public class TestEventBusBase {
} catch (Exception e) {
Assert.fail("", e);
}
-
}
}
diff --git a/util/src/test/java/com/ning/billing/util/bus/TestPersistentEventBus.java b/util/src/test/java/com/ning/billing/util/bus/TestPersistentEventBus.java
index 1b58ce1..2fb937b 100644
--- a/util/src/test/java/com/ning/billing/util/bus/TestPersistentEventBus.java
+++ b/util/src/test/java/com/ning/billing/util/bus/TestPersistentEventBus.java
@@ -13,17 +13,17 @@
* License for the specific language governing permissions and limitations
* under the License.
*/
+
package com.ning.billing.util.bus;
import org.skife.config.ConfigurationObjectFactory;
import org.skife.jdbi.v2.IDBI;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.DBIProvider;
import com.ning.billing.dbi.DbiConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
@@ -31,28 +31,12 @@ import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
import com.ning.billing.util.glue.BusModule;
import com.ning.billing.util.glue.BusModule.BusType;
-import com.ning.billing.util.io.IOUtils;
@Guice(modules = TestPersistentEventBus.PersistentBusModuleTest.class)
public class TestPersistentEventBus extends TestEventBusBase {
@Inject
private MysqlTestingHelper helper;
- @BeforeClass(groups = {"slow"})
- public void setup() throws Exception {
- helper.startMysql();
- final String ddl = IOUtils.toString(TestPersistentEventBus.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- helper.initDb(ddl);
- cleanup();
- super.setup();
- }
-
- @BeforeMethod(groups = {"slow"})
- public void cleanup() {
- helper.cleanupTable("bus_events");
- helper.cleanupTable("claimed_bus_events");
- }
-
public static class PersistentBusModuleTest extends AbstractModule {
@Override
protected void configure() {
@@ -61,7 +45,7 @@ public class TestPersistentEventBus extends TestEventBusBase {
bind(Clock.class).to(ClockMock.class).asEagerSingleton();
bind(ClockMock.class).asEagerSingleton();
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
if (helper.isUsingLocalInstance()) {
bind(IDBI.class).toProvider(DBIProvider.class).asEagerSingleton();
@@ -75,16 +59,14 @@ public class TestPersistentEventBus extends TestEventBusBase {
}
}
- @Test(groups = {"slow"})
+ @Test(groups = "slow")
public void testSimple() {
super.testSimple();
}
// Until Guava fixes exception handling, r13?
- @Test(groups = {"slow"}, enabled = false)
+ @Test(groups = "slow", enabled = false)
public void testSimpleWithException() {
super.testSimpleWithException();
-
}
-
}
diff --git a/util/src/test/java/com/ning/billing/util/callcontext/TestCallContext.java b/util/src/test/java/com/ning/billing/util/callcontext/TestCallContext.java
index 3ed0f8d..2ecc629 100644
--- a/util/src/test/java/com/ning/billing/util/callcontext/TestCallContext.java
+++ b/util/src/test/java/com/ning/billing/util/callcontext/TestCallContext.java
@@ -23,7 +23,6 @@ import org.joda.time.DateTime;
import com.ning.billing.util.clock.DefaultClock;
public class TestCallContext implements CallContext {
-
private final String userName;
private final DateTime updatedDate;
private final DateTime createdDate;
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 d8542e0..681b0b2 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
@@ -32,11 +32,9 @@ import com.ning.billing.catalog.api.Duration;
import com.ning.billing.catalog.api.TimeUnit;
public class ClockMock implements Clock {
-
private MutablePeriod delta = new MutablePeriod();
private static final Logger log = LoggerFactory.getLogger(ClockMock.class);
-
@Override
public synchronized DateTime getNow(final DateTimeZone tz) {
return getUTCNow().toDateTime(tz);
@@ -146,6 +144,4 @@ public class ClockMock implements Clock {
return new Period();
}
}
-
-
}
diff --git a/util/src/test/java/com/ning/billing/util/clock/OldClockMock.java b/util/src/test/java/com/ning/billing/util/clock/OldClockMock.java
index b032bed..4197b24 100644
--- a/util/src/test/java/com/ning/billing/util/clock/OldClockMock.java
+++ b/util/src/test/java/com/ning/billing/util/clock/OldClockMock.java
@@ -158,6 +158,4 @@ public class OldClockMock extends DefaultClock {
public String toString() {
return getUTCNow().toString();
}
-
-
}
diff --git a/util/src/test/java/com/ning/billing/util/config/TestXMLLoader.java b/util/src/test/java/com/ning/billing/util/config/TestXMLLoader.java
index 96f7a06..0c3a5dd 100644
--- a/util/src/test/java/com/ning/billing/util/config/TestXMLLoader.java
+++ b/util/src/test/java/com/ning/billing/util/config/TestXMLLoader.java
@@ -28,11 +28,12 @@ import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import com.ning.billing.catalog.api.InvalidConfigException;
+import com.ning.billing.util.UtilTestSuite;
import static org.testng.Assert.assertEquals;
-public class TestXMLLoader {
+public class TestXMLLoader extends UtilTestSuite {
public static final String TEST_XML =
"<xmlTestClass>" +
" <foo>foo</foo>" +
@@ -40,7 +41,7 @@ public class TestXMLLoader {
" <lala>42</lala>" +
"</xmlTestClass>";
- @Test
+ @Test(groups = "fast")
public void test() throws SAXException, InvalidConfigException, JAXBException, IOException, TransformerException, URISyntaxException, ValidationException {
final InputStream is = new ByteArrayInputStream(TEST_XML.getBytes());
final XmlTestClass test = XMLLoader.getObjectFromStream(new URI("internal:/"), is, XmlTestClass.class);
@@ -48,6 +49,4 @@ public class TestXMLLoader {
assertEquals(test.getBar(), 1.0);
assertEquals(test.getLala(), 42);
}
-
-
}
diff --git a/util/src/test/java/com/ning/billing/util/config/TestXMLSchemaGenerator.java b/util/src/test/java/com/ning/billing/util/config/TestXMLSchemaGenerator.java
index 8eae647..fde04b0 100644
--- a/util/src/test/java/com/ning/billing/util/config/TestXMLSchemaGenerator.java
+++ b/util/src/test/java/com/ning/billing/util/config/TestXMLSchemaGenerator.java
@@ -23,9 +23,10 @@ import java.io.InputStream;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.io.IOUtils;
-public class TestXMLSchemaGenerator {
+public class TestXMLSchemaGenerator extends UtilTestSuite {
@Test(groups = "fast", enabled = false)
public void test() throws IOException, TransformerException, JAXBException {
final InputStream stream = XMLSchemaGenerator.xmlSchema(XmlTestClass.class);
diff --git a/util/src/test/java/com/ning/billing/util/config/TestXMLWriter.java b/util/src/test/java/com/ning/billing/util/config/TestXMLWriter.java
index 11878b9..53c854a 100644
--- a/util/src/test/java/com/ning/billing/util/config/TestXMLWriter.java
+++ b/util/src/test/java/com/ning/billing/util/config/TestXMLWriter.java
@@ -22,9 +22,11 @@ import java.net.URI;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
+
import static org.testng.Assert.assertEquals;
-public class TestXMLWriter {
+public class TestXMLWriter extends UtilTestSuite {
public static final String TEST_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<xmlTestClass>" +
@@ -33,7 +35,7 @@ public class TestXMLWriter {
"<lala>42</lala>" +
"</xmlTestClass>";
- @Test
+ @Test(groups = "fast")
public void test() throws Exception {
final InputStream is = new ByteArrayInputStream(TEST_XML.getBytes());
final XmlTestClass test = XMLLoader.getObjectFromStream(new URI("internal:/"), is, XmlTestClass.class);
@@ -42,11 +44,7 @@ public class TestXMLWriter {
assertEquals(test.getLala(), 42);
final String output = XMLWriter.writeXML(test, XmlTestClass.class);
-
- System.out.println(output);
+ //System.out.println(output);
assertEquals(output.replaceAll("\\s", ""), TEST_XML.replaceAll("\\s", ""));
-
}
-
-
}
diff --git a/util/src/test/java/com/ning/billing/util/customfield/TestFieldStore.java b/util/src/test/java/com/ning/billing/util/customfield/TestFieldStore.java
index e5caad4..6182629 100644
--- a/util/src/test/java/com/ning/billing/util/customfield/TestFieldStore.java
+++ b/util/src/test/java/com/ning/billing/util/customfield/TestFieldStore.java
@@ -22,11 +22,12 @@ import java.util.UUID;
import org.skife.jdbi.v2.IDBI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.callcontext.CallContext;
import com.ning.billing.util.callcontext.CallOrigin;
import com.ning.billing.util.callcontext.DefaultCallContextFactory;
@@ -36,28 +37,20 @@ import com.ning.billing.util.customfield.dao.AuditedCustomFieldDao;
import com.ning.billing.util.customfield.dao.CustomFieldDao;
import com.ning.billing.util.customfield.dao.CustomFieldSqlDao;
import com.ning.billing.util.dao.ObjectType;
-import com.ning.billing.util.io.IOUtils;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
-@Test(groups = {"util", "slow"})
-public class TestFieldStore {
- Logger log = LoggerFactory.getLogger(TestFieldStore.class);
- private final MysqlTestingHelper helper = new MysqlTestingHelper();
+public class TestFieldStore extends UtilTestSuiteWithEmbeddedDB {
+ private final Logger log = LoggerFactory.getLogger(TestFieldStore.class);
+ private final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
private CallContext context;
private IDBI dbi;
private CustomFieldDao customFieldDao;
- @BeforeClass(groups = {"util", "slow"})
+ @BeforeClass(groups = "slow")
protected void setup() throws IOException {
- // Health check test to make sure MySQL is setup properly
try {
- final String utilDdl = IOUtils.toString(TestFieldStore.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
-
dbi = helper.getDBI();
customFieldDao = new AuditedCustomFieldDao(dbi);
context = new DefaultCallContextFactory(new ClockMock()).createCallContext("Fezzik", CallOrigin.TEST, UserType.TEST);
@@ -67,14 +60,7 @@ public class TestFieldStore {
}
}
- @AfterClass(groups = {"util", "slow"})
- public void stopMysql() {
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
- @Test
+ @Test(groups = "slow")
public void testFieldStore() {
final UUID id = UUID.randomUUID();
final ObjectType objectType = ObjectType.ACCOUNT;
diff --git a/util/src/test/java/com/ning/billing/util/email/DefaultCatalogTranslationTest.java b/util/src/test/java/com/ning/billing/util/email/DefaultCatalogTranslationTest.java
index d092a5a..4fe5198 100644
--- a/util/src/test/java/com/ning/billing/util/email/DefaultCatalogTranslationTest.java
+++ b/util/src/test/java/com/ning/billing/util/email/DefaultCatalogTranslationTest.java
@@ -23,17 +23,17 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.template.translation.DefaultCatalogTranslator;
import com.ning.billing.util.template.translation.Translator;
import com.ning.billing.util.template.translation.TranslatorConfig;
import static org.testng.Assert.assertEquals;
-@Test(groups = {"fast", "email"})
-public class DefaultCatalogTranslationTest {
+public class DefaultCatalogTranslationTest extends UtilTestSuite {
private Translator translation;
- @BeforeClass(groups = {"fast", "email"})
+ @BeforeClass(groups = "fast")
public void setup() {
final ConfigSource configSource = new ConfigSource() {
private final Map<String, String> properties = ImmutableMap.<String, String>of("killbill.template.invoiceFormatterFactoryClass",
@@ -49,49 +49,49 @@ public class DefaultCatalogTranslationTest {
translation = new DefaultCatalogTranslator(config);
}
- @Test(groups = {"fast", "email"}, enabled = false)
+ @Test(groups = "fast")
public void testInitialization() {
- final String ningPlusText = "ning-plus";
- final String ningProText = "ning-pro";
+ final String shotgunMonthly = "shotgun-monthly";
+ final String shotgunAnnual = "shotgun-annual";
final String badText = "Bad text";
- assertEquals(translation.getTranslation(Locale.US, ningPlusText), "Plus");
- assertEquals(translation.getTranslation(Locale.US, ningProText), "Pro");
+ assertEquals(translation.getTranslation(Locale.US, shotgunMonthly), "Monthly shotgun plan");
+ assertEquals(translation.getTranslation(Locale.US, shotgunAnnual), "Annual shotgun plan");
assertEquals(translation.getTranslation(Locale.US, badText), badText);
- assertEquals(translation.getTranslation(Locale.CANADA_FRENCH, ningPlusText), "Plus en francais");
- assertEquals(translation.getTranslation(Locale.CANADA_FRENCH, ningProText), "Pro");
+ assertEquals(translation.getTranslation(Locale.CANADA_FRENCH, shotgunMonthly), "Fusil de chasse mensuel");
+ assertEquals(translation.getTranslation(Locale.CANADA_FRENCH, shotgunAnnual), "Fusil de chasse annuel");
assertEquals(translation.getTranslation(Locale.CANADA_FRENCH, badText), badText);
- assertEquals(translation.getTranslation(Locale.CHINA, ningPlusText), "Plus");
- assertEquals(translation.getTranslation(Locale.CHINA, ningProText), "Pro");
+ assertEquals(translation.getTranslation(Locale.CHINA, shotgunMonthly), "Monthly shotgun plan");
+ assertEquals(translation.getTranslation(Locale.CHINA, shotgunAnnual), "Annual shotgun plan");
assertEquals(translation.getTranslation(Locale.CHINA, badText), badText);
}
- @Test(enabled = false)
+ @Test(groups = "fast")
public void testExistingTranslation() {
- // if the translation exists, return the translation
- final String originalText = "ning-plus";
- assertEquals(translation.getTranslation(Locale.US, originalText), "Plus");
+ // If the translation exists, return the translation
+ final String originalText = "shotgun-monthly";
+ assertEquals(translation.getTranslation(Locale.US, originalText), "Monthly shotgun plan");
}
- @Test
+ @Test(groups = "fast")
public void testMissingTranslation() {
- // if the translation is missing from the file, return the original text
+ // If the translation is missing from the file, return the original text
final String originalText = "missing translation";
assertEquals(translation.getTranslation(Locale.US, originalText), originalText);
}
- @Test(enabled = false)
+ @Test(groups = "fast")
public void testMissingTranslationFileWithEnglishText() {
- // if the translation file doesn't exist, return the "English" translation
- final String originalText = "ning-plus";
- assertEquals(translation.getTranslation(Locale.CHINA, originalText), "Plus");
+ // If the translation file doesn't exist, return the "English" translation
+ final String originalText = "shotgun-monthly";
+ assertEquals(translation.getTranslation(Locale.CHINA, originalText), "Monthly shotgun plan");
}
- @Test
+ @Test(groups = "fast")
public void testMissingFileAndText() {
- // if the file is missing, and the "English" translation is missing, return the original text
+ // If the file is missing, and the "English" translation is missing, return the original text
final String originalText = "missing translation";
assertEquals(translation.getTranslation(Locale.CHINA, originalText), originalText);
}
diff --git a/util/src/test/java/com/ning/billing/util/email/EmailSenderTest.java b/util/src/test/java/com/ning/billing/util/email/EmailSenderTest.java
index b3e4d64..81b40d9 100644
--- a/util/src/test/java/com/ning/billing/util/email/EmailSenderTest.java
+++ b/util/src/test/java/com/ning/billing/util/email/EmailSenderTest.java
@@ -21,8 +21,10 @@ import org.skife.config.ConfigurationObjectFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-@Test(groups = {"slow", "email"})
-public class EmailSenderTest {
+import com.ning.billing.util.UtilTestSuite;
+
+@Test(groups = "slow")
+public class EmailSenderTest extends UtilTestSuite {
private EmailConfig config;
@BeforeClass
diff --git a/util/src/test/java/com/ning/billing/util/globallocker/MockGlobalLocker.java b/util/src/test/java/com/ning/billing/util/globallocker/MockGlobalLocker.java
index 4a1ff01..4466b1a 100644
--- a/util/src/test/java/com/ning/billing/util/globallocker/MockGlobalLocker.java
+++ b/util/src/test/java/com/ning/billing/util/globallocker/MockGlobalLocker.java
@@ -17,9 +17,8 @@
package com.ning.billing.util.globallocker;
public class MockGlobalLocker implements GlobalLocker {
-
@Override
- public GlobalLock lockWithNumberOfTries(final LockerService service,
+ public GlobalLock lockWithNumberOfTries(final LockerType service,
final String lockKey, final int retry) {
return new GlobalLock() {
@Override
@@ -29,7 +28,7 @@ public class MockGlobalLocker implements GlobalLocker {
}
@Override
- public Boolean isFree(final LockerService service, final String lockKey) {
+ public Boolean isFree(final LockerType service, final String lockKey) {
return Boolean.TRUE;
}
}
diff --git a/util/src/test/java/com/ning/billing/util/globallocker/TestMysqlGlobalLocker.java b/util/src/test/java/com/ning/billing/util/globallocker/TestMysqlGlobalLocker.java
index 4619b42..ed05f5f 100644
--- a/util/src/test/java/com/ning/billing/util/globallocker/TestMysqlGlobalLocker.java
+++ b/util/src/test/java/com/ning/billing/util/globallocker/TestMysqlGlobalLocker.java
@@ -24,49 +24,39 @@ import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.MysqlTestingHelper;
-import com.ning.billing.util.globallocker.GlobalLocker.LockerService;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
+import com.ning.billing.util.globallocker.GlobalLocker.LockerType;
import com.ning.billing.util.io.IOUtils;
-@Test(groups = "slow")
@Guice(modules = TestMysqlGlobalLocker.TestMysqlGlobalLockerModule.class)
-public class TestMysqlGlobalLocker {
-
+public class TestMysqlGlobalLocker extends UtilTestSuiteWithEmbeddedDB {
@Inject
private IDBI dbi;
@Inject
private MysqlTestingHelper helper;
- @BeforeClass(groups = "slow")
+ @BeforeMethod(groups = "slow")
public void setup() throws IOException {
final String testDdl = IOUtils.toString(TestMysqlGlobalLocker.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
- helper.startMysql();
helper.initDb(testDdl);
}
- @AfterClass(groups = "slow")
- public void tearDown() {
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
// Used as a manual test to validate the simple DAO by stepping through that locking is done and release correctly
- @Test(groups = "slow", enabled = true)
+ @Test(groups = "slow")
public void testSimpleLocking() {
-
final String lockName = UUID.randomUUID().toString();
final GlobalLocker locker = new MySqlGlobalLocker(dbi);
- final GlobalLock lock = locker.lockWithNumberOfTries(LockerService.INVOICE, lockName, 3);
+ final GlobalLock lock = locker.lockWithNumberOfTries(LockerType.ACCOUNT, lockName, 3);
dbi.inTransaction(new TransactionCallback<Void>() {
@Override
@@ -76,11 +66,11 @@ public class TestMysqlGlobalLocker {
return null;
}
});
- Assert.assertEquals(locker.isFree(LockerService.INVOICE, lockName), Boolean.FALSE);
+ Assert.assertEquals(locker.isFree(LockerType.ACCOUNT, lockName), Boolean.FALSE);
boolean gotException = false;
try {
- locker.lockWithNumberOfTries(LockerService.INVOICE, lockName, 1);
+ locker.lockWithNumberOfTries(LockerType.ACCOUNT, lockName, 1);
} catch (LockFailedException e) {
gotException = true;
}
@@ -88,14 +78,13 @@ public class TestMysqlGlobalLocker {
lock.release();
- Assert.assertEquals(locker.isFree(LockerService.INVOICE, lockName), Boolean.TRUE);
+ Assert.assertEquals(locker.isFree(LockerType.ACCOUNT, lockName), Boolean.TRUE);
}
public static final class TestMysqlGlobalLockerModule extends AbstractModule {
-
@Override
protected void configure() {
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
diff --git a/util/src/test/java/com/ning/billing/util/notificationq/dao/TestNotificationSqlDao.java b/util/src/test/java/com/ning/billing/util/notificationq/dao/TestNotificationSqlDao.java
index d7141d3..ba2232a 100644
--- a/util/src/test/java/com/ning/billing/util/notificationq/dao/TestNotificationSqlDao.java
+++ b/util/src/test/java/com/ning/billing/util/notificationq/dao/TestNotificationSqlDao.java
@@ -16,8 +16,6 @@
package com.ning.billing.util.notificationq.dao;
-import java.io.IOException;
-import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
@@ -27,7 +25,6 @@ import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.tweak.HandleCallback;
import org.testng.Assert;
-import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Guice;
@@ -35,8 +32,9 @@ import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.MysqlTestingHelper;
-import com.ning.billing.util.io.IOUtils;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.notificationq.DefaultNotification;
import com.ning.billing.util.notificationq.Notification;
import com.ning.billing.util.notificationq.dao.NotificationSqlDao.NotificationSqlMapper;
@@ -45,9 +43,9 @@ import com.ning.billing.util.queue.PersistentQueueEntryLifecycle.PersistentQueue
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
-@Test(groups = "slow")
@Guice(modules = TestNotificationSqlDao.TestNotificationSqlDaoModule.class)
-public class TestNotificationSqlDao {
+public class TestNotificationSqlDao extends UtilTestSuiteWithEmbeddedDB {
+ private static final UUID accountId = UUID.randomUUID();
private static final String hostname = "Yop";
@Inject
@@ -58,34 +56,14 @@ public class TestNotificationSqlDao {
private NotificationSqlDao dao;
- private void startMysql() throws IOException, ClassNotFoundException, SQLException {
- final String ddl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- helper.startMysql();
- helper.initDb(ddl);
- }
-
@BeforeSuite(groups = "slow")
public void setup() {
- try {
- startMysql();
- dao = dbi.onDemand(NotificationSqlDao.class);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @AfterSuite(groups = "slow")
- public void stopMysql() {
- if (helper != null) {
- helper.stopMysql();
- }
+ dao = dbi.onDemand(NotificationSqlDao.class);
}
-
@BeforeTest(groups = "slow")
public void cleanupDb() {
dbi.withHandle(new HandleCallback<Void>() {
-
@Override
public Void withHandle(final Handle handle) throws Exception {
handle.execute("delete from notifications");
@@ -95,14 +73,13 @@ public class TestNotificationSqlDao {
});
}
- @Test
+ @Test(groups = "slow")
public void testBasic() throws InterruptedException {
-
final String ownerId = UUID.randomUUID().toString();
final String notificationKey = UUID.randomUUID().toString();
final DateTime effDt = new DateTime();
- final Notification notif = new DefaultNotification("testBasic", hostname, notificationKey.getClass().getName(), notificationKey, effDt);
+ final Notification notif = new DefaultNotification("testBasic", hostname, notificationKey.getClass().getName(), notificationKey, accountId, effDt);
dao.insertNotification(notif);
Thread.sleep(1000);
@@ -126,7 +103,7 @@ public class TestNotificationSqlDao {
notification = fetchNotification(notification.getId().toString());
assertEquals(notification.getNotificationKey(), notificationKey);
validateDate(notification.getEffectiveDate(), effDt);
- assertEquals(notification.getOwner().toString(), ownerId);
+ assertEquals(notification.getOwner(), ownerId);
assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.IN_PROCESSING);
validateDate(notification.getNextAvailableDate(), nextAvailable);
@@ -138,35 +115,56 @@ public class TestNotificationSqlDao {
//assertEquals(notification.getOwner(), null);
assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.PROCESSED);
validateDate(notification.getNextAvailableDate(), nextAvailable);
+ }
+ @Test(groups = "slow")
+ public void testGetByAccountAndDate() throws InterruptedException {
+ final String notificationKey = UUID.randomUUID().toString();
+ final DateTime effDt = new DateTime();
+ final Notification notif1 = new DefaultNotification("testBasic1", hostname, notificationKey.getClass().getName(), notificationKey, accountId, effDt);
+ dao.insertNotification(notif1);
+
+ final Notification notif2 = new DefaultNotification("testBasic2", hostname, notificationKey.getClass().getName(), notificationKey, accountId, effDt);
+ dao.insertNotification(notif2);
+
+ List<Notification> notifications = dao.getNotificationForAccountAndDate(accountId.toString(), effDt.toDate());
+ assertEquals(notifications.size(), 2);
+ for (final Notification cur : notifications) {
+ Assert.assertEquals(cur.getProcessingState(), PersistentQueueEntryLifecycleState.AVAILABLE);
+ dao.removeNotification(cur.getId().toString());
+ }
+
+ notifications = dao.getNotificationForAccountAndDate(accountId.toString(), effDt.toDate());
+ assertEquals(notifications.size(), 2);
+ for (final Notification cur : notifications) {
+ Assert.assertEquals(cur.getProcessingState(), PersistentQueueEntryLifecycleState.REMOVED);
+ }
}
private Notification fetchNotification(final String notificationId) {
- final Notification res = dbi.withHandle(new HandleCallback<Notification>() {
-
+ return dbi.withHandle(new HandleCallback<Notification>() {
@Override
public Notification withHandle(final Handle handle) throws Exception {
- final Notification res = handle.createQuery(" select" +
- " record_id " +
- ", id" +
- ", class_name" +
- ", notification_key" +
- ", created_date" +
- ", creating_owner" +
- ", effective_date" +
- ", queue_name" +
- ", processing_owner" +
- ", processing_available_date" +
- ", processing_state" +
- " from notifications " +
- " where " +
- " id = '" + notificationId + "';")
- .map(new NotificationSqlMapper())
- .first();
- return res;
+ return handle.createQuery(" select" +
+ " record_id " +
+ ", id" +
+ ", class_name" +
+ ", account_id" +
+ ", notification_key" +
+ ", created_date" +
+ ", creating_owner" +
+ ", effective_date" +
+ ", queue_name" +
+ ", processing_owner" +
+ ", processing_available_date" +
+ ", processing_state" +
+ " from notifications " +
+ " where " +
+ " id = '" + notificationId + "';")
+ .map(new NotificationSqlMapper())
+ .first();
}
});
- return res;
}
private void validateDate(DateTime input, DateTime expected) {
@@ -192,8 +190,7 @@ public class TestNotificationSqlDao {
public static class TestNotificationSqlDaoModule extends AbstractModule {
@Override
protected void configure() {
-
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
diff --git a/util/src/test/java/com/ning/billing/util/notificationq/MockNotificationQueue.java b/util/src/test/java/com/ning/billing/util/notificationq/MockNotificationQueue.java
index 5e7d607..259952c 100644
--- a/util/src/test/java/com/ning/billing/util/notificationq/MockNotificationQueue.java
+++ b/util/src/test/java/com/ning/billing/util/notificationq/MockNotificationQueue.java
@@ -19,9 +19,9 @@ package com.ning.billing.util.notificationq;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
-import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
+import java.util.UUID;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.sqlobject.mixins.Transmogrifier;
@@ -33,10 +33,10 @@ import com.ning.billing.util.notificationq.NotificationQueueService.Notification
import com.ning.billing.util.queue.PersistentQueueEntryLifecycle.PersistentQueueEntryLifecycleState;
public class MockNotificationQueue extends NotificationQueueBase implements NotificationQueue {
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
private final TreeSet<Notification> notifications;
- ObjectMapper objectMapper = new ObjectMapper();
-
public MockNotificationQueue(final Clock clock, final String svcName, final String queueName, final NotificationQueueHandler handler, final NotificationConfig config) {
super(clock, svcName, queueName, handler, config);
notifications = new TreeSet<Notification>(new Comparator<Notification>() {
@@ -52,19 +52,17 @@ public class MockNotificationQueue extends NotificationQueueBase implements Noti
}
@Override
- public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationKey notificationKey) throws IOException {
+ public void recordFutureNotification(final DateTime futureNotificationTime, final UUID accountId, final NotificationKey notificationKey) throws IOException {
final String json = objectMapper.writeValueAsString(notificationKey);
- final Notification notification = new DefaultNotification("MockQueue", hostname, notificationKey.getClass().getName(), json, futureNotificationTime);
+ final Notification notification = new DefaultNotification("MockQueue", getHostname(), notificationKey.getClass().getName(), json, accountId, futureNotificationTime);
synchronized (notifications) {
notifications.add(notification);
}
}
@Override
- public void recordFutureNotificationFromTransaction(
- final Transmogrifier transactionalDao, final DateTime futureNotificationTime,
- final NotificationKey notificationKey) throws IOException {
- recordFutureNotification(futureNotificationTime, notificationKey);
+ public void recordFutureNotificationFromTransaction(final Transmogrifier transactionalDao, final DateTime futureNotificationTime, final UUID accountId, final NotificationKey notificationKey) throws IOException {
+ recordFutureNotification(futureNotificationTime, accountId, notificationKey);
}
public List<Notification> getPendingEvents() {
@@ -75,23 +73,20 @@ public class MockNotificationQueue extends NotificationQueueBase implements Noti
result.add(notification);
}
}
+
return result;
}
@Override
public int doProcessEvents() {
-
- int result = 0;
-
+ final int result;
final List<Notification> processedNotifications = new ArrayList<Notification>();
final List<Notification> oldNotifications = new ArrayList<Notification>();
final List<Notification> readyNotifications = new ArrayList<Notification>();
synchronized (notifications) {
- final Iterator<Notification> it = notifications.iterator();
- while (it.hasNext()) {
- final Notification cur = it.next();
- if (cur.isAvailableForProcessing(clock.getUTCNow())) {
+ for (final Notification cur : notifications) {
+ if (cur.isAvailableForProcessing(getClock().getUTCNow())) {
readyNotifications.add(cur);
}
}
@@ -99,15 +94,16 @@ public class MockNotificationQueue extends NotificationQueueBase implements Noti
result = readyNotifications.size();
for (final Notification cur : readyNotifications) {
-
-
- NotificationKey key = deserializeEvent(cur.getNotificationKeyClass(), cur.getNotificationKey());
- handler.handleReadyNotification(key, cur.getEffectiveDate());
- final DefaultNotification processedNotification = new DefaultNotification(-1L, cur.getId(), hostname, hostname, "MockQueue", clock.getUTCNow().plus(CLAIM_TIME_MS), PersistentQueueEntryLifecycleState.PROCESSED,
- cur.getNotificationKeyClass(), cur.getNotificationKey(), cur.getEffectiveDate());
+ final NotificationKey key = deserializeEvent(cur.getNotificationKeyClass(), cur.getNotificationKey());
+ getHandler().handleReadyNotification(key, cur.getEffectiveDate());
+ final DefaultNotification processedNotification = new DefaultNotification(-1L, cur.getId(), getHostname(), getHostname(),
+ "MockQueue", getClock().getUTCNow().plus(CLAIM_TIME_MS),
+ PersistentQueueEntryLifecycleState.PROCESSED, cur.getNotificationKeyClass(),
+ cur.getNotificationKey(), cur.getAccountId(), cur.getEffectiveDate());
oldNotifications.add(cur);
processedNotifications.add(processedNotification);
}
+
synchronized (notifications) {
if (oldNotifications.size() > 0) {
notifications.removeAll(oldNotifications);
@@ -117,6 +113,7 @@ public class MockNotificationQueue extends NotificationQueueBase implements Noti
notifications.addAll(processedNotifications);
}
}
+
return result;
}
@@ -128,11 +125,24 @@ public class MockNotificationQueue extends NotificationQueueBase implements Noti
toClearNotifications.add(notification);
}
}
+
synchronized (notifications) {
if (toClearNotifications.size() > 0) {
notifications.removeAll(toClearNotifications);
}
}
+ }
+
+ @Override
+ public List<Notification> getNotificationForAccountAndDate(UUID accountId,
+ DateTime effectiveDate) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public void removeNotification(UUID notificationId) {
+ // TODO Auto-generated method stub
}
}
diff --git a/util/src/test/java/com/ning/billing/util/notificationq/TestNotificationQueue.java b/util/src/test/java/com/ning/billing/util/notificationq/TestNotificationQueue.java
index 11db32e..32fdc70 100644
--- a/util/src/test/java/com/ning/billing/util/notificationq/TestNotificationQueue.java
+++ b/util/src/test/java/com/ning/billing/util/notificationq/TestNotificationQueue.java
@@ -16,8 +16,6 @@
package com.ning.billing.util.notificationq;
-import java.io.IOException;
-import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
@@ -34,7 +32,6 @@ import org.skife.jdbi.v2.tweak.HandleCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Guice;
@@ -47,8 +44,10 @@ import com.google.common.collect.Collections2;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.name.Names;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.config.NotificationConfig;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
import com.ning.billing.util.io.IOUtils;
@@ -59,10 +58,12 @@ import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.testng.Assert.assertEquals;
-@Test(groups = "slow")
@Guice(modules = TestNotificationQueue.TestNotificationQueueModule.class)
-public class TestNotificationQueue {
- Logger log = LoggerFactory.getLogger(TestNotificationQueue.class);
+public class TestNotificationQueue extends UtilTestSuiteWithEmbeddedDB {
+ private final Logger log = LoggerFactory.getLogger(TestNotificationQueue.class);
+
+ private static final UUID accountId = UUID.randomUUID();
+
@Inject
private IDBI dbi;
@@ -76,23 +77,11 @@ public class TestNotificationQueue {
private int eventsReceived;
- // private NotificationQueue queue;
-
- private void startMysql() throws IOException, ClassNotFoundException, SQLException {
- final String ddl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
- final String testDdl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
- helper.startMysql();
- helper.initDb(ddl);
- helper.initDb(testDdl);
- }
-
-
- private final static class TestNotificationKey implements NotificationKey, Comparable<TestNotificationKey> {
-
+ private static final class TestNotificationKey implements NotificationKey, Comparable<TestNotificationKey> {
private final String value;
@JsonCreator
- public TestNotificationKey(@JsonProperty("value") String value) {
+ public TestNotificationKey(@JsonProperty("value") final String value) {
super();
this.value = value;
}
@@ -106,21 +95,14 @@ public class TestNotificationQueue {
return value.compareTo(arg0.value);
}
}
-
-
+
@BeforeSuite(groups = "slow")
public void setup() throws Exception {
- startMysql();
+ final String testDdl = IOUtils.toString(NotificationSqlDao.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
+ helper.initDb(testDdl);
dao = dbi.onDemand(DummySqlTest.class);
}
- @AfterClass(groups = "slow")
- public void tearDown() {
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
@BeforeTest(groups = "slow")
public void beforeTest() {
dbi.withHandle(new HandleCallback<Void>() {
@@ -138,32 +120,30 @@ public class TestNotificationQueue {
eventsReceived = 0;
}
-
/**
* Test that we can post a notification in the future from a transaction and get the notification
* callback with the correct key when the time is ready
*
* @throws Exception
*/
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testSimpleNotification() throws Exception {
final Map<NotificationKey, Boolean> expectedNotifications = new TreeMap<NotificationKey, Boolean>();
final DefaultNotificationQueue queue = new DefaultNotificationQueue(dbi, clock, "test-svc", "foo",
- new NotificationQueueHandler() {
- @Override
- public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDateTime) {
- synchronized (expectedNotifications) {
- log.info("Handler received key: " + notificationKey);
-
- expectedNotifications.put(notificationKey, Boolean.TRUE);
- expectedNotifications.notify();
- }
- }
- },
- getNotificationConfig(false, 100, 1, 10000));
-
+ new NotificationQueueHandler() {
+ @Override
+ public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDateTime) {
+ synchronized (expectedNotifications) {
+ log.info("Handler received key: " + notificationKey);
+
+ expectedNotifications.put(notificationKey, Boolean.TRUE);
+ expectedNotifications.notify();
+ }
+ }
+ },
+ getNotificationConfig(false, 100, 1, 10000));
queue.startQueue();
@@ -175,16 +155,15 @@ public class TestNotificationQueue {
expectedNotifications.put(notificationKey, Boolean.FALSE);
-
// Insert dummy to be processed in 2 sec'
dao.inTransaction(new Transaction<Void, DummySqlTest>() {
@Override
public Void inTransaction(final DummySqlTest transactional,
- final TransactionStatus status) throws Exception {
+ final TransactionStatus status) throws Exception {
transactional.insertDummy(obj);
queue.recordFutureNotificationFromTransaction(transactional,
- readyTime, notificationKey);
+ readyTime, accountId, notificationKey);
log.info("Posted key: " + notificationKey);
return null;
@@ -211,17 +190,16 @@ public class TestNotificationQueue {
final Map<NotificationKey, Boolean> expectedNotifications = new TreeMap<NotificationKey, Boolean>();
final DefaultNotificationQueue queue = new DefaultNotificationQueue(dbi, clock, "test-svc", "many",
- new NotificationQueueHandler() {
- @Override
- public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDateTime) {
- synchronized (expectedNotifications) {
- expectedNotifications.put(notificationKey, Boolean.TRUE);
- expectedNotifications.notify();
- }
- }
- },
- getNotificationConfig(false, 100, 10, 10000));
-
+ new NotificationQueueHandler() {
+ @Override
+ public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDateTime) {
+ synchronized (expectedNotifications) {
+ expectedNotifications.put(notificationKey, Boolean.TRUE);
+ expectedNotifications.notify();
+ }
+ }
+ },
+ getNotificationConfig(false, 100, 10, 10000));
queue.startQueue();
@@ -241,11 +219,11 @@ public class TestNotificationQueue {
dao.inTransaction(new Transaction<Void, DummySqlTest>() {
@Override
public Void inTransaction(final DummySqlTest transactional,
- final TransactionStatus status) throws Exception {
+ final TransactionStatus status) throws Exception {
transactional.insertDummy(obj);
queue.recordFutureNotificationFromTransaction(transactional,
- now.plus((currentIteration + 1) * nextReadyTimeIncrementMs), notificationKey);
+ now.plus((currentIteration + 1) * nextReadyTimeIncrementMs), accountId, notificationKey);
return null;
}
});
@@ -263,7 +241,6 @@ public class TestNotificationQueue {
boolean success = false;
do {
synchronized (expectedNotifications) {
-
final Collection<Boolean> completed = Collections2.filter(expectedNotifications.values(), new Predicate<Boolean>() {
@Override
public boolean apply(final Boolean input) {
@@ -281,7 +258,7 @@ public class TestNotificationQueue {
} while (nbTry-- > 0);
queue.stopQueue();
- log.info("STEPH GOT SIZE " + Collections2.filter(expectedNotifications.values(), new Predicate<Boolean>() {
+ log.info("STEPH GOT SIZE " + Collections2.filter(expectedNotifications.values(), new Predicate<Boolean>() {
@Override
public boolean apply(final Boolean input) {
return input;
@@ -296,9 +273,8 @@ public class TestNotificationQueue {
*
* @throws Exception
*/
- @Test(groups = {"slow"}, enabled = true)
+ @Test(groups = "slow")
public void testMultipleHandlerNotification() throws Exception {
-
final Map<NotificationKey, Boolean> expectedNotificationsFred = new TreeMap<NotificationKey, Boolean>();
final Map<NotificationKey, Boolean> expectedNotificationsBarney = new TreeMap<NotificationKey, Boolean>();
@@ -316,7 +292,6 @@ public class TestNotificationQueue {
}
};
-
final NotificationQueue queueFred = notificationQueueService.createNotificationQueue("UtilTest", "Fred", new NotificationQueueHandler() {
@Override
public void handleReadyNotification(final NotificationKey notificationKey, final DateTime eventDateTime) {
@@ -325,7 +300,7 @@ public class TestNotificationQueue {
eventsReceived++;
}
},
- config);
+ config);
final NotificationQueue queueBarney = notificationQueueService.createNotificationQueue("UtilTest", "Barney", new NotificationQueueHandler() {
@Override
@@ -335,37 +310,34 @@ public class TestNotificationQueue {
eventsReceived++;
}
},
- config);
+ config);
queueFred.startQueue();
// We don't start Barney so it can never pick up notifications
-
final UUID key = UUID.randomUUID();
final DummyObject obj = new DummyObject("foo", key);
final DateTime now = new DateTime();
final DateTime readyTime = now.plusMillis(2000);
final NotificationKey notificationKeyFred = new TestNotificationKey("Fred");
-
- final NotificationKey notificationKeyBarney = new TestNotificationKey("Barney");
+ final NotificationKey notificationKeyBarney = new TestNotificationKey("Barney");
expectedNotificationsFred.put(notificationKeyFred, Boolean.FALSE);
expectedNotificationsFred.put(notificationKeyBarney, Boolean.FALSE);
-
// Insert dummy to be processed in 2 sec'
dao.inTransaction(new Transaction<Void, DummySqlTest>() {
@Override
public Void inTransaction(final DummySqlTest transactional,
- final TransactionStatus status) throws Exception {
+ final TransactionStatus status) throws Exception {
transactional.insertDummy(obj);
queueFred.recordFutureNotificationFromTransaction(transactional,
- readyTime, notificationKeyFred);
+ readyTime, accountId, notificationKeyFred);
log.info("posted key: " + notificationKeyFred.toString());
queueBarney.recordFutureNotificationFromTransaction(transactional,
- readyTime, notificationKeyBarney);
+ readyTime, accountId, notificationKeyBarney);
log.info("posted key: " + notificationKeyBarney.toString());
return null;
@@ -394,8 +366,7 @@ public class TestNotificationQueue {
Assert.assertFalse(expectedNotificationsFred.get(notificationKeyBarney));
}
- NotificationConfig getNotificationConfig(final boolean off,
- final long sleepTime, final int maxReadyEvents, final long claimTimeMs) {
+ NotificationConfig getNotificationConfig(final boolean off, final long sleepTime, final int maxReadyEvents, final long claimTimeMs) {
return new NotificationConfig() {
@Override
public boolean isNotificationProcessingOff() {
@@ -409,27 +380,24 @@ public class TestNotificationQueue {
};
}
-
@Test(groups = "slow")
public void testRemoveNotifications() throws InterruptedException {
-
final UUID key = UUID.randomUUID();
final NotificationKey notificationKey = new TestNotificationKey(key.toString());
final UUID key2 = UUID.randomUUID();
final NotificationKey notificationKey2 = new TestNotificationKey(key2.toString());
final DefaultNotificationQueue queue = new DefaultNotificationQueue(dbi, clock, "test-svc", "many",
- new NotificationQueueHandler() {
- @Override
- public void handleReadyNotification(final NotificationKey inputKey, final DateTime eventDateTime) {
- if (inputKey.equals(notificationKey) || inputKey.equals(notificationKey2)) { //ignore stray events from other tests
- log.info("Received notification with key: " + notificationKey);
- eventsReceived++;
- }
- }
- },
- getNotificationConfig(false, 100, 10, 10000));
-
+ new NotificationQueueHandler() {
+ @Override
+ public void handleReadyNotification(final NotificationKey inputKey, final DateTime eventDateTime) {
+ if (inputKey.equals(notificationKey) || inputKey.equals(notificationKey2)) { //ignore stray events from other tests
+ log.info("Received notification with key: " + notificationKey);
+ eventsReceived++;
+ }
+ }
+ },
+ getNotificationConfig(false, 100, 10, 10000));
queue.startQueue();
@@ -441,19 +409,18 @@ public class TestNotificationQueue {
dao.inTransaction(new Transaction<Void, DummySqlTest>() {
@Override
public Void inTransaction(final DummySqlTest transactional,
- final TransactionStatus status) throws Exception {
+ final TransactionStatus status) throws Exception {
queue.recordFutureNotificationFromTransaction(transactional,
- start.plus(nextReadyTimeIncrementMs), notificationKey);
+ start.plus(nextReadyTimeIncrementMs), accountId, notificationKey);
queue.recordFutureNotificationFromTransaction(transactional,
- start.plus(2 * nextReadyTimeIncrementMs), notificationKey);
+ start.plus(2 * nextReadyTimeIncrementMs), accountId, notificationKey);
queue.recordFutureNotificationFromTransaction(transactional,
- start.plus(3 * nextReadyTimeIncrementMs), notificationKey2);
+ start.plus(3 * nextReadyTimeIncrementMs), accountId, notificationKey2);
return null;
}
});
-
queue.removeNotificationsByKey(notificationKey); // should remove 2 of the 3
// Move time in the future after the notification effectiveDate
@@ -474,26 +441,17 @@ public class TestNotificationQueue {
queue.stopQueue();
}
-
public static class TestNotificationQueueModule extends AbstractModule {
@Override
protected void configure() {
-
bind(Clock.class).to(ClockMock.class);
- final MysqlTestingHelper helper = new MysqlTestingHelper();
+ final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(MysqlTestingHelper.class).toInstance(helper);
final IDBI dbi = helper.getDBI();
bind(IDBI.class).toInstance(dbi);
final IDBI otherDbi = helper.getDBI();
bind(IDBI.class).annotatedWith(Names.named("global-lock")).toInstance(otherDbi);
- /*
- bind(DBI.class).toProvider(DBIProvider.class).asEagerSingleton();
- final DbiConfig config = new ConfigurationObjectFactory(System.getProperties()).build(DbiConfig.class);
- bind(DbiConfig.class).toInstance(config);
- */
}
}
-
-
}
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagCreationEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagCreationEvent.java
index 5ebd270..9651c31 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagCreationEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagCreationEvent.java
@@ -21,13 +21,14 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultControlTagCreationEvent {
+public class TestDefaultControlTagCreationEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionCreationEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionCreationEvent.java
index 05d4c05..7ad5252 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionCreationEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionCreationEvent.java
@@ -21,12 +21,13 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultControlTagDefinitionCreationEvent {
+public class TestDefaultControlTagDefinitionCreationEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagDefinitionId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionDeletionEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionDeletionEvent.java
index 08059d1..2ea3181 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionDeletionEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDefinitionDeletionEvent.java
@@ -21,12 +21,13 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultControlTagDefinitionDeletionEvent {
+public class TestDefaultControlTagDefinitionDeletionEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagDefinitionId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDeletionEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDeletionEvent.java
index 692149a..5f68460 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDeletionEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultControlTagDeletionEvent.java
@@ -21,13 +21,14 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultControlTagDeletionEvent {
+public class TestDefaultControlTagDeletionEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagCreationEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagCreationEvent.java
index 4d8162a..e330375 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagCreationEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagCreationEvent.java
@@ -21,13 +21,14 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultUserTagCreationEvent {
+public class TestDefaultUserTagCreationEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionCreationEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionCreationEvent.java
index 89507d3..ae7ddfa 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionCreationEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionCreationEvent.java
@@ -21,12 +21,13 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultUserTagDefinitionCreationEvent {
+public class TestDefaultUserTagDefinitionCreationEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagDefinitionId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionDeletionEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionDeletionEvent.java
index bdcfaff..9bc13a2 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionDeletionEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDefinitionDeletionEvent.java
@@ -21,12 +21,13 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultUserTagDefinitionDeletionEvent {
+public class TestDefaultUserTagDefinitionDeletionEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagDefinitionId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDeletionEvent.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDeletionEvent.java
index ff022ef..2b8bd68 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDeletionEvent.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestDefaultUserTagDeletionEvent.java
@@ -21,13 +21,14 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.jackson.ObjectMapper;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
-public class TestDefaultUserTagDeletionEvent {
+public class TestDefaultUserTagDeletionEvent extends UtilTestSuite {
@Test(groups = "fast")
public void testPojo() throws Exception {
final UUID tagId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/api/user/TestTagEventBuilder.java b/util/src/test/java/com/ning/billing/util/tag/api/user/TestTagEventBuilder.java
index 724ad14..f9f7411 100644
--- a/util/src/test/java/com/ning/billing/util/tag/api/user/TestTagEventBuilder.java
+++ b/util/src/test/java/com/ning/billing/util/tag/api/user/TestTagEventBuilder.java
@@ -21,6 +21,7 @@ import java.util.UUID;
import org.testng.Assert;
import org.testng.annotations.Test;
+import com.ning.billing.util.UtilTestSuite;
import com.ning.billing.util.dao.ObjectType;
import com.ning.billing.util.tag.DefaultTagDefinition;
import com.ning.billing.util.tag.TagDefinition;
@@ -35,7 +36,7 @@ import com.ning.billing.util.tag.api.UserTagDefinitionCreationEvent;
import com.ning.billing.util.tag.api.UserTagDefinitionDeletionEvent;
import com.ning.billing.util.tag.api.UserTagDeletionEvent;
-public class TestTagEventBuilder {
+public class TestTagEventBuilder extends UtilTestSuite {
@Test(groups = "fast")
public void testNewUserTagDefinitionCreationEvent() throws Exception {
final UUID tagDefinitionId = UUID.randomUUID();
diff --git a/util/src/test/java/com/ning/billing/util/tag/dao/TestAuditedTagDao.java b/util/src/test/java/com/ning/billing/util/tag/dao/TestAuditedTagDao.java
index 2bb6a37..35c3117 100644
--- a/util/src/test/java/com/ning/billing/util/tag/dao/TestAuditedTagDao.java
+++ b/util/src/test/java/com/ning/billing/util/tag/dao/TestAuditedTagDao.java
@@ -32,6 +32,7 @@ import org.testng.annotations.Test;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.callcontext.CallContext;
@@ -48,7 +49,7 @@ import com.ning.billing.util.tag.TestTagStore;
import com.ning.billing.util.tag.api.TagEvent;
@Guice(modules = MockTagStoreModuleSql.class)
-public class TestAuditedTagDao {
+public class TestAuditedTagDao extends UtilTestSuiteWithEmbeddedDB {
@Inject
private MysqlTestingHelper helper;
@@ -69,25 +70,19 @@ public class TestAuditedTagDao {
@BeforeClass(groups = "slow")
public void setup() throws IOException {
- final String utilDdl = IOUtils.toString(TestTagStore.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
-
context = new DefaultCallContextFactory(clock).createCallContext("Tag DAO test", CallOrigin.TEST, UserType.TEST, UUID.randomUUID());
bus.start();
}
@BeforeMethod(groups = "slow")
- public void cleanup() throws Bus.EventBusException {
+ public void cleanupBeforeMethod() throws Bus.EventBusException {
eventsListener = new EventsListener();
bus.register(eventsListener);
}
@AfterClass(groups = "slow")
- public void stopMysql() {
+ public void tearDown() {
bus.stop();
- helper.stopMysql();
}
@Test(groups = "slow")
@@ -95,7 +90,7 @@ public class TestAuditedTagDao {
final String definitionName = UUID.randomUUID().toString().substring(0, 5);
final String description = UUID.randomUUID().toString().substring(0, 5);
final UUID objectId = UUID.randomUUID();
- final ObjectType objectType = ObjectType.RECURRING_INVOICE_ITEM;
+ final ObjectType objectType = ObjectType.INVOICE_ITEM;
// Verify the initial state
Assert.assertEquals(eventsListener.getEvents().size(), 0);
diff --git a/util/src/test/java/com/ning/billing/util/tag/dao/TestDefaultTagDefinitionDao.java b/util/src/test/java/com/ning/billing/util/tag/dao/TestDefaultTagDefinitionDao.java
index c895b67..15d00e1 100644
--- a/util/src/test/java/com/ning/billing/util/tag/dao/TestDefaultTagDefinitionDao.java
+++ b/util/src/test/java/com/ning/billing/util/tag/dao/TestDefaultTagDefinitionDao.java
@@ -31,6 +31,7 @@ import org.testng.annotations.Test;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.bus.Bus;
import com.ning.billing.util.bus.BusEvent;
import com.ning.billing.util.callcontext.CallContext;
@@ -45,7 +46,7 @@ import com.ning.billing.util.tag.TestTagStore;
import com.ning.billing.util.tag.api.TagDefinitionEvent;
@Guice(modules = MockTagStoreModuleSql.class)
-public class TestDefaultTagDefinitionDao {
+public class TestDefaultTagDefinitionDao extends UtilTestSuiteWithEmbeddedDB {
@Inject
private MysqlTestingHelper helper;
@@ -63,25 +64,19 @@ public class TestDefaultTagDefinitionDao {
@BeforeClass(groups = "slow")
public void setup() throws IOException {
- final String utilDdl = IOUtils.toString(TestTagStore.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
-
context = new DefaultCallContextFactory(clock).createCallContext("TagDefinition DAO test", CallOrigin.TEST, UserType.TEST, UUID.randomUUID());
bus.start();
}
@BeforeMethod(groups = "slow")
- public void cleanup() throws Bus.EventBusException {
+ public void cleanupBeforeMethod() throws Bus.EventBusException {
eventsListener = new EventsListener();
bus.register(eventsListener);
}
@AfterClass(groups = "slow")
- public void stopMysql() {
+ public void tearDown() {
bus.stop();
- helper.stopMysql();
}
@Test(groups = "slow")
diff --git a/util/src/test/java/com/ning/billing/util/tag/MockTagStoreModuleSql.java b/util/src/test/java/com/ning/billing/util/tag/MockTagStoreModuleSql.java
index d7a704b..56bb2f7 100644
--- a/util/src/test/java/com/ning/billing/util/tag/MockTagStoreModuleSql.java
+++ b/util/src/test/java/com/ning/billing/util/tag/MockTagStoreModuleSql.java
@@ -21,6 +21,7 @@ import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.tweak.HandleCallback;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.MysqlTestingHelper;
import com.ning.billing.mock.glue.MockClockModule;
import com.ning.billing.util.bus.Bus;
@@ -32,7 +33,7 @@ public class MockTagStoreModuleSql extends TagStoreModule {
@Override
protected void configure() {
- helper = new MysqlTestingHelper();
+ helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
bind(IDBI.class).toInstance(helper.getDBI());
bind(MysqlTestingHelper.class).toInstance(helper);
install(new MockClockModule());
diff --git a/util/src/test/java/com/ning/billing/util/tag/TestTagStore.java b/util/src/test/java/com/ning/billing/util/tag/TestTagStore.java
index a5016a7..0fb9e97 100644
--- a/util/src/test/java/com/ning/billing/util/tag/TestTagStore.java
+++ b/util/src/test/java/com/ning/billing/util/tag/TestTagStore.java
@@ -36,6 +36,7 @@ import org.testng.annotations.Test;
import com.google.inject.Inject;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.api.TagApiException;
import com.ning.billing.util.api.TagDefinitionApiException;
import com.ning.billing.util.bus.Bus;
@@ -57,7 +58,7 @@ import static org.testng.Assert.fail;
@Test(groups = {"slow"})
@Guice(modules = MockTagStoreModuleSql.class)
-public class TestTagStore {
+public class TestTagStore extends UtilTestSuiteWithEmbeddedDB {
@Inject
private MysqlTestingHelper helper;
@@ -83,17 +84,10 @@ public class TestTagStore {
@BeforeClass(groups = "slow")
protected void setup() throws IOException {
- // Health check test to make sure MySQL is setup properly
try {
- final String utilDdl = IOUtils.toString(TestTagStore.class.getResourceAsStream("/com/ning/billing/util/ddl.sql"));
-
- helper.startMysql();
- helper.initDb(utilDdl);
-
context = new DefaultCallContextFactory(clock).createCallContext("Tag store test", CallOrigin.TEST, UserType.TEST);
bus.start();
- cleanupTags();
tagDefinitionDao.create("tag1", "First tag", context);
testTag = tagDefinitionDao.create("testTag", "Second tag", context);
} catch (Throwable t) {
@@ -103,27 +97,8 @@ public class TestTagStore {
}
@AfterClass(groups = "slow")
- public void stopMysql() {
+ public void tearDown() {
bus.stop();
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
- private void cleanupTags() {
- try {
- helper.getDBI().withHandle(new HandleCallback<Void>() {
- @Override
- public Void withHandle(final Handle handle) throws Exception {
- handle.createScript("delete from tag_definitions").execute();
- handle.createScript("delete from tag_definition_history").execute();
- handle.createScript("delete from tags").execute();
- handle.createScript("delete from tag_history").execute();
- return null;
- }
- });
- } catch (Throwable ignore) {
- }
}
@Test(groups = "slow")
diff --git a/util/src/test/java/com/ning/billing/util/template/translation/TestDefaultTranslatorBase.java b/util/src/test/java/com/ning/billing/util/template/translation/TestDefaultTranslatorBase.java
new file mode 100644
index 0000000..00fc0c2
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/util/template/translation/TestDefaultTranslatorBase.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2010-2012 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.util.template.translation;
+
+import java.util.Locale;
+import java.util.UUID;
+
+import org.mockito.Mockito;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.ning.billing.util.UtilTestSuite;
+
+public class TestDefaultTranslatorBase extends UtilTestSuite {
+ private final class TestTranslatorBase extends DefaultTranslatorBase {
+ public TestTranslatorBase(final TranslatorConfig config) {
+ super(config);
+ }
+
+ @Override
+ protected String getBundlePath() {
+ return UUID.randomUUID().toString();
+ }
+
+ @Override
+ protected String getTranslationType() {
+ return UUID.randomUUID().toString();
+ }
+ }
+
+ @Test(groups = "fast")
+ public void testResourceDoesNotExist() throws Exception {
+ final TestTranslatorBase translator = new TestTranslatorBase(Mockito.mock(TranslatorConfig.class));
+ final String originalText = UUID.randomUUID().toString();
+ Assert.assertEquals(translator.getTranslation(Locale.FRANCE, originalText), originalText);
+ }
+}
diff --git a/util/src/test/java/com/ning/billing/util/UtilTestSuite.java b/util/src/test/java/com/ning/billing/util/UtilTestSuite.java
new file mode 100644
index 0000000..3b0658b
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/util/UtilTestSuite.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.util;
+
+import com.ning.billing.KillbillTestSuite;
+
+public abstract class UtilTestSuite extends KillbillTestSuite {
+}
diff --git a/util/src/test/java/com/ning/billing/util/UtilTestSuiteWithEmbeddedDB.java b/util/src/test/java/com/ning/billing/util/UtilTestSuiteWithEmbeddedDB.java
new file mode 100644
index 0000000..e0b2c3d
--- /dev/null
+++ b/util/src/test/java/com/ning/billing/util/UtilTestSuiteWithEmbeddedDB.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2010-2012 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.util;
+
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
+
+public abstract class UtilTestSuiteWithEmbeddedDB extends KillbillTestSuiteWithEmbeddedDB {
+}
diff --git a/util/src/test/java/com/ning/billing/util/validation/TestValidationManager.java b/util/src/test/java/com/ning/billing/util/validation/TestValidationManager.java
index 204abdb..9406f4d 100644
--- a/util/src/test/java/com/ning/billing/util/validation/TestValidationManager.java
+++ b/util/src/test/java/com/ning/billing/util/validation/TestValidationManager.java
@@ -25,7 +25,10 @@ import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import com.ning.billing.KillbillTestSuiteWithEmbeddedDB;
import com.ning.billing.dbi.MysqlTestingHelper;
+import com.ning.billing.util.UtilTestSuite;
+import com.ning.billing.util.UtilTestSuiteWithEmbeddedDB;
import com.ning.billing.util.globallocker.TestMysqlGlobalLocker;
import com.ning.billing.util.io.IOUtils;
import com.ning.billing.util.validation.dao.DatabaseSchemaDao;
@@ -36,8 +39,8 @@ import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
-public class TestValidationManager {
- private final MysqlTestingHelper helper = new MysqlTestingHelper();
+public class TestValidationManager extends UtilTestSuiteWithEmbeddedDB {
+ private final MysqlTestingHelper helper = KillbillTestSuiteWithEmbeddedDB.getMysqlTestingHelper();
private static final String TABLE_NAME = "validation_test";
private ValidationManager vm;
@@ -57,21 +60,9 @@ public class TestValidationManager {
private void setupDatabase() throws IOException {
final String testDdl = IOUtils.toString(TestMysqlGlobalLocker.class.getResourceAsStream("/com/ning/billing/util/ddl_test.sql"));
- helper.startMysql();
helper.initDb(testDdl);
}
- @AfterClass(groups = "slow")
- public void tearDown() {
- stopDatabase();
- }
-
- private void stopDatabase() {
- if (helper != null) {
- helper.stopMysql();
- }
- }
-
@Test(groups = "slow")
public void testRetrievingColumnInfo() {
final Collection<ColumnInfo> columnInfoList = vm.getTableInfo(TABLE_NAME);
diff --git a/util/src/test/resources/com/ning/billing/util/email/templates/HtmlInvoiceTemplate.mustache b/util/src/test/resources/com/ning/billing/util/email/templates/HtmlInvoiceTemplate.mustache
index aef1dce..be1668b 100644
--- a/util/src/test/resources/com/ning/billing/util/email/templates/HtmlInvoiceTemplate.mustache
+++ b/util/src/test/resources/com/ning/billing/util/email/templates/HtmlInvoiceTemplate.mustache
@@ -78,12 +78,12 @@
<tr>
<td colspan=2 />
<td align=right><strong>{{text.invoiceAmount}}</strong></td>
- <td align=right><strong>{{invoice.amountCharged}}</strong></td>
+ <td align=right><strong>{{invoice.chargedAmount}}</strong></td>
</tr>
<tr>
<td colspan=2 />
<td align=right><strong>{{text.invoiceAmountPaid}}</strong></td>
- <td align=right><strong>{{invoice.amountPaid}}</strong></td>
+ <td align=right><strong>{{invoice.paidAmount}}</strong></td>
</tr>
<tr>
<td colspan=2 />
diff --git a/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_en_US.properties b/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_en_US.properties
new file mode 100644
index 0000000..0bde4ee
--- /dev/null
+++ b/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_en_US.properties
@@ -0,0 +1,2 @@
+shotgun-monthly = Monthly shotgun plan
+shotgun-annual = Annual shotgun plan
\ No newline at end of file
diff --git a/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_fr_CA.properties b/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_fr_CA.properties
new file mode 100644
index 0000000..2415908
--- /dev/null
+++ b/util/src/test/resources/com/ning/billing/util/template/translation/CatalogTranslation_fr_CA.properties
@@ -0,0 +1,2 @@
+shotgun-monthly = Fusil de chasse mensuel
+shotgun-annual = Fusil de chasse annuel
\ No newline at end of file