Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

@ToString
public String toString() 

Source Link

Document

Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).

Usage

From source file:com.ning.arecibo.collector.rest.DefaultCollectorClient.java

License:Apache License

@Override
public InputStream getHostSamplesAsStream(final Iterable<String> hostNames,
        final Iterable<String> categoriesAndSampleKinds, final DateTime from, final DateTime to,
        final Integer outputCount) throws UniformInterfaceException {
    final MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    for (final String hostName : hostNames) {
        params.add("host", hostName);
    }/*from  w w  w . j a va2s  .  c o  m*/
    for (final String categoriesAndSampleKind : categoriesAndSampleKinds) {
        params.add("category_and_sample_kind", categoriesAndSampleKind);
    }

    params.add("from", from.toString());
    params.add("to", to.toString());
    params.add("output_count", String.valueOf(outputCount));

    return getPathAsStream("host_samples", params);
}

From source file:com.ning.billing.entitlement.api.user.DefaultEntitlementUserApi.java

License:Apache License

@Override
public Subscription createSubscription(final UUID bundleId, final PlanPhaseSpecifier spec,
        final DateTime requestedDateWithMs, final CallContext context) throws EntitlementUserApiException {
    try {//www.  j  ava 2  s .  c o  m
        final String realPriceList = (spec.getPriceListName() == null) ? PriceListSet.DEFAULT_PRICELIST_NAME
                : spec.getPriceListName();
        final DateTime now = clock.getUTCNow();
        final DateTime requestedDate = (requestedDateWithMs != null)
                ? DefaultClock.truncateMs(requestedDateWithMs)
                : now;
        if (requestedDate.isAfter(now)) {
            throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE, now.toString(),
                    requestedDate.toString());
        }
        final DateTime effectiveDate = requestedDate;

        final Catalog catalog = catalogService.getFullCatalog();
        final Plan plan = catalog.findPlan(spec.getProductName(), spec.getBillingPeriod(), realPriceList,
                requestedDate);

        final PlanPhase phase = plan.getAllPhases()[0];
        if (phase == null) {
            throw new EntitlementError(String.format(
                    "No initial PlanPhase for Product %s, term %s and set %s does not exist in the catalog",
                    spec.getProductName(), spec.getBillingPeriod().toString(), realPriceList));
        }

        final SubscriptionBundle bundle = dao.getSubscriptionBundleFromId(bundleId,
                internalCallContextFactory.createInternalTenantContext(context));
        if (bundle == null) {
            throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_NO_BUNDLE, bundleId);
        }

        DateTime bundleStartDate = null;
        final SubscriptionData baseSubscription = (SubscriptionData) dao.getBaseSubscription(bundleId,
                internalCallContextFactory.createInternalTenantContext(context));
        switch (plan.getProduct().getCategory()) {
        case BASE:
            if (baseSubscription != null) {
                if (baseSubscription.getState() == SubscriptionState.ACTIVE) {
                    throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_BP_EXISTS, bundleId);
                } else {
                    // If we do create on an existing CANCELLED BP, this is equivalent to call recreate on that Subscription.
                    final Subscription recreatedSubscriptionForApiUse = createSubscriptionForApiUse(
                            baseSubscription);
                    recreatedSubscriptionForApiUse.recreate(spec, requestedDate, context);
                    return recreatedSubscriptionForApiUse;
                }
            }
            bundleStartDate = requestedDate;
            break;
        case ADD_ON:
            if (baseSubscription == null) {
                throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_NO_BP, bundleId);
            }
            if (effectiveDate.isBefore(baseSubscription.getStartDate())) {
                throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE,
                        effectiveDate.toString(), baseSubscription.getStartDate().toString());
            }
            addonUtils.checkAddonCreationRights(baseSubscription, plan);
            bundleStartDate = baseSubscription.getStartDate();
            break;
        case STANDALONE:
            if (baseSubscription != null) {
                throw new EntitlementUserApiException(ErrorCode.ENT_CREATE_BP_EXISTS, bundleId);
            }
            // Not really but we don't care, there is no alignment for STANDALONE subscriptions
            bundleStartDate = requestedDate;
            break;
        default:
            throw new EntitlementError(String.format("Can't create subscription of type %s",
                    plan.getProduct().getCategory().toString()));
        }

        return apiService.createPlan(
                new SubscriptionBuilder().setId(UUID.randomUUID()).setBundleId(bundleId)
                        .setCategory(plan.getProduct().getCategory()).setBundleStartDate(bundleStartDate)
                        .setAlignStartDate(effectiveDate),
                plan, spec.getPhaseType(), realPriceList, requestedDate, effectiveDate, now, context);
    } catch (CatalogApiException e) {
        throw new EntitlementUserApiException(e);
    }
}

From source file:com.ning.billing.entitlement.api.user.DefaultSubscriptionApiService.java

License:Apache License

private void validateRequestedDate(final SubscriptionData subscription, final DateTime now,
        final DateTime requestedDate) throws EntitlementUserApiException {

    if (requestedDate.isAfter(now)) {
        throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_FUTURE_DATE,
                requestedDate.toString());
    }/*ww w .  j  a  v  a  2s. co  m*/

    final SubscriptionTransition previousTransition = subscription.getPreviousTransition();
    if (previousTransition != null && previousTransition.getEffectiveTransitionTime().isAfter(requestedDate)) {
        throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE, requestedDate.toString(),
                previousTransition.getEffectiveTransitionTime());
    }
}

From source file:com.ning.billing.entitlement.api.user.SubscriptionApiService.java

License:Apache License

public void cancel(SubscriptionData subscription, DateTime requestedDate, boolean eot)
        throws EntitlementUserApiException {

    try {/*from w  w w . j ava 2s  . co  m*/
        SubscriptionState currentState = subscription.getState();
        if (currentState != SubscriptionState.ACTIVE) {
            throw new EntitlementUserApiException(ErrorCode.ENT_CANCEL_BAD_STATE, subscription.getId(),
                    currentState);
        }

        DateTime now = clock.getUTCNow();
        requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
        // STEPH needs to check if requestedDate is before last 'erasable event'?
        if (requestedDate != null && requestedDate.isAfter(now)) {
            throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE,
                    requestedDate.toString());
        }

        Plan currentPlan = subscription.getCurrentPlan();
        PlanPhaseSpecifier planPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(),
                currentPlan.getProduct().getCategory(), subscription.getCurrentPlan().getBillingPeriod(),
                subscription.getCurrentPriceList(), subscription.getCurrentPhase().getPhaseType());

        ActionPolicy policy = null;
        policy = catalogService.getCatalog().planCancelPolicy(planPhase);
        DateTime effectiveDate = subscription.getPlanChangeEffectiveDate(policy, requestedDate);

        EntitlementEvent cancelEvent = new ApiEventCancel(new ApiEventBuilder()
                .setSubscriptionId(subscription.getId()).setActiveVersion(subscription.getActiveVersion())
                .setProcessedDate(now).setEffectiveDate(effectiveDate).setRequestedDate(now));

        dao.cancelSubscription(subscription.getId(), cancelEvent);
        subscription.rebuildTransitions(dao.getEventsForSubscription(subscription.getId()),
                catalogService.getCatalog());
    } catch (CatalogApiException e) {
        throw new EntitlementUserApiException(e);
    }
}

From source file:com.ning.billing.entitlement.api.user.SubscriptionApiService.java

License:Apache License

public void changePlan(SubscriptionData subscription, String productName, BillingPeriod term, String priceList,
        DateTime requestedDate) throws EntitlementUserApiException {

    try {//from w w  w  .j a  v  a  2  s .  c  o  m

        DateTime now = clock.getUTCNow();
        requestedDate = (requestedDate != null) ? DefaultClock.truncateMs(requestedDate) : now;
        // STEPH needs to check if requestedDate is before last 'erasable event'?
        if (requestedDate != null && requestedDate.isAfter(now)) {
            throw new EntitlementUserApiException(ErrorCode.ENT_INVALID_REQUESTED_DATE,
                    requestedDate.toString());
        }

        String currentPriceList = subscription.getCurrentPriceList();

        SubscriptionState currentState = subscription.getState();
        if (currentState != SubscriptionState.ACTIVE) {
            throw new EntitlementUserApiException(ErrorCode.ENT_CHANGE_NON_ACTIVE, subscription.getId(),
                    currentState);
        }

        if (subscription.isSubscriptionFutureCancelled()) {
            throw new EntitlementUserApiException(ErrorCode.ENT_CHANGE_FUTURE_CANCELLED, subscription.getId());
        }
        PlanChangeResult planChangeResult = null;
        try {

            Product destProduct = catalogService.getCatalog().findProduct(productName);
            Plan currentPlan = subscription.getCurrentPlan();
            PlanPhaseSpecifier fromPlanPhase = new PlanPhaseSpecifier(currentPlan.getProduct().getName(),
                    currentPlan.getProduct().getCategory(), currentPlan.getBillingPeriod(), currentPriceList,
                    subscription.getCurrentPhase().getPhaseType());
            PlanSpecifier toPlanPhase = new PlanSpecifier(productName, destProduct.getCategory(), term,
                    priceList);

            planChangeResult = catalogService.getCatalog().planChange(fromPlanPhase, toPlanPhase);
        } catch (CatalogApiException e) {
            throw new EntitlementUserApiException(e);
        }

        ActionPolicy policy = planChangeResult.getPolicy();
        PriceList newPriceList = planChangeResult.getNewPriceList();

        Plan newPlan = catalogService.getCatalog().findPlan(productName, term, newPriceList.getName());
        DateTime effectiveDate = subscription.getPlanChangeEffectiveDate(policy, now);

        TimedPhase currentTimedPhase = planAligner.getCurrentTimedPhaseOnChange(subscription, newPlan,
                newPriceList.getName(), effectiveDate);

        EntitlementEvent changeEvent = new ApiEventChange(new ApiEventBuilder()
                .setSubscriptionId(subscription.getId()).setEventPlan(newPlan.getName())
                .setEventPlanPhase(currentTimedPhase.getPhase().getName())
                .setEventPriceList(newPriceList.getName()).setActiveVersion(subscription.getActiveVersion())
                .setProcessedDate(now).setEffectiveDate(effectiveDate).setRequestedDate(now));

        TimedPhase nextTimedPhase = planAligner.getNextTimedPhaseOnChange(subscription, newPlan,
                newPriceList.getName(), effectiveDate);
        PhaseEvent nextPhaseEvent = (nextTimedPhase != null) ? PhaseEventData.getNextPhaseEvent(
                nextTimedPhase.getPhase().getName(), subscription, now, nextTimedPhase.getStartPhase()) : null;
        List<EntitlementEvent> changeEvents = new ArrayList<EntitlementEvent>();
        // Only add the PHASE if it does not coincide with the CHANGE, if not this is 'just' a CHANGE.
        if (nextPhaseEvent != null
                && !nextPhaseEvent.getEffectiveDate().equals(changeEvent.getEffectiveDate())) {
            changeEvents.add(nextPhaseEvent);
        }
        changeEvents.add(changeEvent);
        dao.changePlan(subscription.getId(), changeEvents);
        subscription.rebuildTransitions(dao.getEventsForSubscription(subscription.getId()),
                catalogService.getCatalog());
    } catch (CatalogApiException e) {
        throw new EntitlementUserApiException(e);
    }
}

From source file:com.ning.billing.invoice.notification.DefaultNextBillingDatePoster.java

License:Apache License

@Override
public void insertNextBillingNotification(
        final EntitySqlDaoWrapperFactory<EntitySqlDao> entitySqlDaoWrapperFactory, final UUID accountId,
        final UUID subscriptionId, final DateTime futureNotificationTime, final UUID userToken) {
    final InternalCallContext context = createCallContext(accountId, userToken);

    final NotificationQueue nextBillingQueue;
    try {/*w  w w .  j a  va  2  s .  c o m*/
        nextBillingQueue = notificationQueueService.getNotificationQueue(
                DefaultInvoiceService.INVOICE_SERVICE_NAME,
                DefaultNextBillingDateNotifier.NEXT_BILLING_DATE_NOTIFIER_QUEUE);
        log.info("Queuing next billing date notification at {} for subscriptionId {}",
                futureNotificationTime.toString(), subscriptionId.toString());

        nextBillingQueue.recordFutureNotificationFromTransaction(entitySqlDaoWrapperFactory,
                futureNotificationTime, new NextBillingDateNotificationKey(subscriptionId), context);
    } catch (NoSuchNotificationQueue e) {
        log.error("Attempting to put items on a non-existent queue (NextBillingDateNotifier).", e);
    } catch (IOException e) {
        log.error("Failed to serialize notificationKey for subscriptionId {}", subscriptionId);
    }
}

From source file:com.ning.billing.jaxrs.KillbillClient.java

License:Apache License

protected InvoiceJsonSimple createDryRunInvoice(final String accountId, final DateTime futureDate)
        throws IOException {
    final String uri = JaxrsResource.INVOICES_PATH;

    final Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put(JaxrsResource.QUERY_ACCOUNT_ID, accountId);
    queryParams.put(JaxrsResource.QUERY_TARGET_DATE, futureDate.toString());
    queryParams.put(JaxrsResource.QUERY_DRY_RUN, "true");

    final Response response = doPost(uri, null, queryParams, DEFAULT_HTTP_TIMEOUT_SEC);
    Assert.assertEquals(response.getStatusCode(), Status.OK.getStatusCode());

    final String baseJson = response.getResponseBody();
    final InvoiceJsonSimple futureInvoice = mapper.readValue(baseJson, InvoiceJsonSimple.class);
    assertNotNull(futureInvoice);//from   w  w w.  ja  v  a2s.co  m

    return futureInvoice;
}

From source file:com.ning.billing.jaxrs.KillbillClient.java

License:Apache License

protected void createInvoice(final String accountId, final DateTime futureDate) throws IOException {
    final String uri = JaxrsResource.INVOICES_PATH;

    final Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put(JaxrsResource.QUERY_ACCOUNT_ID, accountId);
    queryParams.put(JaxrsResource.QUERY_TARGET_DATE, futureDate.toString());

    final Response response = doPost(uri, null, queryParams, DEFAULT_HTTP_TIMEOUT_SEC);
    Assert.assertEquals(response.getStatusCode(), Status.CREATED.getStatusCode());

    final String location = response.getHeader("Location");
    Assert.assertNotNull(location);/*from www  .ja  va 2s  . c o  m*/
}

From source file:com.ning.billing.ovedue.notification.DefaultOverdueCheckPoster.java

License:Apache License

@Override
public void insertOverdueCheckNotification(final Blockable overdueable, final DateTime futureNotificationTime,
        final InternalCallContext context) {
    final NotificationQueue checkOverdueQueue;
    try {/* www  . ja v  a  2  s  .  co m*/
        checkOverdueQueue = notificationQueueService.getNotificationQueue(
                DefaultOverdueService.OVERDUE_SERVICE_NAME,
                DefaultOverdueCheckNotifier.OVERDUE_CHECK_NOTIFIER_QUEUE);

        transactionalSqlDao.execute(new EntitySqlDaoTransactionWrapper<Void>() {
            @Override
            public Void inTransaction(final EntitySqlDaoWrapperFactory<EntitySqlDao> entitySqlDaoWrapperFactory)
                    throws Exception {
                boolean shouldInsertNewNotification = true;

                // Check if we already have notifications for that key
                final List<Notification> futureNotifications = getFutureNotificationsForAccountAndOverdueableInTransaction(
                        entitySqlDaoWrapperFactory, checkOverdueQueue, overdueable, context);
                if (futureNotifications.size() > 0) {
                    // Results are ordered by effective date asc
                    final DateTime earliestExistingNotificationDate = futureNotifications.get(0)
                            .getEffectiveDate();

                    final int minIndexToDeleteFrom;
                    if (earliestExistingNotificationDate.isBefore(futureNotificationTime)) {
                        // We don't have to insert a new one. For sanity, delete any other future notification
                        minIndexToDeleteFrom = 1;
                        shouldInsertNewNotification = false;
                    } else {
                        // We win - we are before any other already recorded. Delete all others.
                        minIndexToDeleteFrom = 0;
                    }

                    for (int i = minIndexToDeleteFrom; i < futureNotifications.size(); i++) {
                        checkOverdueQueue.removeNotificationFromTransaction(entitySqlDaoWrapperFactory,
                                futureNotifications.get(i).getId(), context);
                    }
                }

                if (shouldInsertNewNotification) {
                    log.info("Queuing overdue check notification. Overdueable id: {}, timestamp: {}",
                            overdueable.getId().toString(), futureNotificationTime.toString());
                    final OverdueCheckNotificationKey notificationKey = new OverdueCheckNotificationKey(
                            overdueable.getId(), Type.get(overdueable));
                    checkOverdueQueue.recordFutureNotificationFromTransaction(entitySqlDaoWrapperFactory,
                            futureNotificationTime, notificationKey, context);
                } else {
                    log.info("Skipping queuing overdue check notification. Overdueable id: {}, timestamp: {}",
                            overdueable.getId().toString(), futureNotificationTime.toString());
                }

                return null;
            }
        });
    } catch (NoSuchNotificationQueue e) {
        log.error("Attempting to put items on a non-existent queue (DefaultOverdueCheck).", e);
    }
}

From source file:com.ning.killbill.zuora.zuora.ZuoraApi.java

License:Apache License

public Either<ZuoraError, List<Invoice>> getInvoicesForAccount(final ZuoraConnection connection,
        final Account account, @Nullable final DateTime from, @Nullable final DateTime to) {
    // We need to round down the to, invoice date in Zuora is in the form 2011-09-29T00:00:00.000-08:00
    final String toDate = to == null ? ""
            : to.toLocalDate().toDateTimeAtStartOfDay(DateTimeZone.forID("Pacific/Pitcairn")).toString();

    final String query;
    if (from == null && to != null) {
        query = stringTemplateLoader.load("getPostedInvoicesForAccountTo").define("accountId", account.getId())
                .define("invoiceDateTo", toDate).build();
    } else if (from != null && to != null) {
        query = stringTemplateLoader.load("getPostedInvoicesForAccountFromTo")
                .define("accountId", account.getId()).define("invoiceDateTo", toDate)
                .define("invoiceDateFrom", from.toString()).build();
    } else {/*from ww  w  .jav  a 2 s .c  om*/
        throw new UnsupportedOperationException();
    }

    final Either<ZuoraError, List<Invoice>> invoicesOrError = connection.query(query);
    if (invoicesOrError.isLeft()) {
        return Either.left(invoicesOrError.getLeft());
    } else {
        return Either.right(invoicesOrError.getRight());
    }
}