Example usage for com.amazonaws.services.simpledb.model ReplaceableAttribute setName

List of usage examples for com.amazonaws.services.simpledb.model ReplaceableAttribute setName

Introduction

In this page you can find the example usage for com.amazonaws.services.simpledb.model ReplaceableAttribute setName.

Prototype


public void setName(String name) 

Source Link

Document

The name of the replaceable attribute.

Usage

From source file:org.teiid.resource.adapter.simpledb.SimpleDBConnectionImpl.java

License:Open Source License

private void addAttribute(String name, Object value, List<ReplaceableAttribute> attributes) {
    if (value.getClass().isArray()) {
        String[] values = (String[]) value;
        for (int i = 0; i < values.length; i++) {
            addAttribute(name, values[i], attributes);
        }/* w  ww.  j ava 2 s.  c om*/
    } else {
        ReplaceableAttribute attribute = new ReplaceableAttribute();
        attribute.setName(name);
        attribute.setReplace(true);
        attribute.setValue((String) value);
        attributes.add(attribute);
    }
}

From source file:org.teiid.resource.adpter.simpledb.SimpleDbAPIClass.java

License:Open Source License

private List<ReplaceableAttribute> createMultivaluedAttribute(Map.Entry<String, String> column) {
    List<ReplaceableAttribute> attributes = new ArrayList<ReplaceableAttribute>();
    String trimmedAttributes = column.getValue().substring(1, column.getValue().length() - 1);
    Pattern p = Pattern.compile("[^\\\\];"); //$NON-NLS-1$
    Matcher match = p.matcher(trimmedAttributes);
    int lastMatch = 0;
    while (match.find()) {
        ReplaceableAttribute attribute = new ReplaceableAttribute();
        attribute.setName(column.getKey());
        String value = trimmedAttributes.substring(lastMatch, match.start() + 1);
        attribute.setValue(value.replaceAll("\\;", ";")); //$NON-NLS-1$ //$NON-NLS-2$
        lastMatch = match.end();/*w ww  .j  ava2  s  .c om*/
        attribute.setReplace(false);
        attributes.add(attribute);
    }
    ReplaceableAttribute attribute = new ReplaceableAttribute();
    attribute.setName(column.getKey());
    String value = trimmedAttributes.substring(lastMatch, trimmedAttributes.length());
    attribute.setValue(value.replaceAll("\\\\;", ";")); //$NON-NLS-1$ //$NON-NLS-2$
    attribute.setReplace(false);
    attributes.add(attribute);
    return attributes;
}

From source file:squash.booking.lambdas.core.BookingManager.java

License:Apache License

@Override
public List<Booking> createBooking(Booking bookingToCreate, boolean isSquashServiceUserCall) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The booking manager has not been initialised");
    }/*from  w w  w. j av a2s  .c om*/

    getLifecycleManager().throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    logger.log("About to create booking in database: " + bookingToCreate);

    // Get today's bookings (and version number), via consistent read:
    String itemName = bookingToCreate.getDate();

    // We retry the creation of the booking if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies
    // the database between us reading and writing it.
    return RetryHelper.DoWithRetries(() -> {
        ImmutablePair<Optional<Integer>, List<Booking>> versionedBookings = getVersionedBookings(itemName);

        // Check that the court(s) we're booking is/are currently free
        // Get individual booked courts as (court, slot) pairs
        Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>();
        versionedBookings.right.forEach((booking) -> {
            addBookingToSet(booking, bookedCourts);
        });

        // Get courts we're trying to book as (court, slot) pairs
        Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>();
        addBookingToSet(bookingToCreate, courtsToBook);

        // Does the new booking clash with existing bookings?
        boolean bookingClashes = Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0);

        if (bookingClashes) {
            // Case of trying to book an already-booked slot - this
            // probably means either:
            // - more than one person was trying to book the slot at once,
            // or
            // - not all courts in our block booking are free
            logger.log(
                    "Cannot book courts which are already booked, so throwing a 'Booking creation failed' exception");
            throw new Exception("Booking creation failed");
        }

        logger.log("Required courts are currently free - so proceeding to make booking");

        // Do a conditional put - so we don't overwrite someone else's
        // booking
        String attributeName = getAttributeNameFromBooking(bookingToCreate);
        String attributeValue = bookingToCreate.getName();
        logger.log("ItemName: " + itemName);
        logger.log("AttributeName: " + attributeName);
        logger.log("AttributeValue: " + attributeValue);
        ReplaceableAttribute bookingAttribute = new ReplaceableAttribute();
        bookingAttribute.setName(attributeName);
        bookingAttribute.setValue(attributeValue);

        getOptimisticPersister().put(itemName, versionedBookings.left, bookingAttribute);
        logger.log("Created booking in database");
        // Add the booking we've just made to the pre-existing ones.
        List<Booking> bookings = versionedBookings.right;
        bookings.add(bookingToCreate);
        return bookings;
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.booking.lambdas.core.LifecycleManager.java

License:Apache License

@Override
public void setLifecycleState(LifecycleState lifecycleState, Optional<String> newServiceUrl) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The lifecycle manager has not been initialised");
    }//from   ww  w .  j  a va  2 s . c  o m

    if (lifecycleState.equals(LifecycleState.RETIRED)) {
        String message = null;
        if (!newServiceUrl.isPresent() || !newServiceUrl.get().startsWith("http")) {
            if (!newServiceUrl.isPresent()) {
                message = "Throwing exception as url to new service has not been provided when setting lifecycle state to RETIRED";
            } else if (!newServiceUrl.get().startsWith("http")) {
                // Insist on correct format for the forwarding url.
                message = "Throwing exception as url to new service when setting lifecycle state to RETIRED does not start with http";
            }
            logger.log(message);
            throw new Exception(
                    "Must provide valid url to new service when setting lifecycle state to RETIRED");
        }
    }

    // Get attribute - so can set version correctly. We assume only one person
    // (i.e. the site admin) will ever be calling this at one time, but we
    // nevertheless supply the version - so we can use the optimistic persister.
    ImmutablePair<Optional<Integer>, Set<Attribute>> lifecycleStateItem = getOptimisticPersister()
            .get(lifecycleItemName);

    logger.log("About to set lifecycle state in database to: " + lifecycleState.name());
    ReplaceableAttribute lifecycleAttribute = new ReplaceableAttribute();
    lifecycleAttribute.setName("State");
    lifecycleAttribute.setValue(lifecycleState.name());
    lifecycleAttribute.setReplace(true);
    int newVersion = getOptimisticPersister().put(lifecycleItemName, lifecycleStateItem.left,
            lifecycleAttribute);
    logger.log("Updated lifecycle state in database to: " + lifecycleState.name());

    if (newServiceUrl.isPresent()) {
        logger.log("About to set lifecycle state url in database to: " + newServiceUrl.get());
        ReplaceableAttribute urlAttribute = new ReplaceableAttribute();
        urlAttribute.setName("Url");
        urlAttribute.setValue(newServiceUrl.get());
        urlAttribute.setReplace(true);
        getOptimisticPersister().put(lifecycleItemName, Optional.of(newVersion), urlAttribute);
        logger.log("Updated lifecycle state url in database to: " + newServiceUrl.get());
    }
}

From source file:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public int put(String itemName, Optional<Integer> version, ReplaceableAttribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }/* w  ww.ja  va2 s. c o  m*/

    logger.log("About to add attrbutes to simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // Check the put will not take us over the maximum number of attributes:
    // N.B. if (replace == true) then this check could be over-eager, but not
    // worth refining it, since this effectively just alters the limit by one.
    ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

    if (versionedAttributes.left.isPresent()) {
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ")  have version number: " + versionedAttributes.left.get());
    } else {
        // There should be no attributes in this case.
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ") have no version number");
    }

    Boolean tooManyAttributes = versionedAttributes.right.size() >= maxNumberOfAttributes;
    if (tooManyAttributes && !attribute.getValue().startsWith("Inactive")) {
        // We allow puts to inactivate attributes even when on the limit -
        // otherwise we could never delete when we're on the limit.
        logger.log("Cannot create attribute - the maximum number of attributes already exists ("
                + maxNumberOfAttributes
                + ") so throwing a 'Database put failed - too many attributes' exception");
        throw new Exception("Database put failed - too many attributes");
    }

    // Do a conditional put - so we don't overwrite someone else's attributes
    UpdateCondition updateCondition = new UpdateCondition();
    updateCondition.setName(versionAttributeName);
    ReplaceableAttribute versionAttribute = new ReplaceableAttribute();
    versionAttribute.setName(versionAttributeName);
    versionAttribute.setReplace(true);
    // Update will proceed unless the version number has changed
    if (version.isPresent()) {
        // A version number attribute exists - so it should be unchanged
        updateCondition.setValue(Integer.toString(version.get()));
        // Bump up our version number attribute
        versionAttribute.setValue(Integer.toString(version.get() + 1));
    } else {
        // A version number attribute did not exist - so it still should not
        updateCondition.setExists(false);
        // Set initial value for our version number attribute
        versionAttribute.setValue("0");
    }

    List<ReplaceableAttribute> replaceableAttributes = new ArrayList<>();
    replaceableAttributes.add(versionAttribute);

    // Add the new attribute
    replaceableAttributes.add(attribute);

    PutAttributesRequest simpleDBPutRequest = new PutAttributesRequest(simpleDbDomainName, itemName,
            replaceableAttributes, updateCondition);

    try {
        client.putAttributes(simpleDBPutRequest);
    } catch (AmazonServiceException ase) {
        if (ase.getErrorCode().contains("ConditionalCheckFailed")) {
            // Someone else has mutated an attribute since we read them. This is
            // likely to be rare, and a retry should almost always succeed. However,
            // we leave it to clients of this class to retry the call if they wish,
            // as the new mutation may mean they no longer want to do the put.
            logger.log("Caught AmazonServiceException for ConditionalCheckFailed whilst creating"
                    + " attribute(s) so throwing as 'Database put failed' instead");
            throw new Exception("Database put failed - conditional check failed");
        }
        throw ase;
    }

    logger.log("Created attribute(s) in simpledb");

    return Integer.parseInt(versionAttribute.getValue());
}

From source file:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public void delete(String itemName, Attribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }//from   w  ww. ja  va  2s  .  com

    logger.log("About to delete attribute from simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // We retry the delete if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies the
    // database between us reading and writing it.
    RetryHelper.DoWithRetries(() -> {
        try {
            // Get existing attributes (and version number), via consistent
            // read:
            ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

            if (!versionedAttributes.left.isPresent()) {
                logger.log(
                        "A version number attribute did not exist - this means no attributes exist, so we have nothing to delete.");
                return null;
            }
            if (!versionedAttributes.right.contains(attribute)) {
                logger.log("The attribute did not exist - so we have nothing to delete.");
                return null;
            }

            // Since it seems impossible to update the version number while
            // deleting an attribute, we first mark the attribute as inactive,
            // and then delete it.
            ReplaceableAttribute inactiveAttribute = new ReplaceableAttribute();
            inactiveAttribute.setName(attribute.getName());
            inactiveAttribute.setValue("Inactive" + attribute.getValue());
            inactiveAttribute.setReplace(true);
            put(itemName, versionedAttributes.left, inactiveAttribute);

            // Now we can safely delete the attribute, as other readers will now
            // ignore it.
            UpdateCondition updateCondition = new UpdateCondition();
            updateCondition.setName(inactiveAttribute.getName());
            updateCondition.setValue(inactiveAttribute.getValue());
            // Update will proceed unless the attribute no longer exists
            updateCondition.setExists(true);

            Attribute attributeToDelete = new Attribute();
            attributeToDelete.setName(inactiveAttribute.getName());
            attributeToDelete.setValue(inactiveAttribute.getValue());
            List<Attribute> attributesToDelete = new ArrayList<>();
            attributesToDelete.add(attributeToDelete);
            DeleteAttributesRequest simpleDBDeleteRequest = new DeleteAttributesRequest(simpleDbDomainName,
                    itemName, attributesToDelete, updateCondition);
            client.deleteAttributes(simpleDBDeleteRequest);
            logger.log("Deleted attribute from simpledb");
            return null;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().contains("AttributeDoesNotExist")) {
                // Case of trying to delete an attribute that no longer exists -
                // that's ok - it probably just means more than one person was
                // trying to delete the attribute at once. So swallow this
                // exception
                logger.log(
                        "Caught AmazonServiceException for AttributeDoesNotExist whilst deleting attribute so"
                                + " swallowing and continuing");
                return null;
            } else {
                throw ase;
            }
        }
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.booking.lambdas.core.RuleManager.java

License:Apache License

@Override
public Set<BookingRule> createRule(BookingRule bookingRuleToCreate, boolean isSquashServiceUserCall)
        throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The rule manager has not been initialised");
    }//from   w  w  w .ja v a  2  s .c o m

    lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    // We retry the put of the rule if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies the
    // database between us reading and writing it.
    return RetryHelper.DoWithRetries(() -> {
        Set<BookingRule> bookingRules = null;

        // Check that non-recurring rule is not for a date in the past.
        if (!bookingRuleToCreate.getIsRecurring()) {
            if ((new SimpleDateFormat("yyyy-MM-dd")).parse(bookingRuleToCreate.getBooking().getDate())
                    .before(new SimpleDateFormat("yyyy-MM-dd")
                            .parse(getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) {
                logger.log(
                        "Cannot add non-recurring booking rule for a date in the past, so throwing a 'Booking rule creation failed' exception");
                throw new Exception("Booking rule creation failed");
            }
        }

        // We should POST or DELETE to the BookingRuleExclusion resource,
        // with a BookingRule, and an exclusion date. This will call through
        // to the addBookingRuleExclusion or deleteBookingRuleExclusion
        // methods on this manager.
        logger.log("About to create booking rule in simpledb: " + bookingRuleToCreate);
        ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
        bookingRules = versionedBookingRules.right;

        // Check that the rule we're creating does not clash with an
        // existing rule.
        if (doesRuleClash(bookingRuleToCreate, bookingRules)) {
            logger.log(
                    "Cannot create rule as it clashes with existing rule, so throwing a 'Booking rule creation failed - rule would clash' exception");
            throw new Exception("Booking rule creation failed - rule would clash");
        }

        logger.log("The new rule does not clash with existing rules - so proceeding to create rule");

        String attributeName = getAttributeNameFromBookingRule(bookingRuleToCreate);
        String attributeValue = "";
        if (bookingRuleToCreate.getDatesToExclude().length > 0) {
            attributeValue = StringUtils.join(bookingRuleToCreate.getDatesToExclude(), ",");
        }
        logger.log("ItemName: " + ruleItemName);
        logger.log("AttributeName: " + attributeName);
        logger.log("AttributeValue: " + attributeValue);
        ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
        bookingRuleAttribute.setName(attributeName);
        bookingRuleAttribute.setValue(attributeValue);

        optimisticPersister.put(ruleItemName, versionedBookingRules.left, bookingRuleAttribute);
        bookingRules.add(bookingRuleToCreate);
        return bookingRules;
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.booking.lambdas.core.RuleManager.java

License:Apache License

@Override
public Optional<BookingRule> addRuleExclusion(String dateToExclude, BookingRule bookingRuleToAddExclusionTo,
        boolean isSquashServiceUserCall) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The rule manager has not been initialised");
    }/*from  ww w.j  av  a2 s  .co m*/

    lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    logger.log("About to add exclusion for " + dateToExclude + " to booking rule: "
            + bookingRuleToAddExclusionTo.toString());

    // We retry the addition of the exclusion if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies
    // the database between us reading and writing it.
    return RetryHelper.DoWithRetries((ThrowingSupplier<Optional<BookingRule>>) (() -> {
        ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
        Set<BookingRule> existingBookingRules = versionedBookingRules.right;

        // Check the BookingRule we're adding the exclusion to still
        // exists
        Optional<BookingRule> existingRule = existingBookingRules.stream()
                .filter(rule -> rule.equals(bookingRuleToAddExclusionTo)).findFirst();
        if (!existingRule.isPresent()) {
            logger.log("Trying to add an exclusion to a booking rule that does not exist.");
            throw new Exception("Booking rule exclusion addition failed");
        }

        // Check rule is recurring - we cannot add exclusions to
        // non-recurring rules
        if (!existingRule.get().getIsRecurring()) {
            logger.log("Trying to add an exclusion to a non-recurring booking rule.");
            throw new Exception("Booking rule exclusion addition failed");
        }

        // Check that the rule exclusion we're creating does not exist
        // already.
        if (ArrayUtils.contains(existingRule.get().getDatesToExclude(), dateToExclude)) {
            logger.log("An identical booking rule exclusion exists already - so quitting early");
            return Optional.empty();
        }

        // Check the exclusion is for the right day of the week.
        DayOfWeek dayToExclude = dayOfWeekFromDate(dateToExclude);
        DayOfWeek dayOfBookingRule = dayOfWeekFromDate(existingRule.get().getBooking().getDate());
        if (!dayToExclude.equals(dayOfBookingRule)) {
            logger.log("Exclusion being added and target booking rule are for different days of the week.");
            throw new Exception("Booking rule exclusion addition failed");
        }

        // Check it is not in the past, relative to now, or to the
        // Booking rule start date.
        Date bookingRuleStartDate = new SimpleDateFormat("yyyy-MM-dd")
                .parse(existingRule.get().getBooking().getDate());
        Date excludedDate = new SimpleDateFormat("yyyy-MM-dd").parse(dateToExclude);
        if (excludedDate.before(bookingRuleStartDate)) {
            logger.log("Exclusion being added is before target booking rule start date.");
            throw new Exception("Booking rule exclusion addition failed");
        }
        if (excludedDate.before(new SimpleDateFormat("yyyy-MM-dd")
                .parse(getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) {
            logger.log("Exclusion being added is in the past.");
            throw new Exception("Booking rule exclusion addition failed");
        }

        // Check we'll not exceed the maximum number of dates to exclude
        // (this limit is here as SimpleDB has a 1024-byte limit for
        // attribute
        // values).
        Set<String> datesToExclude = Sets.newHashSet(bookingRuleToAddExclusionTo.getDatesToExclude());
        if (datesToExclude.size() >= maxNumberOfDatesToExclude) {
            logger.log("The maximum number of booking rule exclusions(" + maxNumberOfDatesToExclude
                    + ") exists already.");
            throw new Exception("Booking rule exclusion addition failed - too many exclusions");
        }

        logger.log("Proceeding to add the new rule exclusion");
        datesToExclude.add(dateToExclude);
        String attributeName = getAttributeNameFromBookingRule(bookingRuleToAddExclusionTo);
        String attributeValue = StringUtils.join(datesToExclude, ",");
        logger.log("ItemName: " + ruleItemName);
        logger.log("AttributeName: " + attributeName);
        logger.log("AttributeValue: " + attributeValue);
        ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
        bookingRuleAttribute.setName(attributeName);
        bookingRuleAttribute.setValue(attributeValue);
        bookingRuleAttribute.setReplace(true);

        optimisticPersister.put(ruleItemName, versionedBookingRules.left, bookingRuleAttribute);
        BookingRule updatedBookingRule = new BookingRule(bookingRuleToAddExclusionTo);
        updatedBookingRule.setDatesToExclude(datesToExclude.toArray(new String[datesToExclude.size()]));
        logger.log("Added new rule exclusion");
        return Optional.of(updatedBookingRule);
    }), Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.booking.lambdas.core.RuleManager.java

License:Apache License

@Override
public Optional<BookingRule> deleteRuleExclusion(String dateNotToExclude,
        BookingRule bookingRuleToDeleteExclusionFrom, boolean isSquashServiceUserCall) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The rule manager has not been initialised");
    }/*from ww w.ja va  2  s  .  c om*/

    lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall);

    logger.log("About to delete exclusion for " + dateNotToExclude + " from booking rule: "
            + bookingRuleToDeleteExclusionFrom.toString());

    // We retry the deletion of the exclusion if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies
    // the database between us reading and writing it.
    return RetryHelper.DoWithRetries((ThrowingSupplier<Optional<BookingRule>>) (() -> {
        ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
        Set<BookingRule> existingBookingRules = versionedBookingRules.right;

        // Check the BookingRule we're deleting the exclusion from still
        // exists
        Optional<BookingRule> existingRule = existingBookingRules.stream()
                .filter(rule -> rule.equals(bookingRuleToDeleteExclusionFrom)).findFirst();
        if (!existingRule.isPresent()) {
            logger.log(
                    "Trying to delete an exclusion from a booking rule that does not exist, so swallowing and continuing");
            return Optional.empty();
        }

        // Check that the rule exclusion we're deleting still exists.
        if (!Arrays.asList(existingRule.get().getDatesToExclude()).contains(dateNotToExclude)) {
            logger.log("The booking rule exclusion being deleted no longer exists - so quitting early");
            return Optional.empty();
        }

        // Check deleting this exclusion does not cause a latent rule
        // clash to manifest. Do by pretending to add this rule again.
        existingBookingRules.remove(existingRule.get());
        Set<String> datesToExclude = Sets.newHashSet(bookingRuleToDeleteExclusionFrom.getDatesToExclude());
        datesToExclude.remove(dateNotToExclude);
        existingRule.get().setDatesToExclude(datesToExclude.toArray(new String[datesToExclude.size()]));
        if (doesRuleClash(existingRule.get(), existingBookingRules)) {
            logger.log("Cannot delete booking rule exclusion as remaining rules would then clash");
            throw new Exception("Booking rule exclusion deletion failed - latent clash exists");
        }

        logger.log("Proceeding to delete the rule exclusion");
        String attributeName = getAttributeNameFromBookingRule(bookingRuleToDeleteExclusionFrom);
        String attributeValue = StringUtils.join(datesToExclude, ",");
        logger.log("ItemName: " + ruleItemName);
        logger.log("AttributeName: " + attributeName);
        logger.log("AttributeValue: " + attributeValue);
        ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
        bookingRuleAttribute.setName(attributeName);
        bookingRuleAttribute.setValue(attributeValue);
        bookingRuleAttribute.setReplace(true);

        optimisticPersister.put(ruleItemName, versionedBookingRules.left, bookingRuleAttribute);
        BookingRule updatedBookingRule = new BookingRule(bookingRuleToDeleteExclusionFrom);
        updatedBookingRule.setDatesToExclude(datesToExclude.toArray(new String[datesToExclude.size()]));
        logger.log("Deleted rule exclusion");
        return Optional.of(updatedBookingRule);
    }), Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:squash.booking.lambdas.core.RuleManager.java

License:Apache License

private void purgeExpiredRulesAndRuleExclusions() throws Exception {
    ImmutablePair<Optional<Integer>, Set<BookingRule>> versionedBookingRules = getVersionedBookingRules();
    Set<BookingRule> existingBookingRules = versionedBookingRules.right;

    Optional<Integer> versionNumber = versionedBookingRules.left;
    String todayFormatted = getCurrentLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    Date today = (new SimpleDateFormat("yyyy-MM-dd").parse(todayFormatted));
    logger.log("Purging all rules and exclusions that expired before: " + todayFormatted);
    for (BookingRule bookingRule : existingBookingRules) {
        if (!bookingRule.getIsRecurring()
                && (new SimpleDateFormat("yyyy-MM-dd").parse(bookingRule.getBooking().getDate()))
                        .before(today)) {
            logger.log("Deleting non-recurring booking rule as it has expired: " + bookingRule.toString());
            try {
                deleteRule(bookingRule, false);
                logger.log("Deleted expired booking rule");
            } catch (Exception exception) {
                // Don't want to abort here if we fail to remove a rule - after all
                // we'll get another shot at it in 24 hours time.
                logger.log("Exception caught deleting expired booking rule - swallowing and carrying on...");
            }/*from   w  w  w.j a  v  a 2  s . c o  m*/
            continue;
        }

        // Purge any expired exclusions from this rule
        if (!bookingRule.getIsRecurring()) {
            // Non-recurring rules have no exclusions
            continue;
        }
        logger.log("Purging any expired exclusions from recurring rule: " + bookingRule);
        Set<String> datesToExclude = Sets.newHashSet(bookingRule.getDatesToExclude());
        Set<String> newDatesToExclude = new HashSet<>();
        for (String date : datesToExclude) {
            if ((new SimpleDateFormat("yyyy-MM-dd").parse(date)).after(new SimpleDateFormat("yyyy-MM-dd").parse(
                    getCurrentLocalDate().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))) {
                // Keep the exclusion if it applies to a date after yesterday.
                newDatesToExclude.add(date);
            } else {
                logger.log("Expiring exclusion for: " + date);
            }
            if (datesToExclude.size() > newDatesToExclude.size()) {
                // Update the database as some exclusions have been purged
                logger.log("Proceeding to update the rule after purging expired exclusion(s)");
                String attributeName = getAttributeNameFromBookingRule(bookingRule);
                String attributeValue = StringUtils.join(newDatesToExclude, ",");
                logger.log("ItemName: " + ruleItemName);
                logger.log("AttributeName: " + attributeName);
                logger.log("AttributeValue: " + attributeValue);
                ReplaceableAttribute bookingRuleAttribute = new ReplaceableAttribute();
                bookingRuleAttribute.setName(attributeName);
                bookingRuleAttribute.setValue(attributeValue);
                bookingRuleAttribute.setReplace(true);
                try {
                    versionNumber = Optional
                            .of(optimisticPersister.put(ruleItemName, versionNumber, bookingRuleAttribute));
                    logger.log("Updated rule to purge expired exclusion(s)");
                } catch (Exception exception) {
                    // Don't want to abort here if we fail to remove an exclusion -
                    // after all we'll get another shot at it in 24 hours time.
                    logger.log(
                            "Exception caught deleting expired booking exclusion - swallowing and carrying on...");
                }
            }
        }
    }
    logger.log("Purged all expired rules and exclusions");
}