Search in sources :

Example 36 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class InvoiceChecker method checkInvoiceNoAudits.

public void checkInvoiceNoAudits(final Invoice invoice, final CallContext context, final List<ExpectedInvoiceItemCheck> expected) throws InvoiceApiException {
    final List<InvoiceItem> actual = invoice.getInvoiceItems();
    Assert.assertEquals(actual.size(), expected.size(), String.format("Expected items: %s, actual items: %s", expected, actual));
    for (final ExpectedInvoiceItemCheck cur : expected) {
        boolean found = false;
        // First try to find exact match; this is necessary because the for loop below might encounter a similar item -- for instance
        // same type, same dates, but different amount and choke.
        final InvoiceItem foundItem = Iterables.tryFind(actual, new Predicate<InvoiceItem>() {

            @Override
            public boolean apply(final InvoiceItem input) {
                if (input.getInvoiceItemType() != cur.getType() || (cur.shouldCheckDates() && input.getStartDate().compareTo(cur.getStartDate()) != 0)) {
                    return false;
                }
                if (input.getAmount().compareTo(cur.getAmount()) != 0) {
                    return false;
                }
                if (!cur.shouldCheckDates() || (cur.getEndDate() == null && input.getEndDate() == null) || (cur.getEndDate() != null && input.getEndDate() != null && cur.getEndDate().compareTo(input.getEndDate()) == 0)) {
                    return true;
                }
                return false;
            }
        }).orNull();
        if (foundItem != null) {
            continue;
        }
        // If we could not find it, we still loop again, so that error message helps to debug when there is a 'similar' item.
        for (final InvoiceItem in : actual) {
            // Match first on type and start date
            if (in.getInvoiceItemType() != cur.getType() || (cur.shouldCheckDates() && in.getStartDate().compareTo(cur.getStartDate()) != 0)) {
                continue;
            }
            if (in.getAmount().compareTo(cur.getAmount()) != 0) {
                log.info(String.format("Found item type = %s and startDate = %s but amount differ (actual = %s, expected = %s) ", cur.getType(), cur.getStartDate(), in.getAmount(), cur.getAmount()));
                continue;
            }
            if (!cur.shouldCheckDates() || (cur.getEndDate() == null && in.getEndDate() == null) || (cur.getEndDate() != null && in.getEndDate() != null && cur.getEndDate().compareTo(in.getEndDate()) == 0)) {
                found = true;
                break;
            }
            log.info(String.format("Found item type = %s and startDate = %s, amount = %s but endDate differ (actual = %s, expected = %s) ", cur.getType(), cur.getStartDate(), in.getAmount(), in.getEndDate(), cur.getEndDate()));
        }
        if (!found) {
            final StringBuilder debugBuilder = new StringBuilder();
            debugBuilder.append(String.format("Invoice id=[%s], targetDate=[%s]", invoice.getId(), invoice.getTargetDate()));
            for (final InvoiceItem actualInvoiceItem : actual) {
                debugBuilder.append(String.format("\n    type=[%s] startDate=[%s] endDate=[%s] amount=[%s]", actualInvoiceItem.getInvoiceItemType(), actualInvoiceItem.getStartDate(), actualInvoiceItem.getEndDate(), actualInvoiceItem.getAmount()));
            }
            final String failureMessage = String.format("Failed to find invoice item type = %s and startDate = %s, amount = %s, endDate = %s for invoice id %s\n%s", cur.getType(), cur.getStartDate(), cur.getAmount(), cur.getEndDate(), invoice.getId(), debugBuilder.toString());
            Assert.fail(failureMessage);
        }
    }
}
Also used : InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) Predicate(com.google.common.base.Predicate)

Example 37 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestInvoicePayment method testCancellationEOTWithInvoiceItemAdjustmentsOnInvoiceWithMultipleItems.

@Test(groups = "slow")
public void testCancellationEOTWithInvoiceItemAdjustmentsOnInvoiceWithMultipleItems() throws Exception {
    final int billingDay = 1;
    final DateTime initialCreationDate = new DateTime(2016, 9, 1, 0, 3, 42, 0, testTimeZone);
    // set clock to the initial start date
    clock.setTime(initialCreationDate);
    final Account account = createAccountWithNonOsgiPaymentMethod(getAccountData(billingDay));
    final DefaultEntitlement bpEntitlement1 = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey1", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
    assertNotNull(bpEntitlement1);
    final DefaultEntitlement bpEntitlement2 = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey2", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
    assertNotNull(bpEntitlement2);
    paymentPlugin.makeNextPaymentFailWithError();
    busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.PHASE, NextEvent.NULL_INVOICE, NextEvent.INVOICE, NextEvent.INVOICE_PAYMENT_ERROR, NextEvent.PAYMENT_ERROR);
    clock.addDays(30);
    assertListenerStatus();
    invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2016, 10, 1), new LocalDate(2016, 11, 1), InvoiceItemType.RECURRING, new BigDecimal("249.95")), new ExpectedInvoiceItemCheck(new LocalDate(2016, 10, 1), new LocalDate(2016, 11, 1), InvoiceItemType.RECURRING, new BigDecimal("249.95")));
    clock.addDays(1);
    assertListenerStatus();
    busHandler.pushExpectedEvents(NextEvent.BLOCK);
    bpEntitlement1.cancelEntitlementWithPolicyOverrideBillingPolicy(EntitlementActionPolicy.IMMEDIATE, BillingActionPolicy.END_OF_TERM, ImmutableList.<PluginProperty>of(), callContext);
    assertListenerStatus();
    List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, callContext);
    final Invoice thirdInvoice = invoices.get(2);
    final InvoiceItem itemForBPEntitlement1 = Iterables.tryFind(thirdInvoice.getInvoiceItems(), new Predicate<InvoiceItem>() {

        @Override
        public boolean apply(final InvoiceItem input) {
            return input.getInvoiceItemType() == InvoiceItemType.RECURRING && input.getSubscriptionId().equals(bpEntitlement1.getId());
        }
    }).orNull();
    Assert.assertNotNull(itemForBPEntitlement1);
    busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT);
    invoiceUserApi.insertInvoiceItemAdjustment(account.getId(), thirdInvoice.getId(), itemForBPEntitlement1.getId(), new LocalDate(2016, 10, 2), UUID.randomUUID().toString(), callContext);
    assertListenerStatus();
    // Expect also payment for previous invoice
    busHandler.pushExpectedEvents(NextEvent.CANCEL, NextEvent.NULL_INVOICE, NextEvent.INVOICE, NextEvent.INVOICE_PAYMENT, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT, NextEvent.PAYMENT);
    clock.addMonths(1);
    assertListenerStatus();
    invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, callContext);
    final Invoice fourthInvoice = invoices.get(3);
    Assert.assertEquals(fourthInvoice.getInvoiceItems().size(), 1);
    invoiceChecker.checkInvoice(account.getId(), 4, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2016, 11, 1), new LocalDate(2016, 12, 1), InvoiceItemType.RECURRING, new BigDecimal("249.95")));
}
Also used : Account(org.killbill.billing.account.api.Account) Invoice(org.killbill.billing.invoice.api.Invoice) InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) ExternalChargeInvoiceItem(org.killbill.billing.invoice.model.ExternalChargeInvoiceItem) DefaultEntitlement(org.killbill.billing.entitlement.api.DefaultEntitlement) ExpectedInvoiceItemCheck(org.killbill.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck) LocalDate(org.joda.time.LocalDate) DateTime(org.joda.time.DateTime) BigDecimal(java.math.BigDecimal) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 38 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestRetryablePayment method testRetryLogicFromRetriedStateWithSuccess.

@Test(groups = "fast")
public void testRetryLogicFromRetriedStateWithSuccess() throws PaymentApiException {
    mockRetryProviderPlugin.setAborted(false).setNextRetryDate(null);
    mockRetryAuthorizeOperationCallback.setResult(OperationResult.SUCCESS).setException(null);
    runner.setOperationCallback(mockRetryAuthorizeOperationCallback).setContext(paymentStateContext);
    final State state = retrySMHelper.getRetriedState();
    final UUID transactionId = UUID.randomUUID();
    final UUID paymentId = UUID.randomUUID();
    final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), paymentMethodId, utcNow, utcNow, paymentExternalKey, transactionId, paymentTransactionExternalKey, TransactionType.AUTHORIZE, state.getName(), amount, currency, null, EMPTY_PROPERTIES);
    paymentDao.insertPaymentAttemptWithProperties(attempt, internalCallContext);
    paymentDao.insertPaymentWithFirstTransaction(new PaymentModelDao(paymentId, utcNow, utcNow, account.getId(), paymentMethodId, -1, paymentExternalKey), new PaymentTransactionModelDao(transactionId, attempt.getId(), paymentTransactionExternalKey, utcNow, utcNow, paymentId, TransactionType.AUTHORIZE, utcNow, TransactionStatus.PAYMENT_FAILURE, amount, currency, "bla", "foo"), internalCallContext);
    processor.retryPaymentTransaction(attempt.getId(), ImmutableList.<String>of(MockPaymentControlProviderPlugin.PLUGIN_NAME), internalCallContext);
    final List<PaymentAttemptModelDao> pas = paymentDao.getPaymentAttemptByTransactionExternalKey(paymentTransactionExternalKey, internalCallContext);
    assertEquals(pas.size(), 2);
    final PaymentAttemptModelDao successfulAttempt = Iterables.tryFind(pas, new Predicate<PaymentAttemptModelDao>() {

        @Override
        public boolean apply(final PaymentAttemptModelDao input) {
            return input.getTransactionType() == TransactionType.AUTHORIZE && input.getStateName().equals("SUCCESS");
        }
    }).orNull();
    assertNotNull(successfulAttempt);
}
Also used : PaymentAttemptModelDao(org.killbill.billing.payment.dao.PaymentAttemptModelDao) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) PaymentModelDao(org.killbill.billing.payment.dao.PaymentModelDao) State(org.killbill.automaton.State) UUID(java.util.UUID) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 39 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestRetryablePayment method testRetryLogicFromRetriedStateWithLockFailure.

@Test(groups = "fast")
public void testRetryLogicFromRetriedStateWithLockFailure() throws LockFailedException {
    GlobalLock lock = null;
    try {
        // Grab lock so that operation later will fail...
        lock = locker.lockWithNumberOfTries(LockerType.ACCNT_INV_PAY.toString(), account.getId().toString(), 1);
        mockRetryProviderPlugin.setAborted(false).setNextRetryDate(null);
        mockRetryAuthorizeOperationCallback.setResult(OperationResult.SUCCESS).setException(null);
        runner.setOperationCallback(mockRetryAuthorizeOperationCallback).setContext(paymentStateContext);
        final State state = retrySMHelper.getRetriedState();
        final UUID transactionId = UUID.randomUUID();
        final UUID paymentId = UUID.randomUUID();
        final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), paymentMethodId, utcNow, utcNow, paymentExternalKey, transactionId, paymentTransactionExternalKey, TransactionType.AUTHORIZE, state.getName(), amount, currency, null, EMPTY_PROPERTIES);
        paymentDao.insertPaymentAttemptWithProperties(attempt, internalCallContext);
        paymentDao.insertPaymentWithFirstTransaction(new PaymentModelDao(paymentId, utcNow, utcNow, account.getId(), paymentMethodId, -1, paymentExternalKey), new PaymentTransactionModelDao(transactionId, attempt.getId(), paymentTransactionExternalKey, utcNow, utcNow, paymentId, TransactionType.AUTHORIZE, utcNow, TransactionStatus.PAYMENT_FAILURE, amount, currency, "bla", "foo"), internalCallContext);
        processor.retryPaymentTransaction(attempt.getId(), ImmutableList.<String>of(MockPaymentControlProviderPlugin.PLUGIN_NAME), internalCallContext);
        final List<PaymentAttemptModelDao> pas = paymentDao.getPaymentAttemptByTransactionExternalKey(paymentTransactionExternalKey, internalCallContext);
        assertEquals(pas.size(), 2);
        final PaymentAttemptModelDao failedAttempt = Iterables.tryFind(pas, new Predicate<PaymentAttemptModelDao>() {

            @Override
            public boolean apply(final PaymentAttemptModelDao input) {
                return input.getTransactionType() == TransactionType.AUTHORIZE && input.getStateName().equals("ABORTED");
            }
        }).orNull();
        assertNotNull(failedAttempt);
    } finally {
        if (lock != null) {
            lock.release();
        }
    }
}
Also used : GlobalLock(org.killbill.commons.locker.GlobalLock) PaymentAttemptModelDao(org.killbill.billing.payment.dao.PaymentAttemptModelDao) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) PaymentModelDao(org.killbill.billing.payment.dao.PaymentModelDao) State(org.killbill.automaton.State) UUID(java.util.UUID) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 40 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestPaymentDao method checkProperty.

private void checkProperty(final Iterable<PluginProperty> properties, final PluginProperty expected) {
    final PluginProperty found = Iterables.tryFind(properties, new Predicate<PluginProperty>() {

        @Override
        public boolean apply(final PluginProperty input) {
            return input.getKey().equals(expected.getKey());
        }
    }).orNull();
    assertNotNull(found, "Did not find property key = " + expected.getKey());
    assertEquals(found.getValue(), expected.getValue());
}
Also used : PluginProperty(org.killbill.billing.payment.api.PluginProperty) Predicate(com.google.common.base.Predicate)

Aggregations

Predicate (com.google.common.base.Predicate)217 List (java.util.List)37 Test (org.junit.Test)37 ArrayList (java.util.ArrayList)34 Nullable (javax.annotation.Nullable)33 Map (java.util.Map)24 UUID (java.util.UUID)21 IOException (java.io.IOException)20 File (java.io.File)18 HashMap (java.util.HashMap)15 Set (java.util.Set)14 Test (org.testng.annotations.Test)14 ImmutableList (com.google.common.collect.ImmutableList)13 Collection (java.util.Collection)11 DateTime (org.joda.time.DateTime)9 BigDecimal (java.math.BigDecimal)8 Path (javax.ws.rs.Path)8 Expression (com.sri.ai.expresso.api.Expression)7 Util (com.sri.ai.util.Util)7 XtextResource (org.eclipse.xtext.resource.XtextResource)7