Search in sources :

Example 36 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class DefaultUserDao method addRoleDefinition.

@Override
public void addRoleDefinition(final String role, final List<String> permissions, final String createdBy) throws SecurityApiException {
    final DateTime createdDate = clock.getUTCNow();
    inTransactionWithExceptionHandling(new TransactionCallback<Void>() {

        @Override
        public Void inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
            final RolesPermissionsSqlDao rolesPermissionsSqlDao = handle.attach(RolesPermissionsSqlDao.class);
            final List<RolesPermissionsModelDao> existingRole = rolesPermissionsSqlDao.getByRoleName(role);
            if (!existingRole.isEmpty()) {
                throw new SecurityApiException(ErrorCode.SECURITY_ROLE_ALREADY_EXISTS, role);
            }
            for (final String permission : permissions) {
                rolesPermissionsSqlDao.create(new RolesPermissionsModelDao(role, permission, createdDate, createdBy));
            }
            return null;
        }
    });
}
Also used : TransactionStatus(org.skife.jdbi.v2.TransactionStatus) List(java.util.List) SecurityApiException(org.killbill.billing.security.SecurityApiException) DateTime(org.joda.time.DateTime) SecurityApiException(org.killbill.billing.security.SecurityApiException) Handle(org.skife.jdbi.v2.Handle)

Example 37 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class DefaultUserDao method insertUser.

@Override
public void insertUser(final String username, final String password, final List<String> roles, final String createdBy) throws SecurityApiException {
    final ByteSource salt = rng.nextBytes();
    final String hashedPasswordBase64 = new SimpleHash(KillbillCredentialsMatcher.HASH_ALGORITHM_NAME, password, salt.toBase64(), securityConfig.getShiroNbHashIterations()).toBase64();
    final DateTime createdDate = clock.getUTCNow();
    inTransactionWithExceptionHandling(new TransactionCallback<Void>() {

        @Override
        public Void inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
            final UserRolesSqlDao userRolesSqlDao = handle.attach(UserRolesSqlDao.class);
            for (final String role : roles) {
                userRolesSqlDao.create(new UserRolesModelDao(username, role, createdDate, createdBy));
            }
            final UsersSqlDao usersSqlDao = handle.attach(UsersSqlDao.class);
            final UserModelDao userModelDao = usersSqlDao.getByUsername(username);
            if (userModelDao != null) {
                throw new SecurityApiException(ErrorCode.SECURITY_USER_ALREADY_EXISTS, username);
            }
            usersSqlDao.create(new UserModelDao(username, hashedPasswordBase64, salt.toBase64(), createdDate, createdBy));
            return null;
        }
    });
}
Also used : TransactionStatus(org.skife.jdbi.v2.TransactionStatus) DateTime(org.joda.time.DateTime) SecurityApiException(org.killbill.billing.security.SecurityApiException) Handle(org.skife.jdbi.v2.Handle) SimpleHash(org.apache.shiro.crypto.hash.SimpleHash) ByteSource(org.apache.shiro.util.ByteSource) SecurityApiException(org.killbill.billing.security.SecurityApiException)

Example 38 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class DefaultUserDao method updateUserPassword.

@Override
public void updateUserPassword(final String username, final String password, final String updatedBy) throws SecurityApiException {
    final ByteSource salt = rng.nextBytes();
    final String hashedPasswordBase64 = new SimpleHash(KillbillCredentialsMatcher.HASH_ALGORITHM_NAME, password, salt.toBase64(), securityConfig.getShiroNbHashIterations()).toBase64();
    inTransactionWithExceptionHandling(new TransactionCallback<Void>() {

        @Override
        public Void inTransaction(final Handle handle, final TransactionStatus status) throws Exception {
            final DateTime updatedDate = clock.getUTCNow();
            final UsersSqlDao usersSqlDao = handle.attach(UsersSqlDao.class);
            final UserModelDao userModelDao = usersSqlDao.getByUsername(username);
            if (userModelDao == null) {
                throw new SecurityApiException(ErrorCode.SECURITY_INVALID_USER, username);
            }
            usersSqlDao.updatePassword(username, hashedPasswordBase64, salt.toBase64(), updatedDate.toDate(), updatedBy);
            return null;
        }
    });
}
Also used : TransactionStatus(org.skife.jdbi.v2.TransactionStatus) SecurityApiException(org.killbill.billing.security.SecurityApiException) DateTime(org.joda.time.DateTime) Handle(org.skife.jdbi.v2.Handle) SimpleHash(org.apache.shiro.crypto.hash.SimpleHash) ByteSource(org.apache.shiro.util.ByteSource) SecurityApiException(org.killbill.billing.security.SecurityApiException)

Example 39 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class TestUserApiCancel method testWithMultipleCancellationEvent.

@Test(groups = "slow")
public void testWithMultipleCancellationEvent() throws SubscriptionBillingApiException, SubscriptionBaseApiException {
    final String prod = "Shotgun";
    final BillingPeriod term = BillingPeriod.MONTHLY;
    final String planSet = PriceListSet.DEFAULT_PRICELIST_NAME;
    // CREATE
    DefaultSubscriptionBase subscription = testUtil.createSubscription(bundle, prod, term, planSet);
    PlanPhase trialPhase = subscription.getCurrentPhase();
    assertEquals(trialPhase.getPhaseType(), PhaseType.TRIAL);
    // NEXT PHASE
    final DateTime expectedPhaseTrialChange = TestSubscriptionHelper.addDuration(subscription.getStartDate(), trialPhase.getDuration());
    testUtil.checkNextPhaseChange(subscription, 1, expectedPhaseTrialChange);
    // MOVE TO NEXT PHASE
    testListener.pushExpectedEvent(NextEvent.PHASE);
    Interval it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusDays(31));
    clock.addDeltaFromReality(it.toDurationMillis());
    assertListenerStatus();
    trialPhase = subscription.getCurrentPhase();
    assertEquals(trialPhase.getPhaseType(), PhaseType.EVERGREEN);
    // SET CTD + RE READ SUBSCRIPTION + CHANGE PLAN
    final Duration ctd = testUtil.getDurationMonth(1);
    final DateTime newChargedThroughDate = TestSubscriptionHelper.addDuration(expectedPhaseTrialChange, ctd);
    setChargedThroughDate(subscription.getId(), newChargedThroughDate, internalCallContext);
    subscription = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
    assertEquals(subscription.getLastActiveProduct().getName(), prod);
    assertEquals(subscription.getLastActivePriceList().getName(), planSet);
    assertEquals(subscription.getLastActiveBillingPeriod(), term);
    assertEquals(subscription.getLastActiveCategory(), ProductCategory.BASE);
    // CANCEL
    subscription.cancel(callContext);
    assertListenerStatus();
    subscription = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
    Assert.assertEquals(subscription.getAllTransitions().size(), 3);
    // Manually add a CANCEL event on the same EOT date as the previous one to verify the code is resilient enough to ignore it
    final SubscriptionBaseEvent cancelEvent = subscription.getEvents().get(subscription.getEvents().size() - 1);
    final SubscriptionEventModelDao newCancelEvent = new SubscriptionEventModelDao(cancelEvent);
    newCancelEvent.setId(UUID.randomUUID());
    final Handle handle = dbi.open();
    final SubscriptionEventSqlDao sqlDao = handle.attach(SubscriptionEventSqlDao.class);
    sqlDao.create(newCancelEvent, internalCallContext);
    subscription = (DefaultSubscriptionBase) subscriptionInternalApi.getSubscriptionFromId(subscription.getId(), internalCallContext);
    // The extra cancel event is being ignored
    Assert.assertEquals(subscription.getEvents().size(), 3);
    Assert.assertEquals(subscription.getAllTransitions().size(), 3);
    // We expect only one CANCEL event, this other one is skipped
    testListener.pushExpectedEvents(NextEvent.CANCEL);
    it = new Interval(clock.getUTCNow(), clock.getUTCNow().plusMonths(1));
    clock.addDeltaFromReality(it.toDurationMillis());
    assertListenerStatus();
    // Our previous transition should be a CANCEL with a valid previous plan
    final SubscriptionBaseTransition previousTransition = subscription.getPreviousTransition();
    Assert.assertEquals(previousTransition.getPreviousState(), EntitlementState.ACTIVE);
    Assert.assertNotNull(previousTransition.getPreviousPlan());
}
Also used : SubscriptionEventSqlDao(org.killbill.billing.subscription.engine.dao.SubscriptionEventSqlDao) BillingPeriod(org.killbill.billing.catalog.api.BillingPeriod) PlanPhase(org.killbill.billing.catalog.api.PlanPhase) Duration(org.killbill.billing.catalog.api.Duration) SubscriptionBaseEvent(org.killbill.billing.subscription.events.SubscriptionBaseEvent) SubscriptionEventModelDao(org.killbill.billing.subscription.engine.dao.model.SubscriptionEventModelDao) DateTime(org.joda.time.DateTime) Interval(org.joda.time.Interval) Handle(org.skife.jdbi.v2.Handle) Test(org.testng.annotations.Test)

Example 40 with Handle

use of jnc.platform.win32.Handle in project killbill by killbill.

the class TestInvoiceDispatcher method testWithParking.

@Test(groups = "slow")
public void testWithParking() throws InvoiceApiException, AccountApiException, CatalogApiException, SubscriptionBaseApiException, TagDefinitionApiException {
    final UUID accountId = account.getId();
    final BillingEventSet events = new MockBillingEventSet();
    final Plan plan = MockPlan.createBicycleNoTrialEvergreen1USD();
    final PlanPhase planPhase = MockPlanPhase.create1USDMonthlyEvergreen();
    final DateTime effectiveDate = clock.getUTCNow().minusDays(1);
    final Currency currency = Currency.USD;
    final BigDecimal fixedPrice = null;
    events.add(invoiceUtil.createMockBillingEvent(account, subscription, effectiveDate, plan, planPhase, fixedPrice, BigDecimal.ONE, currency, BillingPeriod.MONTHLY, 1, BillingMode.IN_ADVANCE, "", 1L, SubscriptionBaseTransitionType.CREATE));
    Mockito.when(billingApi.getBillingEventsForAccountAndUpdateAccountBCD(Mockito.<UUID>any(), Mockito.<DryRunArguments>any(), Mockito.<LocalDate>any(), Mockito.<InternalCallContext>any())).thenReturn(events);
    final LocalDate target = internalCallContext.toLocalDate(effectiveDate);
    final InvoiceDispatcher dispatcher = new InvoiceDispatcher(generator, accountApi, billingApi, subscriptionApi, invoiceDao, internalCallContextFactory, invoicePluginDispatcher, locker, bus, notificationQueueService, invoiceConfig, clock, invoiceOptimizer, parkedAccountsManager);
    // Verify initial tags state for account
    Assert.assertTrue(tagUserApi.getTagsForAccount(accountId, true, callContext).isEmpty());
    // Create chaos on disk
    final InvoiceModelDao invoiceModelDao = new InvoiceModelDao(accountId, target, target, currency, false);
    final InvoiceItemModelDao invoiceItemModelDao1 = new InvoiceItemModelDao(clock.getUTCNow(), InvoiceItemType.RECURRING, invoiceModelDao.getId(), accountId, subscription.getBundleId(), subscription.getId(), "Bad data", null, plan.getName(), planPhase.getName(), null, null, effectiveDate.toLocalDate(), effectiveDate.plusMonths(1).toLocalDate(), BigDecimal.TEN, BigDecimal.ONE, currency, null);
    final InvoiceItemModelDao invoiceItemModelDao2 = new InvoiceItemModelDao(clock.getUTCNow(), InvoiceItemType.RECURRING, invoiceModelDao.getId(), accountId, subscription.getBundleId(), subscription.getId(), "Bad data", null, plan.getName(), planPhase.getName(), null, null, effectiveDate.plusDays(1).toLocalDate(), effectiveDate.plusMonths(1).toLocalDate(), BigDecimal.TEN, BigDecimal.ONE, currency, null);
    invoiceModelDao.addInvoiceItem(invoiceItemModelDao1);
    invoiceModelDao.addInvoiceItem(invoiceItemModelDao2);
    invoiceDao.createInvoices(ImmutableList.<InvoiceModelDao>of(invoiceModelDao), events, ImmutableSet.of(), context);
    try {
        dispatcher.processAccountFromNotificationOrBusEvent(accountId, target, new DryRunFutureDateArguments(), false, context);
        Assert.fail();
    } catch (final InvoiceApiException e) {
        Assert.assertEquals(e.getCode(), ErrorCode.UNEXPECTED_ERROR.getCode());
        Assert.assertTrue(e.getCause().getMessage().startsWith("Double billing detected"));
    }
    // Dry-run: no side effect on disk
    Assert.assertEquals(invoiceDao.getInvoicesByAccount(false, context).size(), 1);
    Assert.assertTrue(tagUserApi.getTagsForAccount(accountId, true, callContext).isEmpty());
    try {
        dispatcher.processAccountFromNotificationOrBusEvent(accountId, target, null, false, context);
        Assert.fail();
    } catch (final InvoiceApiException e) {
        Assert.assertEquals(e.getCode(), ErrorCode.UNEXPECTED_ERROR.getCode());
        Assert.assertTrue(e.getCause().getMessage().startsWith("Double billing detected"));
    }
    Assert.assertEquals(invoiceDao.getInvoicesByAccount(false, context).size(), 1);
    // No dry-run: account is parked
    final List<Tag> tags = tagUserApi.getTagsForAccount(accountId, false, callContext);
    Assert.assertEquals(tags.size(), 1);
    Assert.assertEquals(tags.get(0).getTagDefinitionId(), SystemTags.PARK_TAG_DEFINITION_ID);
    // isApiCall=false
    final Invoice nullInvoice1 = dispatcher.processAccountFromNotificationOrBusEvent(accountId, target, null, false, context);
    Assert.assertNull(nullInvoice1);
    // No dry-run and isApiCall=true
    try {
        dispatcher.processAccount(true, accountId, target, null, false, context);
        Assert.fail();
    } catch (final InvoiceApiException e) {
        Assert.assertEquals(e.getCode(), ErrorCode.UNEXPECTED_ERROR.getCode());
        Assert.assertTrue(e.getCause().getMessage().startsWith("Double billing detected"));
    }
    // Idempotency
    Assert.assertEquals(invoiceDao.getInvoicesByAccount(false, context).size(), 1);
    Assert.assertEquals(tagUserApi.getTagsForAccount(accountId, false, callContext), tags);
    // Fix state
    dbi.withHandle(new HandleCallback<Void>() {

        @Override
        public Void withHandle(final Handle handle) throws Exception {
            handle.execute("delete from invoices");
            handle.execute("delete from invoice_items");
            return null;
        }
    });
    // Dry-run and isApiCall=false: still parked
    final Invoice nullInvoice2 = dispatcher.processAccountFromNotificationOrBusEvent(accountId, target, new DryRunFutureDateArguments(), false, context);
    Assert.assertNull(nullInvoice2);
    // Dry-run and isApiCall=true: call goes through
    final Invoice invoice1 = dispatcher.processAccount(true, accountId, target, new DryRunFutureDateArguments(), false, context);
    Assert.assertNotNull(invoice1);
    Assert.assertEquals(invoiceDao.getInvoicesByAccount(false, context).size(), 0);
    // Dry-run: still parked
    Assert.assertEquals(tagUserApi.getTagsForAccount(accountId, false, callContext).size(), 1);
    // No dry-run and isApiCall=true: call goes through
    final Invoice invoice2 = dispatcher.processAccount(true, accountId, target, null, false, context);
    Assert.assertNotNull(invoice2);
    Assert.assertEquals(invoiceDao.getInvoicesByAccount(false, context).size(), 1);
    // No dry-run: now unparked
    Assert.assertEquals(tagUserApi.getTagsForAccount(accountId, false, callContext).size(), 0);
    Assert.assertEquals(tagUserApi.getTagsForAccount(accountId, true, callContext).size(), 1);
}
Also used : Invoice(org.killbill.billing.invoice.api.Invoice) InvoiceModelDao(org.killbill.billing.invoice.dao.InvoiceModelDao) MockPlan(org.killbill.billing.catalog.MockPlan) Plan(org.killbill.billing.catalog.api.Plan) LocalDate(org.joda.time.LocalDate) DateTime(org.joda.time.DateTime) BigDecimal(java.math.BigDecimal) CatalogApiException(org.killbill.billing.catalog.api.CatalogApiException) AccountApiException(org.killbill.billing.account.api.AccountApiException) InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) TagDefinitionApiException(org.killbill.billing.util.api.TagDefinitionApiException) SubscriptionBaseApiException(org.killbill.billing.subscription.api.user.SubscriptionBaseApiException) Handle(org.skife.jdbi.v2.Handle) InvoiceApiException(org.killbill.billing.invoice.api.InvoiceApiException) InvoiceItemModelDao(org.killbill.billing.invoice.dao.InvoiceItemModelDao) BillingEventSet(org.killbill.billing.junction.BillingEventSet) Currency(org.killbill.billing.catalog.api.Currency) DryRunFutureDateArguments(org.killbill.billing.invoice.TestInvoiceHelper.DryRunFutureDateArguments) PlanPhase(org.killbill.billing.catalog.api.PlanPhase) MockPlanPhase(org.killbill.billing.catalog.MockPlanPhase) Tag(org.killbill.billing.util.tag.Tag) UUID(java.util.UUID) Test(org.testng.annotations.Test)

Aggregations

Handle (org.skife.jdbi.v2.Handle)103 DBI (org.skife.jdbi.v2.DBI)28 Before (org.junit.Before)21 IOException (java.io.IOException)18 List (java.util.List)17 DataSourceFactory (io.dropwizard.db.DataSourceFactory)15 DBIFactory (io.dropwizard.jdbi.DBIFactory)15 SQLException (java.sql.SQLException)15 Map (java.util.Map)14 Test (org.junit.Test)14 Test (org.testng.annotations.Test)14 DateTime (org.joda.time.DateTime)13 ArrayList (java.util.ArrayList)11 TransactionStatus (org.skife.jdbi.v2.TransactionStatus)11 ResultSet (java.sql.ResultSet)10 ImmutableList (com.google.common.collect.ImmutableList)8 UUID (java.util.UUID)8 CallbackFailedException (org.skife.jdbi.v2.exceptions.CallbackFailedException)7 ImmutableSet (com.google.common.collect.ImmutableSet)6 Set (java.util.Set)6