Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2013 Ning, Inc.
   *
   * Ning licenses this file to you under the Apache License, version 2.0
   * (the "License"); you may not use this file except in compliance with the
   * License.  You may obtain a copy of the License at:
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  * License for the specific language governing permissions and limitations
  * under the License.
  */
 
 package com.ning.billing.subscription.api.timeline;
 
 import java.util.List;
 import java.util.Set;
 import java.util.UUID;
 
 import  javax.annotation.Nullable;
 
 
 
 
 
     private final RepairSubscriptionLifecycleDao repairDao;
     private final CatalogService catalogService;
     private final AddonUtils addonUtils;
 
 
     private enum RepairType {
         BASE_REPAIR,
         ADD_ON_REPAIR,
         STANDALONE_REPAIR
     }
 
     @Inject
     public DefaultSubscriptionBaseTimelineApi(final CatalogService catalogService,
                                               final SubscriptionBaseApiService apiService,
                                               @Named(.final RepairSubscriptionLifecycleDao repairDaofinal SubscriptionDao dao,
                                               @Named(.final SubscriptionBaseApiService repairApiService,
                                               final InternalCallContextFactory internalCallContextFactoryfinal Clock clockfinal AddonUtils addonUtils) {
         super(daoapiServiceclockcatalogService);
         this. = catalogService;
         this. = repairDao;
         this. = internalCallContextFactory;
         this. = repairApiService;
         this. = addonUtils;
     }
 
     @Override
     public BundleBaseTimeline getBundleTimeline(final SubscriptionBaseBundle bundlefinal TenantContext context)
             throws SubscriptionBaseRepairException {
         return getBundleTimelineInternal(bundlebundle.getExternalKey(), context);
     }
 
     @Override
     public BundleBaseTimeline getBundleTimeline(final UUID accountIdfinal String bundleNamefinal TenantContext context)
            throws SubscriptionBaseRepairException {
        final SubscriptionBaseBundle bundle = bundles.size() > 0 ? bundles.get(bundles.size() - 1) : null;
        return getBundleTimelineInternal(bundlebundleName + " [accountId= " + accountId.toString() + "]"context);
    }
    @Override
    public BundleBaseTimeline getBundleTimeline(final UUID bundleIdfinal TenantContext contextthrows SubscriptionBaseRepairException {
        return getBundleTimelineInternal(bundlebundleId.toString(), context);
    }
    private BundleBaseTimeline getBundleTimelineInternal(final SubscriptionBaseBundle bundlefinal String descBundlefinal TenantContext contextthrows SubscriptionBaseRepairException {
        try {
            if (bundle == null) {
                throw new SubscriptionBaseRepairException(.descBundle);
            }
            if (subscriptions.size() == 0) {
                throw new SubscriptionBaseRepairException(.bundle.getId());
            }
            final String viewId = getViewId(((DefaultSubscriptionBaseBundlebundle).getLastSysUpdateDate(), subscriptions);
            final List<SubscriptionBaseTimelinerepairs = createGetSubscriptionRepairList(subscriptions, Collections.<SubscriptionBaseTimeline>emptyList());
            return createGetBundleRepair(bundle.getId(), bundle.getExternalKey(), viewIdrepairs);
        } catch (CatalogApiException e) {
            throw new SubscriptionBaseRepairException(e);
        }
    }
        return new ArrayList<SubscriptionDataRepair>(Collections2.transform(inputnew Function<SubscriptionBaseSubscriptionDataRepair>() {
            @Override
            public SubscriptionDataRepair apply(@Nullable final SubscriptionBase subscription) {
                return convertToSubscriptionDataRepair((DefaultSubscriptionBasesubscription);
            }
        }));
    }
    }
    @Override
    public BundleBaseTimeline repairBundle(final BundleBaseTimeline inputfinal boolean dryRunfinal CallContext contextthrows SubscriptionBaseRepairException {
        final InternalTenantContext tenantContext = .createInternalTenantContext(context);
        try {
            final SubscriptionBaseBundle bundle = .getSubscriptionBundleFromId(input.getId(), tenantContext);
            if (bundle == null) {
                throw new SubscriptionBaseRepairException(.input.getId());
            }
            // Subscriptions are ordered with BASE subscription first-- if exists
            final List<SubscriptionDataRepairsubscriptions = convertToSubscriptionsDataRepair(.getSubscriptions(input.getId(), tenantContext));
            if (subscriptions.size() == 0) {
                throw new SubscriptionBaseRepairException(.input.getId());
            }
            final String viewId = getViewId(((DefaultSubscriptionBaseBundlebundle).getLastSysUpdateDate(), subscriptions);
            if (!viewId.equals(input.getViewId())) {
                throw new SubscriptionBaseRepairException(.input.getId(), input.getViewId(), viewId);
            }
            DateTime firstDeletedBPEventTime = null;
            DateTime lastRemainingBPEventTime = null;
            boolean isBasePlanRecreate = false;
            DateTime newBundleStartDate = null;
            SubscriptionDataRepair baseSubscriptionRepair = null;
            final List<SubscriptionDataRepairaddOnSubscriptionInRepair = new LinkedList<SubscriptionDataRepair>();
            final List<SubscriptionDataRepairinRepair = new LinkedList<SubscriptionDataRepair>();
            for (final SubscriptionBase cur : subscriptions) {
                final SubscriptionBaseTimeline curRepair = findAndCreateSubscriptionRepair(cur.getId(), input.getSubscriptions());
                if (curRepair != null) {
                    final SubscriptionDataRepair curInputRepair = ((SubscriptionDataRepaircur);
                    final List<SubscriptionBaseEventremaining = getRemainingEventsAndValidateDeletedEvents(curInputRepairfirstDeletedBPEventTimecurRepair.getDeletedEvents());
                    final boolean isPlanRecreate = (curRepair.getNewEvents().size() > 0
                                                    && (curRepair.getNewEvents().get(0).getSubscriptionTransitionType() == .
                                                        || curRepair.getNewEvents().get(0).getSubscriptionTransitionType() == .));
                    final DateTime newSubscriptionStartDate = isPlanRecreate ? curRepair.getNewEvents().get(0).getRequestedDate() : null;
                    if (isPlanRecreate && remaining.size() != 0) {
                        throw new SubscriptionBaseRepairException(.cur.getId(), cur.getBundleId());
                    }
                    if (!isPlanRecreate && remaining.size() == 0) {
                        throw new SubscriptionBaseRepairException(.cur.getId(), cur.getBundleId());
                    }
                    if (cur.getCategory() == .) {
                        final int bpTransitionSize = ((DefaultSubscriptionBasecur).getAllTransitions().size();
                        lastRemainingBPEventTime = (remaining.size() > 0) ? curInputRepair.getAllTransitions().get(remaining.size() - 1).getEffectiveTransitionTime() : null;
                        firstDeletedBPEventTime = (remaining.size() < bpTransitionSize) ? curInputRepair.getAllTransitions().get(remaining.size()).getEffectiveTransitionTime() : null;
                        isBasePlanRecreate = isPlanRecreate;
                        newBundleStartDate = newSubscriptionStartDate;
                    }
                    if (curRepair.getNewEvents().size() > 0) {
                        final DateTime lastRemainingEventTime = (remaining.size() == 0) ? null : curInputRepair.getAllTransitions().get(remaining.size() - 1).getEffectiveTransitionTime();
                        validateFirstNewEvent(curInputRepaircurRepair.getNewEvents().get(0), lastRemainingBPEventTimelastRemainingEventTime);
                    }
                    final SubscriptionDataRepair curOutputRepair = createSubscriptionDataRepair(curInputRepairnewBundleStartDatenewSubscriptionStartDateremaining);
                    .initializeRepair(curInputRepair.getId(), remainingtenantContext);
                    inRepair.add(curOutputRepair);
                    if (curOutputRepair.getCategory() == .) {
                        // Check if ADD_ON RE_CREATE is before BP start
                        if (isPlanRecreate && (subscriptions.get(0)).getStartDate().isAfter(curRepair.getNewEvents().get(0).getRequestedDate())) {
                            throw new SubscriptionBaseRepairException(.cur.getId(), cur.getBundleId());
                        }
                        addOnSubscriptionInRepair.add(curOutputRepair);
                    } else if (curOutputRepair.getCategory() == .) {
                        baseSubscriptionRepair = curOutputRepair;
                    }
                }
            }
            final RepairType repairType = getRepairType(subscriptions.get(0), (baseSubscriptionRepair != null));
            switch (repairType) {
                case :
                    // We need to add any existing addon that are not in the input repair list
                    for (final SubscriptionBase cur : subscriptions) {
                        if (cur.getCategory() == . && !inRepair.contains(cur)) {
                            final SubscriptionDataRepair curOutputRepair = createSubscriptionDataRepair((SubscriptionDataRepaircurnewBundleStartDatenull, ((SubscriptionDataRepaircur).getEvents());
                            .initializeRepair(curOutputRepair.getId(), ((SubscriptionDataRepaircur).getEvents(), tenantContext);
                            inRepair.add(curOutputRepair);
                            addOnSubscriptionInRepair.add(curOutputRepair);
                        }
                    }
                    break;
                case :
                    // We need to set the baseSubscription as it is useful to calculate addon validity
                    final SubscriptionDataRepair baseSubscription = (SubscriptionDataRepairsubscriptions.get(0);
                    baseSubscriptionRepair = createSubscriptionDataRepair(baseSubscriptionbaseSubscription.getBundleStartDate(), baseSubscription.getAlignStartDate(), baseSubscription.getEvents());
                    break;
                case :
                default:
                    break;
            }
            validateBasePlanRecreate(isBasePlanRecreatesubscriptionsinput.getSubscriptions());
            validateInputSubscriptionsKnown(subscriptionsinput.getSubscriptions());
            final Collection<NewEventnewEvents = createOrderedNewEventInput(input.getSubscriptions());
            for (final NewEvent newEvent : newEvents) {
                final DefaultNewEvent cur = (DefaultNewEventnewEvent;
                final SubscriptionDataRepair curDataRepair = findSubscriptionDataRepair(cur.getSubscriptionId(), inRepair);
                if (curDataRepair == null) {
                    throw new SubscriptionBaseRepairException(.cur.getSubscriptionId());
                }
                curDataRepair.addNewRepairEvent(curbaseSubscriptionRepairaddOnSubscriptionInRepaircontext);
            }
            if (dryRun) {
                baseSubscriptionRepair.addFutureAddonCancellation(addOnSubscriptionInRepaircontext);
                final List<SubscriptionBaseTimelinerepairs = createGetSubscriptionRepairList(subscriptionsconvertDataRepair(inRepair));
                return createGetBundleRepair(input.getId(), bundle.getExternalKey(), input.getViewId(), repairs);
            } else {
                .repair(bundle.getAccountId(), input.getId(), inRepair.createInternalCallContext(bundle.getAccountId(), context));
                return getBundleTimeline(input.getId(), context);
            }
        } catch (CatalogApiException e) {
            throw new SubscriptionBaseRepairException(e);
        } finally {
            .cleanup(tenantContext);
        }
    }
    private RepairType getRepairType(final SubscriptionBase firstSubscriptionfinal boolean gotBaseSubscription) {
        if (firstSubscription.getCategory() == .) {
            return gotBaseSubscription ? . : .;
        } else {
            return .;
        }
    }
    private void validateBasePlanRecreate(final boolean isBasePlanRecreatefinal List<SubscriptionDataRepairsubscriptionsfinal List<SubscriptionBaseTimelineinput)
            throws SubscriptionBaseRepairException {
        if (!isBasePlanRecreate) {
            return;
        }
        if (subscriptions.size() != input.size()) {
            throw new SubscriptionBaseRepairException(.subscriptions.get(0).getBundleId());
        }
        for (final SubscriptionBaseTimeline cur : input) {
            if (cur.getNewEvents().size() != 0
                && (cur.getNewEvents().get(0).getSubscriptionTransitionType() != .
                    && cur.getNewEvents().get(0).getSubscriptionTransitionType() != .)) {
                throw new SubscriptionBaseRepairException(.subscriptions.get(0).getBundleId());
            }
        }
    }
    private void validateInputSubscriptionsKnown(final List<SubscriptionDataRepairsubscriptionsfinal List<SubscriptionBaseTimelineinput)
            throws SubscriptionBaseRepairException {
        for (final SubscriptionBaseTimeline cur : input) {
            boolean found = false;
            for (final SubscriptionBase s : subscriptions) {
                if (s.getId().equals(cur.getId())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new SubscriptionBaseRepairException(.cur.getId());
            }
        }
    }
    private void validateFirstNewEvent(final DefaultSubscriptionBase datafinal NewEvent firstNewEventfinal DateTime lastBPRemainingTimefinal DateTime lastRemainingTime)
            throws SubscriptionBaseRepairException {
        if (lastBPRemainingTime != null &&
            firstNewEvent.getRequestedDate().isBefore(lastBPRemainingTime)) {
        }
        if (lastRemainingTime != null &&
            firstNewEvent.getRequestedDate().isBefore(lastRemainingTime)) {
        }
    }
    private Collection<NewEventcreateOrderedNewEventInput(final List<SubscriptionBaseTimelinesubscriptionsReapir) {
        final TreeSet<NewEventnewEventSet = new TreeSet<SubscriptionBaseTimeline.NewEvent>(new Comparator<NewEvent>() {
            @Override
            public int compare(final NewEvent o1final NewEvent o2) {
                return o1.getRequestedDate().compareTo(o2.getRequestedDate());
            }
        });
        for (final SubscriptionBaseTimeline cur : subscriptionsReapir) {
            for (final NewEvent e : cur.getNewEvents()) {
                newEventSet.add(new DefaultNewEvent(cur.getId(), e.getPlanPhaseSpecifier(), e.getRequestedDate(), e.getSubscriptionTransitionType()));
            }
        }
        return newEventSet;
    }
                                                                              final List<SubscriptionBaseTimeline.DeletedEventdeletedEvents)
            throws SubscriptionBaseRepairException {
        if (deletedEvents == null || deletedEvents.size() == 0) {
            return data.getEvents();
        }
        int nbDeleted = 0;
        final LinkedList<SubscriptionBaseEventresult = new LinkedList<SubscriptionBaseEvent>();
        for (final SubscriptionBaseEvent cur : data.getEvents()) {
            boolean foundDeletedEvent = false;
            for (final SubscriptionBaseTimeline.DeletedEvent d : deletedEvents) {
                if (cur.getId().equals(d.getEventId())) {
                    foundDeletedEvent = true;
                    nbDeleted++;
                    break;
                }
            }
            if (!foundDeletedEvent && nbDeleted > 0) {
                throw new SubscriptionBaseRepairException(.cur.getId(), data.getId());
            }
            if (firstBPDeletedTime != null &&
                !cur.getEffectiveDate().isBefore(firstBPDeletedTime) &&
                !foundDeletedEvent) {
                throw new SubscriptionBaseRepairException(.cur.getId(), data.getId());
            }
            if (nbDeleted == 0) {
                result.add(cur);
            }
        }
        if (nbDeleted != deletedEvents.size()) {
            for (final SubscriptionBaseTimeline.DeletedEvent d : deletedEvents) {
                boolean found = false;
                for (final SubscriptionBaseTransition cur : data.getAllTransitions()) {
                    if (((SubscriptionBaseTransitionDatacur).getId().equals(d.getEventId())) {
                        found = true;
                    }
                }
                if (!found) {
                    throw new SubscriptionBaseRepairException(.d.getEventId(), data.getId());
                }
            }
        }
        return result;
    }
    private String getViewId(final DateTime lastUpdateBundleDatefinal List<SubscriptionDataRepairsubscriptions) {
        final StringBuilder tmp = new StringBuilder();
        long lastOrderedId = -1;
        for (final SubscriptionBase cur : subscriptions) {
            lastOrderedId = lastOrderedId < ((DefaultSubscriptionBasecur).getLastEventOrderedId() ? ((DefaultSubscriptionBasecur).getLastEventOrderedId() : lastOrderedId;
        }
        tmp.append(lastOrderedId);
        tmp.append("-");
        tmp.append(lastUpdateBundleDate.toDate().getTime());
        return tmp.toString();
    }
    private BundleBaseTimeline createGetBundleRepair(final UUID bundleIdfinal String externalKeyfinal String viewIdfinal List<SubscriptionBaseTimelinerepairList) {
        return new BundleBaseTimeline() {
            @Override
            public String getViewId() {
                return viewId;
            }
            @Override
            public List<SubscriptionBaseTimelinegetSubscriptions() {
                return repairList;
            }
            @Override
            public UUID getId() {
                return bundleId;
            }
            @Override
            public DateTime getCreatedDate() {
                throw new UnsupportedOperationException();
            }
            @Override
            public DateTime getUpdatedDate() {
                throw new UnsupportedOperationException();
            }
            @Override
            public String getExternalKey() {
                return externalKey;
            }
        };
    }
        final List<SubscriptionBaseTimelineresult = new LinkedList<SubscriptionBaseTimeline>();
        final Set<UUIDrepairIds = new TreeSet<UUID>();
        for (final SubscriptionBaseTimeline cur : inRepair) {
            repairIds.add(cur.getId());
            result.add(cur);
        }
        for (final SubscriptionBase cur : subscriptions) {
            if (!repairIds.contains(cur.getId())) {
                result.add(new DefaultSubscriptionBaseTimeline((SubscriptionDataRepaircur.getFullCatalog()));
            }
        }
        return result;
    }
        final List<SubscriptionBaseTimelineresult = new LinkedList<SubscriptionBaseTimeline>();
        for (final SubscriptionDataRepair cur : input) {
            result.add(new DefaultSubscriptionBaseTimeline(cur.getFullCatalog()));
        }
        return result;
    }
    private SubscriptionDataRepair findSubscriptionDataRepair(final UUID targetIdfinal List<SubscriptionDataRepairinput) {
        for (final SubscriptionDataRepair cur : input) {
            if (cur.getId().equals(targetId)) {
                return cur;
            }
        }
        return null;
    }
    private SubscriptionDataRepair createSubscriptionDataRepair(final DefaultSubscriptionBase curDatafinal DateTime newBundleStartDatefinal DateTime newSubscriptionStartDatefinal List<SubscriptionBaseEventinitialEvents) {
        final SubscriptionBuilder builder = new SubscriptionBuilder(curData);
        builder.setActiveVersion(curData.getActiveVersion() + 1);
        if (newBundleStartDate != null) {
            builder.setBundleStartDate(newBundleStartDate);
        }
        if (newSubscriptionStartDate != null) {
            builder.setAlignStartDate(newSubscriptionStartDate);
        }
        if (initialEvents.size() > 0) {
            for (final SubscriptionBaseEvent cur : initialEvents) {
                cur.setActiveVersion(builder.getActiveVersion());
            }
        }
        final SubscriptionDataRepair subscriptiondataRepair = new SubscriptionDataRepair(buildercurData.getEvents(), , (SubscriptionDao);
        subscriptiondataRepair.rebuildTransitions(curData.getEvents(), .getFullCatalog());
        return subscriptiondataRepair;
    }
        for (final SubscriptionBaseTimeline cur : input) {
            if (target.equals(cur.getId())) {
                return new DefaultSubscriptionBaseTimeline(cur);
            }
        }
        return null;
    }
New to GrepCode? Check out our FAQ X