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;
}
});
}
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;
}
});
}
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;
}
});
}
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());
}
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);
}
Aggregations