Search in sources :

Example 26 with InternalTenantContext

use of org.killbill.billing.callcontext.InternalTenantContext in project killbill by killbill.

the class IncompletePaymentTransactionTask method tryToProcessNotification.

public void tryToProcessNotification(final JanitorNotificationKey notificationKey, final UUID userToken, final Long accountRecordId, final long tenantRecordId) throws LockFailedException {
    final InternalTenantContext internalTenantContext = internalCallContextFactory.createInternalTenantContext(tenantRecordId, accountRecordId);
    tryToDoJanitorOperationWithAccountLock(new JanitorIterationCallback() {

        @Override
        public Void doIteration() {
            // State may have changed since we originally retrieved with no lock
            final PaymentTransactionModelDao rehydratedPaymentTransaction = paymentDao.getPaymentTransaction(notificationKey.getUuidKey(), internalTenantContext);
            final TenantContext tenantContext = internalCallContextFactory.createTenantContext(internalTenantContext);
            final PaymentModelDao payment = paymentDao.getPayment(rehydratedPaymentTransaction.getPaymentId(), internalTenantContext);
            final PaymentTransactionInfoPlugin undefinedPaymentTransaction = new DefaultNoOpPaymentInfoPlugin(payment.getId(), rehydratedPaymentTransaction.getId(), rehydratedPaymentTransaction.getTransactionType(), rehydratedPaymentTransaction.getAmount(), rehydratedPaymentTransaction.getCurrency(), rehydratedPaymentTransaction.getCreatedDate(), rehydratedPaymentTransaction.getCreatedDate(), PaymentPluginStatus.UNDEFINED, null, null);
            PaymentTransactionInfoPlugin paymentTransactionInfoPlugin;
            try {
                final PaymentPluginApi paymentPluginApi = paymentPluginServiceRegistration.getPaymentPluginApi(payment.getPaymentMethodId(), false, internalTenantContext);
                final List<PaymentTransactionInfoPlugin> result = paymentPluginApi.getPaymentInfo(payment.getAccountId(), payment.getId(), ImmutableList.<PluginProperty>of(), tenantContext);
                paymentTransactionInfoPlugin = Iterables.tryFind(result, new Predicate<PaymentTransactionInfoPlugin>() {

                    @Override
                    public boolean apply(final PaymentTransactionInfoPlugin input) {
                        return input.getKbTransactionPaymentId().equals(rehydratedPaymentTransaction.getId());
                    }
                }).or(new Supplier<PaymentTransactionInfoPlugin>() {

                    @Override
                    public PaymentTransactionInfoPlugin get() {
                        return undefinedPaymentTransaction;
                    }
                });
            } catch (final Exception e) {
                paymentTransactionInfoPlugin = undefinedPaymentTransaction;
            }
            updatePaymentAndTransactionIfNeeded(payment, notificationKey.getAttemptNumber(), userToken, rehydratedPaymentTransaction, paymentTransactionInfoPlugin, internalTenantContext);
            return null;
        }
    }, internalTenantContext);
}
Also used : DefaultNoOpPaymentInfoPlugin(org.killbill.billing.payment.provider.DefaultNoOpPaymentInfoPlugin) PaymentModelDao(org.killbill.billing.payment.dao.PaymentModelDao) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) TenantContext(org.killbill.billing.util.callcontext.TenantContext) LockFailedException(org.killbill.commons.locker.LockFailedException) IOException(java.io.IOException) Predicate(com.google.common.base.Predicate) PaymentPluginApi(org.killbill.billing.payment.plugin.api.PaymentPluginApi) PluginProperty(org.killbill.billing.payment.api.PluginProperty) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) PaymentTransactionInfoPlugin(org.killbill.billing.payment.plugin.api.PaymentTransactionInfoPlugin) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List)

Example 27 with InternalTenantContext

use of org.killbill.billing.callcontext.InternalTenantContext in project killbill by killbill.

the class IncompletePaymentTransactionTask method insertNewNotificationForUnresolvedTransactionIfNeeded.

private void insertNewNotificationForUnresolvedTransactionIfNeeded(final UUID paymentTransactionId, @Nullable final Integer attemptNumber, @Nullable final UUID userToken, final Long accountRecordId, final Long tenantRecordId) {
    // When we come from a GET path, we don't want to insert a new notification
    if (attemptNumber == null) {
        return;
    }
    final InternalTenantContext tenantContext = internalCallContextFactory.createInternalTenantContext(tenantRecordId, accountRecordId);
    // Increment value before we insert
    final Integer newAttemptNumber = attemptNumber.intValue() + 1;
    final NotificationEvent key = new JanitorNotificationKey(paymentTransactionId, IncompletePaymentTransactionTask.class.toString(), newAttemptNumber);
    final DateTime notificationTime = getNextNotificationTime(newAttemptNumber, tenantContext);
    // Will be null in the GET path or when we run out opf attempts..
    if (notificationTime != null) {
        try {
            janitorQueue.recordFutureNotification(notificationTime, key, userToken, accountRecordId, tenantRecordId);
        } catch (IOException e) {
            log.warn("Janitor IncompletePaymentTransactionTask : Failed to insert future notification for paymentTransactionId = {}: {}", paymentTransactionId, e.getMessage());
        }
    }
}
Also used : InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) NotificationEvent(org.killbill.notificationq.api.NotificationEvent) IOException(java.io.IOException) DateTime(org.joda.time.DateTime)

Example 28 with InternalTenantContext

use of org.killbill.billing.callcontext.InternalTenantContext in project killbill by killbill.

the class PaymentProcessor method toPayment.

private Payment toPayment(final PaymentModelDao paymentModelDao, @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions, final boolean withAttempts, final InternalTenantContext tenantContext) {
    final InternalTenantContext tenantContextWithAccountRecordId = getInternalTenantContextWithAccountRecordId(paymentModelDao.getAccountId(), tenantContext);
    final List<PaymentTransactionModelDao> transactionsForPayment = paymentDao.getTransactionsForPayment(paymentModelDao.getId(), tenantContextWithAccountRecordId);
    return toPayment(paymentModelDao, transactionsForPayment, pluginTransactions, withAttempts, tenantContextWithAccountRecordId);
}
Also used : PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext)

Example 29 with InternalTenantContext

use of org.killbill.billing.callcontext.InternalTenantContext in project killbill by killbill.

the class TestEhCacheOverdueConfigCache method testExistingTenantOverdue.

//
// Verify OverdueConfigCache returns per tenant overdue config:
// 1. We first mock TenantInternalApi to return a different overdue config than the default one
// 2. We then mock TenantInternalApi to throw RuntimeException which means overdue config was cached and there was no additional call
//    to the TenantInternalApi api (otherwise test would fail with RuntimeException)
//
@Test(groups = "fast")
public void testExistingTenantOverdue() throws OverdueApiException, URISyntaxException, IOException {
    final InternalCallContext differentMultiTenantContext = Mockito.mock(InternalCallContext.class);
    Mockito.when(differentMultiTenantContext.getTenantRecordId()).thenReturn(55667788L);
    final AtomicBoolean shouldThrow = new AtomicBoolean(false);
    final Long multiTenantRecordId = multiTenantContext.getTenantRecordId();
    final Long otherMultiTenantRecordId = otherMultiTenantContext.getTenantRecordId();
    final InputStream tenantInputOverdueConfig = UriAccessor.accessUri(new URI(Resources.getResource("OverdueConfig2.xml").toExternalForm()));
    final String tenantOverdueConfigXML = CharStreams.toString(new InputStreamReader(tenantInputOverdueConfig, "UTF-8"));
    final InputStream otherTenantInputOverdueConfig = UriAccessor.accessUri(new URI(Resources.getResource("OverdueConfig.xml").toExternalForm()));
    final String otherTenantOverdueConfigXML = CharStreams.toString(new InputStreamReader(otherTenantInputOverdueConfig, "UTF-8"));
    Mockito.when(tenantInternalApi.getTenantOverdueConfig(Mockito.any(InternalTenantContext.class))).thenAnswer(new Answer<String>() {

        @Override
        public String answer(final InvocationOnMock invocation) throws Throwable {
            if (shouldThrow.get()) {
                throw new RuntimeException();
            }
            final InternalTenantContext internalContext = (InternalTenantContext) invocation.getArguments()[0];
            if (multiTenantRecordId.equals(internalContext.getTenantRecordId())) {
                return tenantOverdueConfigXML;
            } else if (otherMultiTenantRecordId.equals(internalContext.getTenantRecordId())) {
                return otherTenantOverdueConfigXML;
            } else {
                return null;
            }
        }
    });
    // Verify the lookup for a non-cached tenant. No system config is set yet but EhCacheOverdueConfigCache returns a default no-op one
    OverdueConfig differentResult = overdueConfigCache.getOverdueConfig(differentMultiTenantContext);
    Assert.assertNotNull(differentResult);
    Assert.assertEquals(differentResult.getOverdueStatesAccount().getStates().length, 1);
    Assert.assertTrue(differentResult.getOverdueStatesAccount().getStates()[0].isClearState());
    // Make sure the cache loader isn't invoked, see https://github.com/killbill/killbill/issues/298
    shouldThrow.set(true);
    differentResult = overdueConfigCache.getOverdueConfig(differentMultiTenantContext);
    Assert.assertNotNull(differentResult);
    Assert.assertEquals(differentResult.getOverdueStatesAccount().getStates().length, 1);
    Assert.assertTrue(differentResult.getOverdueStatesAccount().getStates()[0].isClearState());
    shouldThrow.set(false);
    // Set a default config
    overdueConfigCache.loadDefaultOverdueConfig(Resources.getResource("OverdueConfig.xml").toExternalForm());
    // Verify the lookup for this tenant
    final OverdueConfig result = overdueConfigCache.getOverdueConfig(multiTenantContext);
    Assert.assertNotNull(result);
    Assert.assertEquals(result.getOverdueStatesAccount().getStates().length, 1);
    Assert.assertFalse(result.getOverdueStatesAccount().getStates()[0].isClearState());
    // Verify the lookup for another tenant
    final OverdueConfig otherResult = overdueConfigCache.getOverdueConfig(otherMultiTenantContext);
    Assert.assertNotNull(otherResult);
    Assert.assertEquals(otherResult.getOverdueStatesAccount().getStates().length, 1);
    Assert.assertTrue(otherResult.getOverdueStatesAccount().getStates()[0].isClearState());
    shouldThrow.set(true);
    // Verify the lookup for this tenant
    final OverdueConfig result2 = overdueConfigCache.getOverdueConfig(multiTenantContext);
    Assert.assertEquals(result2, result);
    // Verify the lookup with another context for the same tenant
    final InternalCallContext sameMultiTenantContext = Mockito.mock(InternalCallContext.class);
    Mockito.when(sameMultiTenantContext.getAccountRecordId()).thenReturn(9102L);
    Mockito.when(sameMultiTenantContext.getTenantRecordId()).thenReturn(multiTenantRecordId);
    Assert.assertEquals(overdueConfigCache.getOverdueConfig(sameMultiTenantContext), result);
    // Verify the lookup with the other tenant
    Assert.assertEquals(overdueConfigCache.getOverdueConfig(otherMultiTenantContext), otherResult);
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OverdueConfig(org.killbill.billing.overdue.api.OverdueConfig) Test(org.testng.annotations.Test)

Example 30 with InternalTenantContext

use of org.killbill.billing.callcontext.InternalTenantContext in project killbill by killbill.

the class TestBillingStateCalculator method createBSCalc.

public BillingStateCalculator createBSCalc() {
    now = new LocalDate();
    final Collection<Invoice> invoices = new ArrayList<Invoice>();
    invoices.add(createInvoice(now, BigDecimal.ZERO, null));
    invoices.add(createInvoice(now.plusDays(1), BigDecimal.TEN, null));
    invoices.add(createInvoice(now.plusDays(2), new BigDecimal("100.0"), null));
    Mockito.when(invoiceApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<LocalDate>any(), Mockito.<InternalTenantContext>any())).thenReturn(invoices);
    return new BillingStateCalculator(invoiceApi, clock, tagInternalApi) {

        @Override
        public BillingState calculateBillingState(final ImmutableAccountData overdueable, final InternalTenantContext context) {
            return null;
        }
    };
}
Also used : ImmutableAccountData(org.killbill.billing.account.api.ImmutableAccountData) Invoice(org.killbill.billing.invoice.api.Invoice) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) ArrayList(java.util.ArrayList) LocalDate(org.joda.time.LocalDate) BigDecimal(java.math.BigDecimal)

Aggregations

InternalTenantContext (org.killbill.billing.callcontext.InternalTenantContext)56 UUID (java.util.UUID)9 ArrayList (java.util.ArrayList)8 CatalogApiException (org.killbill.billing.catalog.api.CatalogApiException)8 InternalCallContext (org.killbill.billing.callcontext.InternalCallContext)7 CacheLoaderArgument (org.killbill.billing.util.cache.CacheLoaderArgument)7 ImmutableList (com.google.common.collect.ImmutableList)6 List (java.util.List)6 LocalDate (org.joda.time.LocalDate)6 Predicate (com.google.common.base.Predicate)5 IOException (java.io.IOException)5 ObjectType (org.killbill.billing.ObjectType)5 InvoiceApiException (org.killbill.billing.invoice.api.InvoiceApiException)5 SubscriptionBaseApiException (org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)5 InputStream (java.io.InputStream)4 URI (java.net.URI)4 DateTime (org.joda.time.DateTime)4 Account (org.killbill.billing.account.api.Account)4 PlanPhasePriceOverride (org.killbill.billing.catalog.api.PlanPhasePriceOverride)4 Invoice (org.killbill.billing.invoice.api.Invoice)4