Search in sources :

Example 11 with VersionedCatalog

use of org.killbill.billing.catalog.api.VersionedCatalog in project killbill by killbill.

the class TestVersionedCatalogLoader method testLoadCatalogFromInsideResourceFolder.

@Test(groups = "fast")
public void testLoadCatalogFromInsideResourceFolder() throws CatalogApiException {
    final VersionedCatalog c = loader.loadDefaultCatalog("com/acme/SpyCarCustom.xml");
    Assert.assertEquals(c.getVersions().size(), 1);
    final DateTime dt = new DateTime("2015-10-04T00:00:00+00:00");
    Assert.assertEquals(c.getVersions().get(0).getEffectiveDate(), dt.toDate());
    Assert.assertEquals(c.getCatalogName(), "SpyCarCustom");
}
Also used : VersionedCatalog(org.killbill.billing.catalog.api.VersionedCatalog) DefaultVersionedCatalog(org.killbill.billing.catalog.DefaultVersionedCatalog) DateTime(org.joda.time.DateTime) Test(org.testng.annotations.Test)

Example 12 with VersionedCatalog

use of org.killbill.billing.catalog.api.VersionedCatalog in project killbill by killbill.

the class TestVersionedCatalogLoader method testLoadCatalogFromClasspathResourceFolder.

@Test(groups = "fast")
public void testLoadCatalogFromClasspathResourceFolder() throws CatalogApiException {
    final VersionedCatalog c = loader.loadDefaultCatalog("org/killbill/billing/catalog/SpyCarBasic.xml");
    Assert.assertEquals(c.getVersions().size(), 1);
    final DateTime dt = new DateTime("2013-02-08T00:00:00+00:00");
    Assert.assertEquals(c.getVersions().get(0).getEffectiveDate(), dt.toDate());
    Assert.assertEquals(c.getCatalogName(), "SpyCarBasic");
}
Also used : VersionedCatalog(org.killbill.billing.catalog.api.VersionedCatalog) DefaultVersionedCatalog(org.killbill.billing.catalog.DefaultVersionedCatalog) DateTime(org.joda.time.DateTime) Test(org.testng.annotations.Test)

Example 13 with VersionedCatalog

use of org.killbill.billing.catalog.api.VersionedCatalog in project killbill by killbill.

the class TestDefaultCatalogCache method testExistingTenantCatalog.

// 
// Verify CatalogCache returns per tenant catalog:
// 1. We first mock TenantInternalApi to return a different catalog than the default one
// 2. We then mock TenantInternalApi to throw RuntimeException which means catalog was cached and there was no additional call
// to the TenantInternalApi api (otherwise test would fail with RuntimeException)
// 
@Test(groups = "fast")
public void testExistingTenantCatalog() throws CatalogApiException, 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 tenantInputCatalog = UriAccessor.accessUri(new URI(Resources.getResource("org/killbill/billing/catalog/SpyCarAdvanced.xml").toExternalForm()));
    final String tenantCatalogXML = CharStreams.toString(new InputStreamReader(tenantInputCatalog, "UTF-8"));
    final InputStream otherTenantInputCatalog = UriAccessor.accessUri(new URI(Resources.getResource("org/killbill/billing/catalog/SpyCarBasic.xml").toExternalForm()));
    final String otherTenantCatalogXML = CharStreams.toString(new InputStreamReader(otherTenantInputCatalog, "UTF-8"));
    Mockito.when(tenantInternalApi.getTenantCatalogs(Mockito.any(InternalTenantContext.class))).thenAnswer(new Answer<List<String>>() {

        @Override
        public List<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 ImmutableList.<String>of(tenantCatalogXML);
            } else if (otherMultiTenantRecordId.equals(internalContext.getTenantRecordId())) {
                return ImmutableList.<String>of(otherTenantCatalogXML);
            } else {
                return ImmutableList.<String>of();
            }
        }
    });
    // Verify the lookup for a non-cached tenant. No system config is set yet but DefaultCatalogCache returns a default empty one
    VersionedCatalog differentResult = catalogCache.getCatalog(true, true, false, differentMultiTenantContext);
    Assert.assertNotNull(differentResult);
    Assert.assertEquals(differentResult.getCatalogName(), "EmptyCatalog");
    // Make sure the cache loader isn't invoked, see https://github.com/killbill/killbill/issues/300
    shouldThrow.set(true);
    differentResult = catalogCache.getCatalog(true, true, false, differentMultiTenantContext);
    Assert.assertNotNull(differentResult);
    Assert.assertEquals(differentResult.getCatalogName(), "EmptyCatalog");
    shouldThrow.set(false);
    // Set a default config
    catalogCache.loadDefaultCatalog(Resources.getResource("org/killbill/billing/catalog/SpyCarBasic.xml").toExternalForm());
    // Verify the lookup for this tenant
    final VersionedCatalog result = catalogCache.getCatalog(true, true, false, multiTenantContext);
    Assert.assertNotNull(result);
    final StaticCatalog catalogVersion = result.getVersions().get(result.getVersions().size() - 1);
    final Collection<Product> products = catalogVersion.getProducts();
    Assert.assertEquals(products.size(), 6);
    // Verify the lookup for another tenant
    final VersionedCatalog otherResult = catalogCache.getCatalog(true, true, false, otherMultiTenantContext);
    Assert.assertNotNull(otherResult);
    final StaticCatalog othercatalogVersion = otherResult.getVersions().get(result.getVersions().size() - 1);
    final Collection<Product> otherProducts = othercatalogVersion.getProducts();
    Assert.assertEquals(otherProducts.size(), 3);
    shouldThrow.set(true);
    // Verify the lookup for this tenant
    final VersionedCatalog result2 = catalogCache.getCatalog(true, true, false, 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(catalogCache.getCatalog(true, true, false, sameMultiTenantContext), result);
    // Verify the lookup with the other tenant
    Assert.assertEquals(catalogCache.getCatalog(true, true, false, otherMultiTenantContext), otherResult);
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Product(org.killbill.billing.catalog.api.Product) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) URI(java.net.URI) StaticCatalog(org.killbill.billing.catalog.api.StaticCatalog) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) VersionedCatalog(org.killbill.billing.catalog.api.VersionedCatalog) DefaultVersionedCatalog(org.killbill.billing.catalog.DefaultVersionedCatalog) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) StandaloneCatalogWithPriceOverride(org.killbill.billing.catalog.StandaloneCatalogWithPriceOverride) Test(org.testng.annotations.Test)

Example 14 with VersionedCatalog

use of org.killbill.billing.catalog.api.VersionedCatalog in project killbill by killbill.

the class DefaultEntitlementApi method createBaseEntitlementsWithAddOns.

private List<UUID> createBaseEntitlementsWithAddOns(final OperationType operationType, final UUID accountId, final Iterable<BaseEntitlementWithAddOnsSpecifier> originalBaseEntitlementWithAddOnsSpecifiers, final boolean renameCancelledBundleIfExist, final Iterable<PluginProperty> properties, final CallContext callContext) throws EntitlementApiException {
    logCreateEntitlementsWithAOs(log, originalBaseEntitlementWithAddOnsSpecifiers);
    final EntitlementContext pluginContext = new DefaultEntitlementContext(operationType, accountId, null, originalBaseEntitlementWithAddOnsSpecifiers, null, properties, callContext);
    final WithEntitlementPlugin<List<UUID>> createBaseEntitlementsWithAddOns = new WithEntitlementPlugin<List<UUID>>() {

        @Override
        public List<UUID> doCall(final EntitlementApi entitlementApi, final DefaultEntitlementContext updatedPluginContext) throws EntitlementApiException {
            final InternalCallContext contextWithValidAccountRecordId = internalCallContextFactory.createInternalCallContext(accountId, callContext);
            final VersionedCatalog catalog;
            try {
                catalog = catalogInternalApi.getFullCatalog(true, true, contextWithValidAccountRecordId);
            } catch (final CatalogApiException e) {
                throw new EntitlementApiException(e);
            }
            final Map<UUID, Optional<EventsStream>> eventsStreamForBaseSubscriptionPerBundle = new HashMap<UUID, Optional<EventsStream>>();
            final Map<String, Optional<UUID>> bundleKeyToIdMapping = new HashMap<String, Optional<UUID>>();
            final Iterable<BaseEntitlementWithAddOnsSpecifier> baseEntitlementWithAddOnsSpecifiersAfterPlugins = updatedPluginContext.getBaseEntitlementWithAddOnsSpecifiers();
            final Collection<SubscriptionBaseWithAddOnsSpecifier> subscriptionBaseWithAddOnsSpecifiers = new LinkedList<SubscriptionBaseWithAddOnsSpecifier>();
            DateTime upTo = null;
            for (final BaseEntitlementWithAddOnsSpecifier baseEntitlementWithAddOnsSpecifier : baseEntitlementWithAddOnsSpecifiersAfterPlugins) {
                // Entitlement
                final DateTime entitlementRequestedDate = dateHelper.fromLocalDateAndReferenceTime(baseEntitlementWithAddOnsSpecifier.getEntitlementEffectiveDate(), updatedPluginContext.getCreatedDate(), contextWithValidAccountRecordId);
                upTo = upTo == null || upTo.compareTo(entitlementRequestedDate) < 0 ? entitlementRequestedDate : upTo;
                final UUID bundleId = populateCaches(baseEntitlementWithAddOnsSpecifier, eventsStreamForBaseSubscriptionPerBundle, bundleKeyToIdMapping, catalog, callContext, contextWithValidAccountRecordId);
                if (bundleId != null) {
                    final Optional<EventsStream> eventsStreamForBaseSubscription = eventsStreamForBaseSubscriptionPerBundle.get(bundleId);
                    if (eventsStreamForBaseSubscription.isPresent()) {
                        // Verify if the operation is valid for that bundle
                        preCheckAddEntitlement(bundleId, entitlementRequestedDate, baseEntitlementWithAddOnsSpecifier, eventsStreamForBaseSubscription.get());
                    }
                }
                final SubscriptionBaseWithAddOnsSpecifier subscriptionBaseWithAddOnsSpecifier = new SubscriptionBaseWithAddOnsSpecifier(baseEntitlementWithAddOnsSpecifier.getBundleId(), baseEntitlementWithAddOnsSpecifier.getBundleExternalKey(), baseEntitlementWithAddOnsSpecifier.getEntitlementSpecifier(), baseEntitlementWithAddOnsSpecifier.getBillingEffectiveDate(), baseEntitlementWithAddOnsSpecifier.isMigrated());
                subscriptionBaseWithAddOnsSpecifiers.add(subscriptionBaseWithAddOnsSpecifier);
            }
            // Verify if operation is allowed by looking for is_block_change on Account
            // Note that to fully check for block_change we should also look for BlockingState at the BUNDLE/SUBSCRIPTION level in case some of the input contain a BP that already exists.
            checkForAccountBlockingChange(accountId, upTo, contextWithValidAccountRecordId);
            final List<SubscriptionBaseWithAddOns> subscriptionsWithAddOns;
            try {
                subscriptionsWithAddOns = subscriptionBaseInternalApi.createBaseSubscriptionsWithAddOns(catalog, subscriptionBaseWithAddOnsSpecifiers, renameCancelledBundleIfExist, contextWithValidAccountRecordId);
            } catch (final SubscriptionBaseApiException e) {
                throw new EntitlementApiException(e);
            }
            // Update the context for plugins (assume underlying ordering is respected)
            for (int i = 0; i < subscriptionsWithAddOns.size(); i++) {
                final SubscriptionBaseWithAddOns subscriptionBaseWithAddOns = subscriptionsWithAddOns.get(i);
                updatedPluginContext.getBaseEntitlementWithAddOnsSpecifiers(i).setBundleId(subscriptionBaseWithAddOns.getBundle().getId());
                updatedPluginContext.getBaseEntitlementWithAddOnsSpecifiers(i).setBundleExternalKey(subscriptionBaseWithAddOns.getBundle().getExternalKey());
            }
            return createEntitlementEvents(baseEntitlementWithAddOnsSpecifiersAfterPlugins, subscriptionsWithAddOns, updatedPluginContext, contextWithValidAccountRecordId);
        }
    };
    return pluginExecution.executeWithPlugin(createBaseEntitlementsWithAddOns, pluginContext);
}
Also used : SubscriptionBaseWithAddOns(org.killbill.billing.subscription.api.SubscriptionBaseWithAddOns) SubscriptionBaseWithAddOnsSpecifier(org.killbill.billing.subscription.api.SubscriptionBaseWithAddOnsSpecifier) WithEntitlementPlugin(org.killbill.billing.entitlement.api.EntitlementPluginExecution.WithEntitlementPlugin) HashMap(java.util.HashMap) EventsStream(org.killbill.billing.entitlement.EventsStream) InternalCallContext(org.killbill.billing.callcontext.InternalCallContext) DateTime(org.joda.time.DateTime) VersionedCatalog(org.killbill.billing.catalog.api.VersionedCatalog) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) LinkedList(java.util.LinkedList) UUID(java.util.UUID) EntitlementContext(org.killbill.billing.entitlement.plugin.api.EntitlementContext) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) Optional(com.google.common.base.Optional) LinkedList(java.util.LinkedList) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException)

Example 15 with VersionedCatalog

use of org.killbill.billing.catalog.api.VersionedCatalog in project killbill by killbill.

the class DefaultSubscriptionApi method getBlockingStates.

@Override
public Iterable<BlockingState> getBlockingStates(final UUID accountId, @Nullable final List<BlockingStateType> typeFilter, @Nullable final List<String> svcsFilter, final OrderingType orderingType, final int timeFilter, final TenantContext tenantContext) throws EntitlementApiException {
    try {
        final InternalTenantContext internalTenantContextWithValidAccountRecordId = internalCallContextFactory.createInternalTenantContext(accountId, tenantContext);
        final VersionedCatalog catalog = catalogInternalApi.getFullCatalog(true, true, internalTenantContextWithValidAccountRecordId);
        final List<BlockingState> allBlockingStates = blockingStateDao.getBlockingAllForAccountRecordId(catalog, internalTenantContextWithValidAccountRecordId);
        final ImmutableAccountData account = accountApi.getImmutableAccountDataById(accountId, internalTenantContextWithValidAccountRecordId);
        final Iterable<BlockingState> filteredByTypes = typeFilter != null && !typeFilter.isEmpty() ? Iterables.filter(allBlockingStates, new Predicate<BlockingState>() {

            @Override
            public boolean apply(final BlockingState input) {
                return typeFilter.contains(input.getType());
            }
        }) : allBlockingStates;
        final Iterable<BlockingState> filteredByTypesAndSvcs = svcsFilter != null && !svcsFilter.isEmpty() ? Iterables.filter(filteredByTypes, new Predicate<BlockingState>() {

            @Override
            public boolean apply(final BlockingState input) {
                return svcsFilter.contains(input.getService());
            }
        }) : filteredByTypes;
        final LocalDate localDateNowInAccountTimezone = internalTenantContextWithValidAccountRecordId.toLocalDate(clock.getUTCNow());
        final List<BlockingState> result = new ArrayList<BlockingState>();
        for (final BlockingState cur : filteredByTypesAndSvcs) {
            final LocalDate eventDate = internalTenantContextWithValidAccountRecordId.toLocalDate(cur.getEffectiveDate());
            final int comp = eventDate.compareTo(localDateNowInAccountTimezone);
            if ((comp <= 1 && ((timeFilter & SubscriptionApi.PAST_EVENTS) == SubscriptionApi.PAST_EVENTS)) || (comp == 0 && ((timeFilter & SubscriptionApi.PRESENT_EVENTS) == SubscriptionApi.PRESENT_EVENTS)) || (comp >= 1 && ((timeFilter & SubscriptionApi.FUTURE_EVENTS) == SubscriptionApi.FUTURE_EVENTS))) {
                result.add(cur);
            }
        }
        return orderingType == OrderingType.ASCENDING ? result : Lists.reverse(result);
    } catch (final AccountApiException e) {
        throw new EntitlementApiException(e);
    } catch (final CatalogApiException e) {
        throw new EntitlementApiException(e);
    }
}
Also used : ImmutableAccountData(org.killbill.billing.account.api.ImmutableAccountData) ArrayList(java.util.ArrayList) DefaultBlockingState(org.killbill.billing.junction.DefaultBlockingState) EntitlementLoggingHelper.logAddBlockingState(org.killbill.billing.entitlement.logging.EntitlementLoggingHelper.logAddBlockingState) LocalDate(org.joda.time.LocalDate) Predicate(com.google.common.base.Predicate) VersionedCatalog(org.killbill.billing.catalog.api.VersionedCatalog) InternalTenantContext(org.killbill.billing.callcontext.InternalTenantContext) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) AccountApiException(org.killbill.billing.account.api.AccountApiException)

Aggregations

VersionedCatalog (org.killbill.billing.catalog.api.VersionedCatalog)33 Test (org.testng.annotations.Test)14 DefaultVersionedCatalog (org.killbill.billing.catalog.DefaultVersionedCatalog)11 UUID (java.util.UUID)10 DateTime (org.joda.time.DateTime)8 LocalDate (org.joda.time.LocalDate)8 BigDecimal (java.math.BigDecimal)7 ArrayList (java.util.ArrayList)7 Account (org.killbill.billing.account.api.Account)7 ExpectedInvoiceItemCheck (org.killbill.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck)7 PlanPhaseSpecifier (org.killbill.billing.catalog.api.PlanPhaseSpecifier)7 Invoice (org.killbill.billing.invoice.api.Invoice)7 ImmutableList (com.google.common.collect.ImmutableList)6 List (java.util.List)6 InternalTenantContext (org.killbill.billing.callcontext.InternalTenantContext)6 StaticCatalog (org.killbill.billing.catalog.api.StaticCatalog)6 DefaultEntitlementSpecifier (org.killbill.billing.entitlement.api.DefaultEntitlementSpecifier)6 CatalogApiException (org.killbill.billing.catalog.api.CatalogApiException)5 ApiOperation (io.swagger.annotations.ApiOperation)4 ApiResponses (io.swagger.annotations.ApiResponses)4