Search in sources :

Example 11 with InternalTenantContext

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

the class EventsStreamBuilder method buildForBaseSubscription.

public EventsStream buildForBaseSubscription(final UUID bundleId, final TenantContext tenantContext) throws EntitlementApiException {
    final SubscriptionBase baseSubscription;
    try {
        final InternalTenantContext internalTenantContext = internalCallContextFactory.createInternalTenantContext(bundleId, ObjectType.BUNDLE, tenantContext);
        baseSubscription = subscriptionInternalApi.getBaseSubscription(bundleId, internalTenantContext);
    } catch (SubscriptionBaseApiException e) {
        throw new EntitlementApiException(e);
    }
    return buildForEntitlement(baseSubscription.getId(), tenantContext);
}
Also used : SubscriptionBase(org.killbill.billing.subscription.api.SubscriptionBase) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) EntitlementApiException(org.killbill.billing.entitlement.api.EntitlementApiException) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException)

Example 12 with InternalTenantContext

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

the class DefaultInvoiceUserApi method insertCreditForInvoice.

private InvoiceItem insertCreditForInvoice(final UUID accountId, final UUID invoiceId, final BigDecimal amount, final LocalDate effectiveDate, final Currency currency, final boolean autoCommit, final String description, final CallContext context) throws InvoiceApiException {
    if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
        throw new InvoiceApiException(ErrorCode.CREDIT_AMOUNT_INVALID, amount);
    }
    final WithAccountLock withAccountLock = new WithAccountLock() {

        private InvoiceItem creditItem;

        @Override
        public List<Invoice> prepareInvoices() throws InvoiceApiException {
            final InternalTenantContext internalTenantContext = internalCallContextFactory.createInternalTenantContext(accountId, context);
            final LocalDate invoiceDate = internalTenantContext.toLocalDate(context.getCreatedDate());
            // Create an invoice for that credit if it doesn't exist
            final Invoice invoiceForCredit;
            if (invoiceId == null) {
                final InvoiceStatus status = autoCommit ? InvoiceStatus.COMMITTED : InvoiceStatus.DRAFT;
                invoiceForCredit = new DefaultInvoice(accountId, invoiceDate, effectiveDate, currency, status);
            } else {
                invoiceForCredit = getInvoiceAndCheckCurrency(invoiceId, currency, context);
                if (InvoiceStatus.COMMITTED.equals(invoiceForCredit.getStatus())) {
                    throw new InvoiceApiException(ErrorCode.INVOICE_ALREADY_COMMITTED, invoiceId);
                }
            }
            // Create the new credit
            creditItem = new CreditAdjInvoiceItem(UUIDs.randomUUID(), context.getCreatedDate(), invoiceForCredit.getId(), accountId, effectiveDate, description, // Note! The amount is negated here!
            amount.negate(), currency);
            invoiceForCredit.addInvoiceItem(creditItem);
            return ImmutableList.<Invoice>of(invoiceForCredit);
        }
    };
    final Collection<InvoiceItem> creditInvoiceItems = Collections2.<InvoiceItem>filter(invoiceApiHelper.dispatchToInvoicePluginsAndInsertItems(accountId, false, withAccountLock, context), new Predicate<InvoiceItem>() {

        @Override
        public boolean apply(final InvoiceItem invoiceItem) {
            return InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType());
        }
    });
    Preconditions.checkState(creditInvoiceItems.size() == 1, "Should have created a single credit invoice item: " + creditInvoiceItems);
    return creditInvoiceItems.iterator().next();
}
Also used : InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) ExternalChargeInvoiceItem(org.killbill.billing.invoice.model.ExternalChargeInvoiceItem) CreditAdjInvoiceItem(org.killbill.billing.invoice.model.CreditAdjInvoiceItem) Invoice(org.killbill.billing.invoice.api.Invoice) HtmlInvoice(org.killbill.billing.invoice.template.HtmlInvoice) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) CreditAdjInvoiceItem(org.killbill.billing.invoice.model.CreditAdjInvoiceItem) WithAccountLock(org.killbill.billing.invoice.api.WithAccountLock) LocalDate(org.joda.time.LocalDate) InvoiceStatus(org.killbill.billing.invoice.api.InvoiceStatus) DefaultInvoice(org.killbill.billing.invoice.model.DefaultInvoice)

Example 13 with InternalTenantContext

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

the class EhCacheOverdueConfigCache method initializeCacheLoaderArgument.

private CacheLoaderArgument initializeCacheLoaderArgument() {
    final LoaderCallback loaderCallback = new LoaderCallback() {

        @Override
        public Object loadOverdueConfig(final String overdueConfigXML) throws OverdueApiException {
            final InputStream overdueConfigStream = new ByteArrayInputStream(overdueConfigXML.getBytes());
            final URI uri;
            try {
                uri = new URI("/overdueConfig");
                final DefaultOverdueConfig overdueConfig = XMLLoader.getObjectFromStream(uri, overdueConfigStream, DefaultOverdueConfig.class);
                return overdueConfig;
            } catch (final Exception e) {
                throw new OverdueApiException(ErrorCode.OVERDUE_INVALID_FOR_TENANT, "Problem encountered loading overdue config ", e);
            }
        }
    };
    final Object[] args = new Object[1];
    args[0] = loaderCallback;
    final ObjectType irrelevant = null;
    final InternalTenantContext notUsed = null;
    return new CacheLoaderArgument(irrelevant, args, notUsed);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URI(java.net.URI) DefaultOverdueConfig(org.killbill.billing.overdue.config.DefaultOverdueConfig) LoaderCallback(org.killbill.billing.util.cache.TenantOverdueConfigCacheLoader.LoaderCallback) OverdueApiException(org.killbill.billing.overdue.api.OverdueApiException) CacheLoaderArgument(org.killbill.billing.util.cache.CacheLoaderArgument) OverdueApiException(org.killbill.billing.overdue.api.OverdueApiException) ObjectType(org.killbill.billing.ObjectType) ByteArrayInputStream(java.io.ByteArrayInputStream) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext)

Example 14 with InternalTenantContext

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

the class DefaultOverdueApi method getOverdueStateFor.

@Override
public OverdueState getOverdueStateFor(final UUID accountId, final TenantContext tenantContext) throws OverdueApiException {
    final InternalTenantContext internalTenantContext = internalCallContextFactory.createInternalTenantContext(accountId, tenantContext);
    final BlockingState blockingStateForService = blockingInternalApi.getBlockingStateForService(accountId, BlockingStateType.ACCOUNT, OverdueService.OVERDUE_SERVICE_NAME, internalTenantContext);
    final String stateName = blockingStateForService != null ? blockingStateForService.getStateName() : OverdueWrapper.CLEAR_STATE_NAME;
    final OverdueConfig overdueConfig = overdueConfigCache.getOverdueConfig(internalTenantContext);
    final OverdueStateSet states = ((DefaultOverdueConfig) overdueConfig).getOverdueStatesAccount();
    return states.findState(stateName);
}
Also used : OverdueStateSet(org.killbill.billing.overdue.config.api.OverdueStateSet) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) BlockingState(org.killbill.billing.entitlement.api.BlockingState) DefaultOverdueConfig(org.killbill.billing.overdue.config.DefaultOverdueConfig) DefaultOverdueConfig(org.killbill.billing.overdue.config.DefaultOverdueConfig)

Example 15 with InternalTenantContext

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

the class TestStateMachineConfigCache method testExistingTenantStateMachineConfig.

@Test(groups = "fast")
public void testExistingTenantStateMachineConfig() throws PaymentApiException, URISyntaxException, IOException {
    final String pluginName = UUID.randomUUID().toString();
    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();
    Mockito.when(tenantInternalApi.getPluginPaymentStateMachineConfig(Mockito.eq(pluginName), 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()[1];
            if (multiTenantRecordId.equals(internalContext.getTenantRecordId())) {
                return new String(ByteStreams.toByteArray(UriAccessor.accessUri(Resources.getResource(PaymentModule.DEFAULT_STATE_MACHINE_PAYMENT_XML).toExternalForm())));
            } else if (otherMultiTenantRecordId.equals(internalContext.getTenantRecordId())) {
                return new String(ByteStreams.toByteArray(UriAccessor.accessUri(Resources.getResource(PaymentModule.DEFAULT_STATE_MACHINE_RETRY_XML).toExternalForm())));
            } else {
                return null;
            }
        }
    });
    // Verify the lookup for a non-cached tenant. No system config is set yet but EhCacheStateMachineConfigCache returns a default empty one
    final StateMachineConfig defaultStateMachineConfig = stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, differentMultiTenantContext);
    Assert.assertNotNull(defaultStateMachineConfig);
    // Make sure the cache loader isn't invoked, see https://github.com/killbill/killbill/issues/300
    shouldThrow.set(true);
    final StateMachineConfig defaultStateMachineConfig2 = stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, differentMultiTenantContext);
    Assert.assertNotNull(defaultStateMachineConfig2);
    Assert.assertEquals(defaultStateMachineConfig2, defaultStateMachineConfig);
    shouldThrow.set(false);
    // Verify the lookup for this tenant
    Assert.assertEquals(stateMachineConfigCache.getPaymentStateMachineConfig(UUID.randomUUID().toString(), multiTenantContext), defaultStateMachineConfig);
    final StateMachineConfig result = stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, multiTenantContext);
    Assert.assertNotNull(result);
    Assert.assertNotEquals(result, defaultStateMachineConfig);
    Assert.assertEquals(result.getStateMachines().length, 8);
    // Verify the lookup for another tenant
    Assert.assertEquals(stateMachineConfigCache.getPaymentStateMachineConfig(UUID.randomUUID().toString(), otherMultiTenantContext), defaultStateMachineConfig);
    final StateMachineConfig otherResult = stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, otherMultiTenantContext);
    Assert.assertNotNull(otherResult);
    Assert.assertEquals(otherResult.getStateMachines().length, 1);
    shouldThrow.set(true);
    // Verify the lookup for this tenant
    Assert.assertEquals(stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, multiTenantContext), 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(stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, sameMultiTenantContext), result);
    // Verify the lookup with the other tenant
    Assert.assertEquals(stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, otherMultiTenantContext), otherResult);
    // Verify clearing the cache works
    stateMachineConfigCache.clearPaymentStateMachineConfig(pluginName, multiTenantContext);
    Assert.assertEquals(stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, otherMultiTenantContext), otherResult);
    try {
        stateMachineConfigCache.getPaymentStateMachineConfig(pluginName, multiTenantContext);
        Assert.fail();
    } catch (final CacheException exception) {
        Assert.assertTrue(exception.getCause() instanceof RuntimeException);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CacheException(net.sf.ehcache.CacheException) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) StateMachineConfig(org.killbill.automaton.StateMachineConfig) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) Test(org.testng.annotations.Test)

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