OnlyLocationOrFirstRegionOptionallyMatchingRegionId implements ImplicitLocationSupplier { @Override @Singleton public Location get() { String region = regionSupplier.get(); Predicate<Location> locationPredicate = region == null ? Predicates.<Location>or(isZone(), isRegion()) : isZoneOrRegionWhereRegionIdEquals(region); Set<? extends Location> locations = locationsSupplier.get(); if (locationsSupplier.get().size() == 1) return getOnlyElement(locationsSupplier.get()); try { Location toReturn = Iterables.find(locations, locationPredicate); return toReturn.getScope() == LocationScope.REGION ? toReturn : toReturn.getParent(); } catch (NoSuchElementException e) { throw new NoSuchElementException(String.format("couldn't find region matching %s in %s", locationPredicate, transform(locations, ToIdAndScope.INSTANCE))); } } @Inject  OnlyLocationOrFirstRegionOptionallyMatchingRegionId(@Region Supplier<String> regionSupplier,
            @Memoized Supplier<Set<? extends Location>> locationsSupplier); @Override @Singleton Location get();  }
@Test public void testDidntMatchRegionIdThrowsNSEEWithReasonableMessage() { Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location> of(provider, region, region2, zone)); OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId( Suppliers.ofInstance("foo"), supplier); try { fn.get(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException e) { assertEquals( e.getMessage(), "couldn't find region matching isRegionAndIdEqualsOrIsZoneParentIdEquals(foo) in [servo:PROVIDER, servo-r1:REGION, servo-r2:REGION, servo-z:ZONE]"); } }
@Test public void testNoRegionUsesProvider() { Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location> of(provider)); OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId( Suppliers.<String>ofInstance(null), supplier); assertEquals(fn.get(), provider); }
@Test public void testFirstRegion() { Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location> of(provider, region, region2, zone)); OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId( Suppliers.<String>ofInstance(null), supplier); assertEquals(fn.get(), region); }
@Test public void testFindRegion() { Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location> of(provider, region, region2, zone)); OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId( Suppliers.ofInstance(region2.getId()), supplier); assertEquals(fn.get(), region2); }