@Override public ImmutablePair<LifecycleState, Optional<String>> getLifecycleState() throws Exception { if (!initialised) { throw new IllegalStateException("The lifecycle manager has not been initialised"); } ImmutablePair<Optional<Integer>, Set<Attribute>> lifecycleStateItem = getOptimisticPersister() .get(lifecycleItemName); Optional<Attribute> stateAttribute = lifecycleStateItem.right.stream() .filter(attribute -> attribute.getName().equals("State")).findFirst(); Optional<Attribute> urlAttribute = lifecycleStateItem.right.stream() .filter(attribute -> attribute.getName().equals("Url")).findFirst(); // If we've not set the lifecycle state yet, then we must be ACTIVE. LifecycleState state = stateAttribute.isPresent() ? Enum.valueOf(LifecycleState.class, stateAttribute.get().getValue()) : LifecycleState.ACTIVE; // Populate url only if in RETIRED state. Optional<String> url = (urlAttribute.isPresent() && state.equals(LifecycleState.RETIRED)) ? Optional .of(urlAttribute.get().getValue()) : Optional.empty(); return new ImmutablePair<LifecycleState, Optional<String>>(state, url); }
private ImmutablePair<Optional<Integer>, List<Booking>> getVersionedBookings(String date) throws Exception { logger.log("About to get all versioned bookings from database for: " + date); // Get existing bookings (and version number), via consistent read: ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = getOptimisticPersister() .get(date); // Convert attributes to Bookings: List<Booking> existingBookings = new ArrayList<>(); versionedAttributes.right.stream().forEach(attribute -> { existingBookings.add(getBookingFromAttribute(attribute, date)); }); return new ImmutablePair<>(versionedAttributes.left, existingBookings); }
@Override public List<Booking> deleteBooking(Booking bookingToDelete, boolean isSquashServiceUserCall) throws Exception { if (!initialised) { throw new IllegalStateException("The booking manager has not been initialised"); } getLifecycleManager().throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); logger.log("About to delete booking from database: " + bookingToDelete.toString()); Attribute attribute = new Attribute(); attribute.setName(getAttributeNameFromBooking(bookingToDelete)); attribute.setValue(bookingToDelete.getName()); getOptimisticPersister().delete(bookingToDelete.getDate(), attribute); logger.log("Deleted booking from database"); return getVersionedBookings(bookingToDelete.getDate()).right; }
@Override public void deleteRule(BookingRule bookingRuleToDelete, boolean isSquashServiceUserCall) throws Exception { if (!initialised) { throw new IllegalStateException("The rule manager has not been initialised"); } lifecycleManager .throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); logger.log("About to delete booking rule from simpledb: " + bookingRuleToDelete.toString()); String attributeName = getAttributeNameFromBookingRule(bookingRuleToDelete); String attributeValue = StringUtils.join(bookingRuleToDelete.getDatesToExclude(), ","); logger.log("Booking rule attribute name is: " + attributeName); logger.log("Booking rule attribute value is: " + attributeValue); Attribute attribute = new Attribute(); attribute.setName(attributeName); attribute.setValue(attributeValue); optimisticPersister.delete(ruleItemName, attribute); logger.log("Deleted booking rule."); return; }
private ImmutablePair<Optional<Integer>, Set<BookingRule>> getVersionedBookingRules() throws Exception { logger.log("About to get all versioned booking rules from simpledb"); // Get existing booking rules (and version number), via consistent read: ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = optimisticPersister .get(ruleItemName); // Convert attributes to BookingRules: Set<BookingRule> existingBookingRules = new HashSet<>(); versionedAttributes.right.stream().forEach(attribute -> { existingBookingRules.add(getBookingRuleFromAttribute(attribute)); }); return new ImmutablePair<>(versionedAttributes.left, existingBookingRules); }
private void expectOptimisticPersisterToReturnVersionedAttributes(int expectedVersion, List<BookingRule> bookingRules, int numCalls) throws Exception { // Set up attributes to be returned from the database's booking rule item Set<Attribute> attributes = new HashSet<>(); for (BookingRule bookingRule : bookingRules) { Attribute attribute = new Attribute(); attribute.setName(getAttributeNameFromBookingRule(bookingRule)); String[] datesToExclude = bookingRule.getDatesToExclude(); attribute.setValue(StringUtils.join(datesToExclude, ",")); attributes.add(attribute); } mockery.checking(new Expectations() { { exactly(numCalls).of(mockOptimisticPersister).get(with(equal(ruleItemName))); will(returnValue(new ImmutablePair<>(Optional.of(expectedVersion), attributes))); } }); }
private void expectToDeleteRulesViaOptimisticPersister(List<BookingRule> rulesToDelete) throws Exception { // Set up attributes to be deleted from the database's booking rule item for (BookingRule ruleToDelete : rulesToDelete) { Attribute attribute = new Attribute(); attribute.setName(getAttributeNameFromBookingRule(ruleToDelete)); String[] datesToExclude = ruleToDelete.getDatesToExclude(); attribute.setValue(StringUtils.join(datesToExclude, ",")); mockery.checking(new Expectations() { { oneOf(mockOptimisticPersister).delete(with(equal(ruleItemName)), with(equal(attribute))); } }); } }
@Test public void testGetLifecycleStateCorrectlyCallsTheOptimisticPersister() throws Exception { // We should always get the lifecycle state item from the persister. // ARRANGE lifecycleManager.initialise(mockLogger); // Set up a test lifecycle-state item - with an arbitrary version number. ImmutablePair<Optional<Integer>, Set<Attribute>> testItem = new ImmutablePair<Optional<Integer>, Set<Attribute>>( Optional.of(42), new HashSet<Attribute>()); mockery.checking(new Expectations() { { exactly(1).of(mockOptimisticPersister).get(with(equal("LifecycleState"))); will(returnValue(testItem)); } }); // ACT // FIXME verify it returns value got from the persister lifecycleManager.getLifecycleState(); }
@SuppressWarnings("unchecked") @Test public void execute() { List<String> attributeNames = new ArrayList<String>(); attributeNames.add("ATTRIBUTE1"); exchange.getIn().setHeader(SdbConstants.ATTRIBUTE_NAMES, attributeNames); exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1"); command.execute(); assertEquals("DOMAIN1", sdbClient.getAttributesRequest.getDomainName()); assertEquals("ITEM1", sdbClient.getAttributesRequest.getItemName()); assertEquals(Boolean.TRUE, sdbClient.getAttributesRequest.getConsistentRead()); assertEquals(attributeNames, sdbClient.getAttributesRequest.getAttributeNames()); List<Attribute> attributes = exchange.getIn().getHeader(SdbConstants.ATTRIBUTES, List.class); assertEquals(2, attributes.size()); assertEquals("AttributeOne", attributes.get(0).getName()); assertEquals("Value One", attributes.get(0).getValue()); assertEquals("AttributeTwo", attributes.get(1).getName()); assertEquals("Value Two", attributes.get(1).getValue()); }
@Test public void execute() { List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute("NAME1", "VALUE1")); exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes); exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1"); UpdateCondition condition = new UpdateCondition("Key1", "Value1", true); exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition); command.execute(); assertEquals("DOMAIN1", sdbClient.deleteAttributesRequest.getDomainName()); assertEquals("ITEM1", sdbClient.deleteAttributesRequest.getItemName()); assertEquals(condition, sdbClient.deleteAttributesRequest.getExpected()); assertEquals(attributes, sdbClient.deleteAttributesRequest.getAttributes()); }
@Test public void deleteAttributes() { final List<Attribute> attributes = Arrays.asList(new Attribute[] { new Attribute("NAME1", "VALUE1")}); final UpdateCondition condition = new UpdateCondition("Key1", "Value1", true); template.send("direct:start", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DeleteAttributes); exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes); exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1"); exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition); } }); assertEquals("TestDomain", amazonSDBClient.deleteAttributesRequest.getDomainName()); assertEquals("ITEM1", amazonSDBClient.deleteAttributesRequest.getItemName()); assertEquals(condition, amazonSDBClient.deleteAttributesRequest.getExpected()); assertEquals(attributes, amazonSDBClient.deleteAttributesRequest.getAttributes()); }
@VisibleForTesting static CassandraInstance transform(Item item) { CassandraInstance.Builder instanceBuilder = new CassandraInstance.Builder(); for (Attribute attr : item.getAttributes()) { if (attr.getName().equals(ID_KEY)) { instanceBuilder.id(Integer.parseInt(attr.getValue())); } else if (attr.getName().equals(DATACENTER_KEY)) { instanceBuilder.dataCenter(attr.getValue()); } else if (attr.getName().equals(RACK_KEY)) { instanceBuilder.rack(attr.getValue()); } else if (attr.getName().equals(HOSTNAME_KEY)) { instanceBuilder.hostName(attr.getValue()); } else if (attr.getName().equals(PUBLIC_IP_ADDRESS_KEY)) { instanceBuilder.publicIpAddress(attr.getValue()); } else if (attr.getName().equals(FULLY_QUALIFIED_DOMAIN_NAME_KEY)) { instanceBuilder.fullyQualifiedDomainName(attr.getValue()); } } return instanceBuilder.build(); }
private static void assertAttributes(DeleteAttributesRequest request) { assertEquals(6, request.getAttributes().size()); for (Attribute attr : request.getAttributes()) { if (attr.getName().equals(SdbCassandraInstanceDao.ID_KEY)) { assertEquals(String.valueOf(ID), attr.getValue()); } else if (attr.getName().equals(SdbCassandraInstanceDao.DATACENTER_KEY)) { assertEquals(DATACENTER, attr.getValue()); } else if (attr.getName().equals(SdbCassandraInstanceDao.RACK_KEY)) { assertEquals(RACK, attr.getValue()); } else if (attr.getName().equals(SdbCassandraInstanceDao.HOSTNAME_KEY)) { assertEquals(HOSTNAME, attr.getValue()); } else if (attr.getName().endsWith(SdbCassandraInstanceDao.PUBLIC_IP_ADDRESS_KEY)) { assertEquals(PUBLIC_IP_ADDRESS, attr.getValue()); } else if (attr.getName().endsWith(SdbCassandraInstanceDao.FULLY_QUALIFIED_DOMAIN_NAME_KEY)) { assertEquals(FULLY_QUALIFIED_DOMAIN_NAME, attr.getValue()); } else { assertDuplicateAttribute(attr.getName(), attr.getValue()); } } }
/** * {@inheritDoc} */ @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Set<Entry<String, String>> entrySet() { final GetAttributesResult result = this.credentials.aws().getAttributes( new GetAttributesRequest() .withConsistentRead(true) .withDomainName(this.table) .withItemName(this.label) ); final Set<Entry<String, String>> entries = new HashSet<Entry<String, String>>(0); for (final Attribute attr : result.getAttributes()) { entries.add( new AbstractMap.SimpleImmutableEntry<String, String>( attr.getName(), attr.getValue() ) ); } return entries; }
private <T> long invokeCountImpl(boolean consistentRead, SimpleDbEntityInformation<T, ?> entityInformation, final String countQuery) { LOGGER.debug("Count items for query " + countQuery); validateSelectQuery(countQuery); final String escapedQuery = getEscapedQuery(countQuery, entityInformation); final SelectResult selectResult = invokeFindImpl(consistentRead, escapedQuery); for (Item item : selectResult.getItems()) { if (item.getName().equals("Domain")) { for (Attribute attribute : item.getAttributes()) { if (attribute.getName().equals("Count")) { return Long.parseLong(attribute.getValue()); } } } } return 0; }
@Override public ImmutablePair<Optional<Integer>, Set<Attribute>> get(String itemName) { if (!initialised) { throw new IllegalStateException("The optimistic persister has not been initialised"); } logger.log("About to get all active attributes from simpledb item: " + itemName); AmazonSimpleDB client = getSimpleDBClient(); // Do a consistent read - to ensure we get correct version number GetAttributesRequest simpleDBRequest = new GetAttributesRequest(simpleDbDomainName, itemName); logger.log("Using simpleDB domain: " + simpleDbDomainName); simpleDBRequest.setConsistentRead(true); GetAttributesResult result = client.getAttributes(simpleDBRequest); List<Attribute> attributes = result.getAttributes(); // Get the version number and other attributes. Optional<Integer> version = Optional.empty(); Set<Attribute> nonVersionAttributes = new HashSet<>(); if (attributes.size() > 0) { // If we have any attributes, we'll always have a version number Attribute versionNumberAttribute = attributes.stream() .filter(attribute -> attribute.getName().equals(versionAttributeName)).findFirst().get(); version = Optional.of(Integer.parseInt(versionNumberAttribute.getValue())); logger.log("Retrieved version number: " + versionNumberAttribute.getValue()); attributes.remove(versionNumberAttribute); // Add all active attributes (i.e. those not pending deletion) nonVersionAttributes.addAll(attributes.stream() .filter(attribute -> !attribute.getValue().startsWith("Inactive")) .collect(Collectors.toSet())); } logger.log("Got all attributes from simpledb"); return new ImmutablePair<>(version, nonVersionAttributes); }
private Booking getBookingFromAttribute(Attribute attribute, String date) { // N.B. Attributes have names like <court>-<courtSpan>-<slot>-<slotSpan> // e.g. 4-1-7-1 is a single booking for court 4 at time slot 7 // e.g. 4-2-7-3 is a block booking for courts 4-5 for time slots 7-9 String[] parts = attribute.getName().split("-"); Integer court = Integer.parseInt(parts[0]); Integer courtSpan = Integer.parseInt(parts[1]); Integer slot = Integer.parseInt(parts[2]); Integer slotSpan = Integer.parseInt(parts[3]); String name = attribute.getValue(); Booking booking = new Booking(court, courtSpan, slot, slotSpan, name); booking.setDate(date); return booking; }
private BookingRule getBookingRuleFromAttribute(Attribute attribute) { // N.B. BookingRule attributes have names like // <date>-<court>-<courtSpan>-<slot>-<slotSpan>-<isRecurring>-<name> // e.g. 2016-07-04-4-2-7-3-true-TeamTraining books courts 4-5 for time slots // 7-9 every Monday, starting on Monday 4th July 2016, for TeamTraining. // The value is a comma-separated array of dates to exclude. String[] parts = attribute.getName().split("-"); String date = parts[0] + "-" + parts[1] + "-" + parts[2]; Integer court = Integer.parseInt(parts[3]); Integer courtSpan = Integer.parseInt(parts[4]); Integer slot = Integer.parseInt(parts[5]); Integer slotSpan = Integer.parseInt(parts[6]); Boolean isRecurring = Boolean.valueOf(parts[7]); // All remaining parts will be the booking name - possibly hyphenated String name = ""; for (int partNum = 8; partNum < parts.length; partNum++) { name += parts[partNum]; if (partNum < (parts.length - 1)) { name += "-"; } } Booking rulesBooking = new Booking(court, courtSpan, slot, slotSpan, name); rulesBooking.setDate(date); String[] datesToExclude = new String[0]; if (attribute.getValue().length() > 0) { // Use split only if we have some dates to exclude - otherwise we would // get an (invalid) length-1 array containing a single empty string. datesToExclude = attribute.getValue().split(","); } return new BookingRule(rulesBooking, isRecurring, datesToExclude); }
@Before public void beforeTest() { optimisticPersister = new TestOptimisticPersister(); // Set up the mocks mockLogger = mockery.mock(LambdaLogger.class); mockery.checking(new Expectations() { { ignoring(mockLogger); } }); mockSimpleDBClient = mockery.mock(AmazonSimpleDB.class); optimisticPersister.setSimpleDBClient(mockSimpleDBClient); // Set up some typical test attributes allAttributes = new HashSet<>(); nonVersionAttributes = new HashSet<>(); activeNonVersionAttributes = new HashSet<>(); Attribute versionAttribute = new Attribute(); versionAttribute.setName(versionAttributeName); versionAttribute.setValue(Integer.toString(testVersionNumber)); Attribute activeAttribute = new Attribute(); activeAttribute.setName("ActiveAttribute"); activeAttribute.setValue("Active"); Attribute inactiveAttribute = new Attribute(); inactiveAttribute.setName("InactiveAttribute"); inactiveAttribute.setValue("Inactive"); allAttributes.add(versionAttribute); allAttributes.add(activeAttribute); allAttributes.add(inactiveAttribute); nonVersionAttributes.add(activeAttribute); nonVersionAttributes.add(inactiveAttribute); activeNonVersionAttributes.add(activeAttribute); }
@Test public void testGetReturnsTheCorrectVersionNumberAndAttributes() throws Exception { // Get should not return the version-number attribute (but should return the // version number as part of its result pair) and it should not return // inactive attributes. // ARRANGE initialiseOptimisticPersister(); GetAttributesRequest simpleDBRequest = new GetAttributesRequest(testSimpleDBDomainName, testItemName); simpleDBRequest.setConsistentRead(true); // First assert that our allAttribute set has both version and inactive // attributes (which should get filtered out). assertTrue("AllAttribute list should contain an inactive attribute", allAttributes.stream() .filter(attribute -> attribute.getValue().startsWith("Inactive")).count() > 0); assertTrue("AllAttribute list should contain a version number attribute", allAttributes .stream().filter(attribute -> attribute.getName().equals(versionAttributeName)).count() > 0); GetAttributesResult getAttributesResult = new GetAttributesResult(); getAttributesResult.setAttributes(allAttributes); mockery.checking(new Expectations() { { allowing(mockSimpleDBClient).getAttributes(with(equal(simpleDBRequest))); will(returnValue(getAttributesResult)); } }); // ACT ImmutablePair<Optional<Integer>, Set<Attribute>> result = optimisticPersister.get(testItemName); // ASSERT assertTrue("OptimisticPersister should return the correct attributes. Actual: " + result.right + ", Expected: " + activeNonVersionAttributes, result.right.equals(activeNonVersionAttributes)); assertTrue("OptimisticPersister should return a version number", result.left.isPresent()); assertTrue("OptimisticPersister should return the correct version number", result.left.get() .equals(testVersionNumber)); }
@Test public void testGetReturnsAnEmptyVersionNumberAndNoAttributesWhenThereAreNoAttributesInTheDatabase() throws Exception { // ARRANGE initialiseOptimisticPersister(); GetAttributesRequest simpleDBRequest = new GetAttributesRequest(testSimpleDBDomainName, testItemName); simpleDBRequest.setConsistentRead(true); // First assert that our allAttribute set has both version and inactive // attributes (which should get filtered out). assertTrue("AllAttribute list should contain an inactive attribute", allAttributes.stream() .filter(attribute -> attribute.getValue().startsWith("Inactive")).count() > 0); assertTrue("AllAttribute list should contain a version number attribute", allAttributes .stream().filter(attribute -> attribute.getName().equals(versionAttributeName)).count() > 0); // Mimic database with no attributes GetAttributesResult getAttributesResult = new GetAttributesResult(); mockery.checking(new Expectations() { { allowing(mockSimpleDBClient).getAttributes(with(equal(simpleDBRequest))); will(returnValue(getAttributesResult)); } }); // ACT ImmutablePair<Optional<Integer>, Set<Attribute>> result = optimisticPersister.get(testItemName); // ASSERT assertTrue("OptimisticPersister should return no attributes", result.right.size() == 0); assertTrue("OptimisticPersister should return an empty version number", !result.left.isPresent()); }
@Test public void testGetAllItemsCorrectlyCallsSimpleDB() throws Exception { // ARRANGE initialiseOptimisticPersister(); SelectRequest selectRequest = new SelectRequest(); selectRequest.setConsistentRead(true); selectRequest.setSelectExpression("select * from `" + testSimpleDBDomainName + "`"); // Configure select result with an item to be returned: SelectResult selectResult = new SelectResult(); Set<Item> items = new HashSet<>(); Item item = new Item(); String itemDate = "2016-07-23"; item.setName(itemDate); item.setAttributes(allAttributes); items.add(item); selectResult.setItems(items); mockery.checking(new Expectations() { { oneOf(mockSimpleDBClient).select(with(equal(selectRequest))); will(returnValue(selectResult)); } }); List<ImmutablePair<String, List<Attribute>>> expectedItems = new ArrayList<>(); ImmutablePair<String, List<Attribute>> pair = new ImmutablePair<>(itemDate, new ArrayList<>( activeNonVersionAttributes)); expectedItems.add(pair); // ACT List<ImmutablePair<String, List<Attribute>>> actualItems = optimisticPersister.getAllItems(); // ASSERT assertTrue("OptimisticPersister should return the correct items. Actual: " + actualItems + ", Expected: " + expectedItems, actualItems.equals(expectedItems)); }
@Test public void testDeleteThrowsWhenOptimisticPersisterUninitialised() throws Exception { // ARRANGE thrown.expect(Exception.class); thrown.expectMessage("The optimistic persister has not been initialised"); // ACT // Do not initialise the optimistic persister first - so delete should throw Attribute testAttribute = new Attribute(); testAttribute.setName("Name"); testAttribute.setValue("Value"); optimisticPersister.delete(testItemName, testAttribute); }
private void doTestDeleteReturnsEarlyIfAttributeBeingDeletedDoesNotExist( Boolean versionNumberExists) throws Exception { // ARRANGE initialiseOptimisticPersister(); // Configure database to return no attributes. GetAttributesRequest simpleDBRequest = new GetAttributesRequest(testSimpleDBDomainName, testItemName); simpleDBRequest.setConsistentRead(true); GetAttributesResult getAttributesResult = new GetAttributesResult(); if (versionNumberExists) { // Ensure we return at least the version number attribute getAttributesResult.setAttributes(allAttributes); } mockery.checking(new Expectations() { { oneOf(mockSimpleDBClient).getAttributes(with(equal(simpleDBRequest))); will(returnValue(getAttributesResult)); } }); // Ensure we return early. mockery.checking(new Expectations() { { never(mockSimpleDBClient).deleteAttributes(with(anything())); } }); // ACT Attribute attributeToDelete = new Attribute(); attributeToDelete.setName("Name"); attributeToDelete.setValue("Value"); optimisticPersister.delete(testItemName, attributeToDelete); }
private void expectOptimisticPersisterGetToReturnVersionedAttributesOrThrow( Optional<Integer> expectedVersionNumber, List<Booking> expectedBookings, Optional<Exception> exceptionToThrow, int numCalls) throws Exception { Set<Attribute> attributes = new HashSet<>(); expectedBookings.stream().forEach( booking -> { attributes.add(new Attribute(booking.getCourt().toString() + "-" + booking.getCourtSpan().toString() + "-" + booking.getSlot().toString() + "-" + booking.getSlotSpan().toString(), booking.getName())); }); // Set up mock optimistic persister to return these bookings - or to throw if (!exceptionToThrow.isPresent()) { mockery.checking(new Expectations() { { exactly(numCalls).of(mockOptimisticPersister).get(with(equal(fakeCurrentDateString))); will(returnValue(new ImmutablePair<>(expectedVersionNumber, attributes))); } }); } else { mockery.checking(new Expectations() { { exactly(numCalls).of(mockOptimisticPersister).get(with(equal(fakeCurrentDateString))); will(throwException(exceptionToThrow.get())); } }); } bookingManager.setOptimisticPersister(mockOptimisticPersister); }
private void expectDeleteBookingToReturnUpdatedBookingsOrThrow(Booking bookingToDelete, Optional<List<Booking>> expectedBookingsAfterDelete, Optional<Exception> exceptionToThrow) throws Exception { String attributeName; attributeName = bookingToDelete.getCourt().toString() + "-" + bookingToDelete.getCourtSpan().toString() + "-" + bookingToDelete.getSlot().toString() + "-" + bookingToDelete.getSlotSpan().toString(); Attribute attribute = new Attribute(); attribute.setName(attributeName); attribute.setValue(bookingToDelete.getName()); if (!exceptionToThrow.isPresent()) { mockery.checking(new Expectations() { { oneOf(mockOptimisticPersister).delete(with(equal(bookingToDelete.getDate())), with(equal(attribute))); } }); // We expect call to getBookings after the delete Integer someArbitraryNumber = 42; expectOptimisticPersisterGetToReturnVersionedAttributesOrThrow( Optional.of(someArbitraryNumber), expectedBookingsAfterDelete.get(), Optional.empty()); } else { mockery.checking(new Expectations() { { oneOf(mockOptimisticPersister).delete(with(equal(bookingToDelete.getDate())), with(equal(attribute))); will(throwException(exceptionToThrow.get())); } }); } bookingManager.setOptimisticPersister(mockOptimisticPersister); }
private void doTestDeleteAllBookingsCorrectlyCallsTheLifecycleManager( boolean isSquashServiceUserCall) throws Exception { // ARRANGE initialiseBookingManager(); // Set up mock lifecycle manager mockLifecycleManager = mockery.mock(ILifecycleManager.class, "replacementLifecycleManagerMock"); mockery.checking(new Expectations() { { oneOf(mockLifecycleManager).throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); // There's an internal call to getAllBookings which calls lifecycle // manager with a true argument. allowing(mockLifecycleManager).throwIfOperationInvalidForCurrentLifecycleState(true, isSquashServiceUserCall); } }); bookingManager.setLifecycleManager(mockLifecycleManager); // Set up optimistic persister to to return no bookings - this is incidental // to the test, but needs to be setup for the test to run at all. List<ImmutablePair<String, List<Attribute>>> emptyList = new ArrayList<>(); mockery.checking(new Expectations() { { oneOf(mockOptimisticPersister).getAllItems(); will(returnValue(emptyList)); } }); bookingManager.setOptimisticPersister(mockOptimisticPersister); // ACT bookingManager.deleteAllBookings(isSquashServiceUserCall); }
@Test public void testSetLifecycleStateCorrectlyCallsTheOptimisticPersister_retired_with_url() throws Exception { // Tests happy path for setting RETIRED state - where we also supply a // forwarding Url for the new site. // ARRANGE lifecycleManager.initialise(mockLogger); // Set up a test lifecycle-state item - with an arbitrary version number. ImmutablePair<Optional<Integer>, Set<Attribute>> testItem = new ImmutablePair<Optional<Integer>, Set<Attribute>>( Optional.of(42), new HashSet<Attribute>()); ReplaceableAttribute newStateAttribute = new ReplaceableAttribute(); newStateAttribute.setName("State"); newStateAttribute.setValue("RETIRED"); newStateAttribute.setReplace(true); ReplaceableAttribute newUrlAttribute = new ReplaceableAttribute(); newUrlAttribute.setName("Url"); newUrlAttribute.setValue(exampleForwardingUrl); newUrlAttribute.setReplace(true); mockery.checking(new Expectations() { { exactly(1).of(mockOptimisticPersister).get(with(equal("LifecycleState"))); will(returnValue(testItem)); exactly(1).of(mockOptimisticPersister).put(with(equal("LifecycleState")), with(equal(Optional.of(42))), with(equal(newStateAttribute))); will(returnValue(43)); exactly(1).of(mockOptimisticPersister).put(with(equal("LifecycleState")), with(equal(Optional.of(43))), with(equal(newUrlAttribute))); } }); // ACT lifecycleManager.setLifecycleState(LifecycleState.RETIRED, Optional.of(exampleForwardingUrl)); }
private void doTestSetLifecycleStateCorrectlyCallsTheOptimisticPersister( LifecycleState lifecycleState) throws Exception { // ARRANGE lifecycleManager.initialise(mockLogger); // Set up a test lifecycle-state item - with an arbitrary version number. ImmutablePair<Optional<Integer>, Set<Attribute>> testItem = new ImmutablePair<Optional<Integer>, Set<Attribute>>( Optional.of(42), new HashSet<Attribute>()); ReplaceableAttribute newStateAttribute = new ReplaceableAttribute(); newStateAttribute.setName("State"); newStateAttribute.setValue(lifecycleState.name()); newStateAttribute.setReplace(true); mockery.checking(new Expectations() { { exactly(1).of(mockOptimisticPersister).get(with(equal("LifecycleState"))); will(returnValue(testItem)); exactly(1).of(mockOptimisticPersister).put(with(equal("LifecycleState")), with(equal(Optional.of(42))), with(equal(newStateAttribute))); // Don't want to put the Url attribute in this case - since we're not // retiring. never(mockOptimisticPersister).put(with(equal("LifecycleState")), with(equal(Optional.of(43))), with(anything())); } }); // ACT lifecycleManager.setLifecycleState(lifecycleState, Optional.empty()); }
@Test public void testGetLifecycleStateReturnsActiveWhenNoStateHasBeenSet() throws Exception { // If no LifecycleState has been set then the site must be in the ACTIVE // state. // ARRANGE lifecycleManager.initialise(mockLogger); // Set up an empty test lifecycle-state item - with an empty version // number. This corresponds to the state never having been set. ImmutablePair<Optional<Integer>, Set<Attribute>> emptyTestItem = new ImmutablePair<Optional<Integer>, Set<Attribute>>( Optional.empty(), new HashSet<Attribute>()); mockery.checking(new Expectations() { { exactly(1).of(mockOptimisticPersister).get(with(equal("LifecycleState"))); will(returnValue(emptyTestItem)); } }); // ACT ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager .getLifecycleState(); // ASSERT assertTrue("Lifecycle state should be active if it has not been set", lifecycleState.left.equals(LifecycleState.ACTIVE)); }
@Test public void testthrowIfOperationInvalidForCurrentLifecycleStateThrowsForEndUserCallsInRetiredStateWithoutUrl() throws Exception { // All end-user operations should not be allowed in RETIRED state. N.B. // System operations will still be allowed. This just adds check that if // we're retired but for some reason don't have a forwarding url that we // still throw. But we should never get to this state... // ARRANGE thrown.expect(Exception.class); thrown .expectMessage("Cannot access bookings or rules - there is an updated version of the booking service. Forwarding Url: UrlNotPresent"); lifecycleManager.initialise(mockLogger); // Set up a defective retired lifecycle-state item - with missing url. Attribute retiredStateAttribute = new Attribute(); retiredStateAttribute.setName("State"); retiredStateAttribute.setValue("RETIRED"); Set<Attribute> retiredAttributes = new HashSet<Attribute>(); retiredAttributes.add(retiredStateAttribute); mockery.checking(new Expectations() { { exactly(1).of(mockOptimisticPersister).get(with(equal("LifecycleState"))); will(returnValue(new ImmutablePair<Optional<Integer>, Set<Attribute>>(Optional.of(40), retiredAttributes))); } }); // ACT // Should throw - as its an end-user operation when in RETIRED state. lifecycleManager.throwIfOperationInvalidForCurrentLifecycleState(true, true); }
@Test public void deleteAttributes() { final List<Attribute> attributes = Arrays.asList(new Attribute[] { new Attribute("NAME1", "VALUE1")}); final UpdateCondition condition = new UpdateCondition("Key1", "Value1", true); template.send("direct:start", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(SdbConstants.OPERATION, SdbOperations.DeleteAttributes); exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes); exchange.getIn().setHeader(SdbConstants.ITEM_NAME, "ITEM1"); exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition); } }); }
@Test(expected = IllegalArgumentException.class) public void executeWithoutItemName() { List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute("NAME1", "VALUE1")); exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes); UpdateCondition condition = new UpdateCondition("Key1", "Value1", true); exchange.getIn().setHeader(SdbConstants.UPDATE_CONDITION, condition); command.execute(); }
@Test public void determineAttributes() { assertNull(this.command.determineAttributes()); List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute("NAME1", "VALUE1")); exchange.getIn().setHeader(SdbConstants.ATTRIBUTES, attributes); assertEquals(attributes, this.command.determineAttributes()); }
@Override public GetAttributesResult getAttributes(GetAttributesRequest getAttributesRequest) throws AmazonServiceException, AmazonClientException { this.getAttributesRequest = getAttributesRequest; return new GetAttributesResult() .withAttributes(new Attribute("AttributeOne", "Value One")) .withAttributes(new Attribute("AttributeTwo", "Value Two")); }
private Entry createEntry(Item item,boolean user) { StringBuffer dnBuff = new StringBuffer(); LDAPAttribute objClass = null; if (user) { dnBuff.append("uid=").append(item.getName()).append(",ou=users,").append(this.dnBase); objClass = new LDAPAttribute("objectClass",GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getUserObjectClass()); } else { dnBuff.append("cn=").append(item.getName()).append(",ou=groups,").append(this.dnBase); objClass = new LDAPAttribute("objectClass",GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getGroupObjectClass()); } LDAPAttributeSet attrs = new LDAPAttributeSet(); for (Attribute fromAmz : item.getAttributes()) { LDAPAttribute attr = attrs.getAttribute(fromAmz.getName()); if (attr == null) { attr = new LDAPAttribute(fromAmz.getName()); attrs.add(attr); } attr.addValue(fromAmz.getValue()); } attrs.add(objClass); return new Entry(new LDAPEntry(dnBuff.toString(),attrs)); }
/** * @param item * @return */ private ReplaceableItem itemToAWSItem(Item item) { List<ReplaceableAttribute> attributes = new ArrayList<ReplaceableAttribute>(); for (com.intuit.tank.reporting.databases.Attribute attr : item.getAttributes()) { addAttribute(attributes, attr.getName(), attr.getValue()); } ReplaceableItem ret = new ReplaceableItem(item.getName(), attributes); return ret; }
/** * @param item * @return */ private com.intuit.tank.reporting.databases.Item resultToItem(com.amazonaws.services.simpledb.model.Item item) { List<com.intuit.tank.reporting.databases.Attribute> attrs = new ArrayList<com.intuit.tank.reporting.databases.Attribute>(); com.intuit.tank.reporting.databases.Item ret = new com.intuit.tank.reporting.databases.Item(item.getName(), attrs); for (Attribute attr : item.getAttributes()) { attrs.add(new com.intuit.tank.reporting.databases.Attribute(attr.getName(), attr.getValue())); } return ret; }
protected Map<String, List<String>> createAttributeMap(List<Attribute> attributes) { Map<String, List<String>> map = new TreeMap<String, List<String>>(); for (Attribute attribute : attributes) { if (map.get(attribute.getName()) == null) { List<String> list = new ArrayList<String>(); list.add(attribute.getValue()); map.put(attribute.getName(), list); } else { map.get(attribute.getName()).add(attribute.getValue()); } } return map; }