@Override public List<SubscriptionBaseEvent> getPendingEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) { final Date now = clock.getUTCNow().toDate(); return transactionalSqlDao.execute(true, new EntitySqlDaoTransactionWrapper<List<SubscriptionBaseEvent>>() { @Override public List<SubscriptionBaseEvent> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception { final List<SubscriptionEventModelDao> eventModels = entitySqlDaoWrapperFactory.become(SubscriptionEventSqlDao.class).getFutureActiveEventForSubscription(subscriptionId.toString(), now, context); return toSubscriptionBaseEvents(eventModels); } }); }
public static InvoicePayment createAndPersistPayment(final InvoiceInternalApi invoicePaymentApi, final Clock clock, final UUID invoiceId, final BigDecimal amount, final Currency currency, final InternalCallContext callContext) throws InvoiceApiException { final InvoicePayment payment = Mockito.mock(InvoicePayment.class); Mockito.when(payment.getId()).thenReturn(UUID.randomUUID()); Mockito.when(payment.getType()).thenReturn(InvoicePaymentType.ATTEMPT); Mockito.when(payment.getInvoiceId()).thenReturn(invoiceId); Mockito.when(payment.getPaymentId()).thenReturn(UUID.randomUUID()); Mockito.when(payment.getPaymentCookieId()).thenReturn(UUID.randomUUID().toString()); final DateTime utcNow = clock.getUTCNow(); Mockito.when(payment.getPaymentDate()).thenReturn(utcNow); Mockito.when(payment.getAmount()).thenReturn(amount); Mockito.when(payment.getCurrency()).thenReturn(currency); Mockito.when(payment.getProcessedCurrency()).thenReturn(currency); Mockito.when(payment.isSuccess()).thenReturn(true); invoicePaymentApi.recordPaymentAttemptCompletion(payment.getInvoiceId(), payment.getAmount(), payment.getCurrency(), payment.getProcessedCurrency(), payment.getPaymentId(), payment.getPaymentCookieId(), payment.getPaymentDate(), payment.isSuccess(), callContext); return payment; } }
@Override public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationEvent event, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException { final String eventJson = objectMapper.writeValueAsString(event); final UUID futureUserToken = UUID.randomUUID(); final Long searchKey2WithNull = MoreObjects.firstNonNull(searchKey2, new Long(0)); final NotificationEventModelDao notification = new NotificationEventModelDao(CreatorName.get(), clock.getUTCNow(), event.getClass().getName(), eventJson, userToken, searchKey1, searchKey2WithNull, futureUserToken, futureNotificationTime, getFullQName()); dao.insertEntry(notification); }
@Override public void update(final AccountModelDao account, final boolean treatNullValueAsReset, final InternalCallContext context) { super.update(account, context); final AccountModelDao currentAccount = getById(account.getId(), context); final Long accountRecordId = getRecordId(account.getId(), context); final long tenantRecordId = context == null ? InternalCallContextFactory.INTERNAL_TENANT_RECORD_ID : context.getTenantRecordId(); final AccountChangeInternalEvent changeEvent = new DefaultAccountChangeEvent(account.getId(), currentAccount, account, accountRecordId, tenantRecordId, UUID.randomUUID(), clock.getUTCNow()); if (changeEvent.hasChanges()) { try { eventBus.post(changeEvent); } catch (final EventBusException ex) { Assert.fail(ex.toString()); } } }
public AccountData initAccountData(final Clock clock) { final AccountData accountData = new MockAccountBuilder().name(UUIDs.randomUUID().toString().substring(1, 8)) .firstNameLength(6) .email(UUIDs.randomUUID().toString().substring(1, 8)) .phone(UUIDs.randomUUID().toString().substring(1, 8)) .migrated(false) .externalKey(UUIDs.randomUUID().toString()) .billingCycleDayLocal(1) .currency(Currency.USD) .paymentMethodId(UUIDs.randomUUID()) .referenceTime(clock.getUTCNow()) .timeZone(DateTimeZone.forID("Europe/Paris")) .build(); assertNotNull(accountData); return accountData; }
final InternalCallContext internalCallContext) throws EntityPersistenceException { final Invoice invoice = Mockito.mock(Invoice.class); final UUID invoiceId = UUID.randomUUID(); final UUID accountId; try { accountId = account.getId(); } catch (final AccountApiException e) { Assert.fail(e.getMessage()); return null; final LocalDate today = clock.getUTCToday(); Mockito.when(invoice.getInvoiceDate()).thenReturn(today); Mockito.when(invoice.getTargetDate()).thenReturn(today);
final String error = status == PaymentPluginStatus.PROCESSED ? "" : GATEWAY_ERROR; InternalPaymentInfo info = payments.get(kbPaymentId.toString()); if (info == null) { info = new InternalPaymentInfo(); payments.put(kbPaymentId.toString(), info); final PaymentTransactionInfoPlugin result = new DefaultNoOpPaymentInfoPlugin(kbPaymentId, kbTransactionId, type, processedAmount, processedCurrency, clock.getUTCNow(), clock.getUTCNow(), status, errorCode, error, null, null, ImmutableList.<PluginProperty>copyOf(pluginProperties)); List<PaymentTransactionInfoPlugin> existingTransactions = paymentTransactions.get(kbPaymentId.toString()); if (existingTransactions == null) { existingTransactions = new ArrayList<PaymentTransactionInfoPlugin>();
public static InvoiceItem createInvoiceItem(final Clock clock, final UUID invoiceId, final UUID accountId, final BigDecimal amount, final Currency currency) { return new FixedPriceInvoiceItem(invoiceId, accountId, UUID.randomUUID(), UUID.randomUUID(), null, "charge back test", "charge back phase", clock.getUTCToday(), amount, currency); }
@Override public void write(final OutputStream output) throws IOException, WebApplicationException { try { final JsonGenerator generator = mapper.getFactory().createGenerator(output); generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); generator.writeStartObject(); while (iterator.hasNext()) { final Tag tag = iterator.next(); final UUID accountId = tag.getObjectId(); try { invoiceUserApi.triggerInvoiceGeneration(accountId, clock.getUTCToday(), callContext); generator.writeStringField(accountId.toString(), OK); } catch (final InvoiceApiException e) { if (e.getCode() != ErrorCode.INVOICE_NOTHING_TO_DO.getCode()) { log.warn("Unable to trigger invoice generation for accountId='{}'", accountId); } generator.writeStringField(accountId.toString(), ErrorCode.fromCode(e.getCode()).toString()); } } generator.writeEndObject(); generator.close(); } finally { // In case the client goes away (IOException), make sure to close the underlying DB connection tags.close(); } } };
@Override public List<SubscriptionBaseEvent> getPendingEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) { synchronized (events) { final List<SubscriptionBaseEvent> results = new LinkedList<SubscriptionBaseEvent>(); for (final SubscriptionBaseEvent cur : events) { if (cur.isActive() && cur.getEffectiveDate().isAfter(clock.getUTCNow()) && cur.getSubscriptionId().equals(subscriptionId)) { results.add(cur); } } return results; } }
private void checkForOrphanEntries() { if (clock.getUTCNow().getMillis() > lastPollingOrphanTime + POLLING_ORPHANS_MSEC) { final List<T> entriesToClaim = fetchReadyEntries(1); final Long previousLowestOrphanEntry = lowestOrphanEntry; lowestOrphanEntry = (entriesToClaim.isEmpty()) ? -1L : entriesToClaim.get(0).getRecordId(); if (previousLowestOrphanEntry > 0 && previousLowestOrphanEntry == lowestOrphanEntry) { log.warn("{} Detected unprocessed bus event {}", DB_QUEUE_LOG_ID, previousLowestOrphanEntry); } lastPollingOrphanTime = clock.getUTCNow().getMillis(); } }
private boolean claimEntry(final T entry) { final Date nextAvailable = clock.getUTCNow().plus(config.getClaimedTime().getMillis()).toDate(); final int claimEntry = executeQuery(new Query<Integer, QueueSqlDao<T>>() { @Override public Integer execute(final QueueSqlDao<T> queueSqlDao) { return queueSqlDao.claimEntry(entry.getRecordId(), clock.getUTCNow().toDate(), CreatorName.get(), nextAvailable, config.getTableName()); } }); final boolean claimed = (claimEntry == 1); if (claimed) { totalClaimed.inc(); log.debug("{} Claimed entry {}", DB_QUEUE_LOG_ID, entry); } return claimed; }
private boolean shouldSkip(final SubscriptionBaseTransition input) { if (visibility == Visibility.FROM_DISK_ONLY && ! ((SubscriptionBaseTransitionData) input).isFromDisk()) { return true; } if ((timeLimit == TimeLimit.FUTURE_ONLY && !input.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) || ((timeLimit == TimeLimit.PAST_OR_PRESENT_ONLY && input.getEffectiveTransitionTime().isAfter(clock.getUTCNow())))) { return true; } return false; }
switch (policy) { case IMMEDIATE: candidateResult = clock.getUTCNow(); break; case START_OF_TERM: candidateResult = getStartDate(); } else if (!chargedThroughDate.isAfter(clock.getUTCNow())) { candidateResult = chargedThroughDate; } else { while (proposedDate.isAfter(clock.getUTCNow())) { proposedDate = proposedDate.minus(billingPeriod.getPeriod()); candidateResult = (chargedThroughDate != null && chargedThroughDate.isAfter(clock.getUTCNow())) ? chargedThroughDate : clock.getUTCNow(); break; default:
if (!noEvents && (requestedDate == null || requestedDate.compareTo(clock.getUTCToday()) <= 0)) { testListener.pushExpectedEvent(NextEvent.CREATE); internalCallContext).get(0); final DefaultSubscriptionBase subscription = (DefaultSubscriptionBase) subscriptionBaseWithAddOns.getSubscriptionBaseList().get(0); assertNotNull(subscription);
private Date getReapingDate() { return clock.getUTCNow().minusMillis((int) pendingPeriod).toDate(); } };
final DateTime minDate = Strings.isNullOrEmpty(minDateOrNull) ? clock.getUTCNow().minusDays(2) : DATE_TIME_FORMATTER.parseDateTime(minDateOrNull).toDateTime(DateTimeZone.UTC); final DateTime maxDate = Strings.isNullOrEmpty(maxDateOrNull) ? clock.getUTCNow().plusDays(2) : DATE_TIME_FORMATTER.parseDateTime(maxDateOrNull).toDateTime(DateTimeZone.UTC);
if (nextPhaseEvent != null && !nextPhaseEvent.getEffectiveDate().equals(changeEvent.getEffectiveDate())) { changeEvents.add(nextPhaseEvent); final Product currentBaseProduct = changeEvent.getEffectiveDate().compareTo(clock.getUTCNow()) <= 0 ? newPlan.getProduct() : subscription.getCurrentOrPendingPlan().getProduct(); addOnSubscriptionsToBeCancelled.addAll(addCancellationAddOnForEventsIfRequired(addOnCancelEvents, currentBaseProduct, subscription.getBundleId(), effectiveDate, fullCatalog, internalTenantContext));
protected SubscriptionBaseBundle getActiveBundleForKey(final String bundleKey, final Catalog catalog, final InternalTenantContext context) throws CatalogApiException { final List<SubscriptionBaseBundle> existingBundles = dao.getSubscriptionBundlesForKey(bundleKey, context); for (final SubscriptionBaseBundle cur : existingBundles) { final List<DefaultSubscriptionBase> subscriptions = dao.getSubscriptions(cur.getId(), ImmutableList.<SubscriptionBaseEvent>of(), catalog, context); for (final SubscriptionBase s : subscriptions) { if (s.getCategory() == ProductCategory.ADD_ON) { continue; } if (s.getEndDate() == null || s.getEndDate().compareTo(clock.getUTCNow()) > 0) { return cur; } } } return null; }
public List<NotificationEventModelDao> getReadyNotifications() { final List<NotificationEventModelDao> readyNotifications = new ArrayList<NotificationEventModelDao>(); synchronized (notifications) { for (final NotificationEventModelDao cur : notifications) { if (cur.getEffectiveDate().isBefore(clock.getUTCNow()) && cur.isAvailableForProcessing(clock.getUTCNow())) { log.info("MockNotificationQ getReadyNotifications found notification: NOW = " + clock.getUTCNow() + " recordId = " + cur.getRecordId() + ", state = " + cur.getProcessingState() + ", effectiveDate = " + cur.getEffectiveDate()); readyNotifications.add(cur); } } } return readyNotifications; }