target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testGetSpecificValueInMap() { Supplier<Map<String, Supplier<String>>> testMap = Suppliers.<Map<String, Supplier<String>>> ofInstance( ImmutableMap.of("foo", Suppliers.ofInstance("bar"))); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "foo").get(), "bar"); assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, "baz").get(), null); } | public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } | Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } } | Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } } | Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) { return new Supplier<V>() { @Override public V get() { Map<K, Supplier<V>> map = input.get(); return map.containsKey(keyValue) ? map.get(keyValue).get() : null; } @Override public String toString() { return String.format("getValueInMapOrNull('%1$s')", keyValue); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void testOfInstanceFunction() { assertEquals(Suppliers2.ofInstanceFunction().apply("foo").get(), "foo"); } | public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } | Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } } | Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } } | Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { public static <X> Function<X, Supplier<X>> ofInstanceFunction() { return new Function<X, Supplier<X>>() { @Override public Supplier<X> apply(X arg0) { return Suppliers.ofInstance(arg0); } @Override public String toString() { return "Suppliers.ofInstance()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void testOrWhenFirstNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance(null), Suppliers.ofInstance("foo")).get(), "foo"); } | @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void testIfUnmodifiedSince() { Date ifUnmodifiedSince = new Date(999999L); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifUnmodifiedSince(ifUnmodifiedSince); GetOptions expected = new GetOptions(); expected.ifUnmodifiedSince(ifUnmodifiedSince); assertEquals(fn.apply(in), expected); } | @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } |
@Test public void testOrWhenFirstNotNull() { assertEquals(Suppliers2.or(Suppliers.<String> ofInstance("foo"), Suppliers.ofInstance("bar")).get(), "foo"); } | @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { @Beta public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { T val = unlessNull.get(); if (val != null) return val; return fallback.get(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessNull", unlessNull).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void testOnThrowableWhenFirstThrowsMatchingException() { assertEquals(Suppliers2.onThrowable(new Supplier<String>() { @Override public String get() { throw new NoSuchElementException(); } }, NoSuchElementException.class, Suppliers.ofInstance("foo")).get(), "foo"); } | @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test(expectedExceptions = RuntimeException.class) public void testOnThrowableWhenFirstThrowsUnmatchingException() { Suppliers2.onThrowable(new Supplier<String>() { @Override public String get() { throw new RuntimeException(); } }, NoSuchElementException.class, Suppliers.ofInstance("foo")).get(); } | @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void testOnThrowableWhenFirstIsFine() { assertEquals( Suppliers2.onThrowable(Suppliers.<String> ofInstance("foo"), NoSuchElementException.class, Suppliers.ofInstance("bar")).get(), "foo"); } | @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } | Suppliers2 { @Beta public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback) { return new Supplier<T>() { @Override public T get() { try { return unlessThrowable.get(); } catch (Throwable t) { if (Throwables2.getFirstThrowableOfType(t, throwable) != null) return fallback.get(); throw Throwables.propagate(t); } } @Override public String toString() { return MoreObjects.toStringHelper(this).add("unlessThrowable", unlessThrowable) .add("throwable", throwable.getSimpleName()).add("fallback", fallback).toString(); } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable,
final Class<X> throwable, final Supplier<T> fallback); } |
@Test public void defaultGeneratorContainsAll() { String password = new PasswordGenerator().generate(); assertTrue(password.matches(".*[a-z].*[a-z].*")); assertTrue(password.matches(".*[A-Z].*[A-Z].*")); assertTrue(password.matches(".*[0-9].*[0-9].*")); assertTrue(password.replaceAll("[a-zA-Z0-9]", "").length() > 0); } | public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } | PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } } | PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } } | PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } Config lower(); Config upper(); Config numbers(); Config symbols(); String generate(); } | PasswordGenerator { public String generate() { StringBuilder sb = new StringBuilder(); sb.append(lower.fragment()); sb.append(upper.fragment()); sb.append(numbers.fragment()); sb.append(symbols.fragment()); return shuffleAndJoin(sb.toString().toCharArray()); } Config lower(); Config upper(); Config numbers(); Config symbols(); String generate(); } |
@Test public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String contents = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(contents.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().openStream()), contents); assertFalse(iter.hasNext()); } | @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } |
@Test public void testIterableSliceExpectedMulti() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); Payload payload = new InputStreamPayload(new ByteArrayInputStream("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 10).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "aaaaaaaaaa"); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "bbbbbbbbbb"); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(Strings2.toStringAndClose(iter.next().getInput()), "ccccc"); assertFalse(iter.hasNext()); } | @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } |
@Test public void testIterableSliceWithRepeatingByteSourceSmallerPartSize() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); ByteSource byteSource = ByteSource.wrap("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.UTF_8)); Payload payload = new ByteSourcePayload(byteSource); Iterator<Payload> iter = slicer.slice(payload, 10).iterator(); Payload part; assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "aaaaaaaaaa"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10)); assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "bbbbbbbbbb"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10)); assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "ccccc"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(5)); assertFalse(iter.hasNext()); } | @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } |
@Test public void testIterableSliceWithRepeatingByteSourceLargerPartSize() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); ByteSource byteSource = ByteSource.wrap("aaaaaaaaaabbbbbbbbbbccccc".getBytes(Charsets.UTF_8)); Payload payload = new ByteSourcePayload(byteSource); Iterator<Payload> iter = slicer.slice(payload, 50).iterator(); Payload part; assertTrue(iter.hasNext(), "Not enough results"); part = iter.next(); assertEquals(Strings2.toStringAndClose(part.getInput()), "aaaaaaaaaabbbbbbbbbbccccc"); assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(25)); assertFalse(iter.hasNext()); } | @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } | BasePayloadSlicer implements PayloadSlicer { @Override public Payload slice(Payload input, long offset, long length) { checkNotNull(input); checkArgument(offset >= 0, "offset is negative"); checkArgument(length >= 0, "length is negative"); Payload returnVal; if (input.getRawContent() instanceof File) { returnVal = doSlice((File) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof String) { returnVal = doSlice((String) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof byte[]) { returnVal = doSlice((byte[]) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof InputStream) { returnVal = doSlice((InputStream) input.getRawContent(), offset, length); } else if (input.getRawContent() instanceof ByteSource) { returnVal = doSlice((ByteSource) input.getRawContent(), offset, length); } else { returnVal = doSlice(input, offset, length); } return copyMetadataAndSetLength(input, returnVal, length); } @Override Payload slice(Payload input, long offset, long length); @Override Iterable<Payload> slice(Payload input, long size); } |
@Test public void testIfModifiedSince() { Date ifModifiedSince = new Date(999999L); org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.ifModifiedSince(ifModifiedSince); GetOptions expected = new GetOptions(); expected.ifModifiedSince(ifModifiedSince); assertEquals(fn.apply(in), expected); } | @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } |
@Test void testHear() { Injector i = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(any(), blawr); } }); assertEquals(i.getInstance(A.class).logger.getCategory(), getClass().getName() + "$A"); assertEquals(i.getInstance(B.class).logger.getCategory(), getClass().getName() + "$B"); assertEquals(i.getInstance(B.class).blogger.getCategory(), "blogger"); } | public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } | BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } } | BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); } | BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); void hear(TypeLiteral<I> injectableType,
TypeEncounter<I> encounter); } | BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); void hear(TypeLiteral<I> injectableType,
TypeEncounter<I> encounter); } |
@Test(expectedExceptions = RuntimeException.class) public void testArbitraryExceptionDoesntConvert() throws Exception { fn.createOrPropagate(new RuntimeException()); } | @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT") .build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT") .build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } | HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); } |
@Test(expectedExceptions = AuthorizationException.class) public void test401ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(401).build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = AuthorizationException.class) public void test403ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(403).build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = ResourceNotFoundException.class) public void test404ToResourceNotFoundException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(404).build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = IllegalStateException.class) public void test409ToIllegalStateException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(409).build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT").build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT").build())); } | @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } | MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); } |
@Test public void testWithId() { ProviderMetadata providerMetadata; try { providerMetadata = Providers.withId("fake-id"); fail("Looking for a provider with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } providerMetadata = Providers.withId(testBlobstoreProvider.getId()); assertEquals(testBlobstoreProvider, providerMetadata); assertNotEquals(testBlobstoreProvider, testComputeProvider); assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider); } | public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } | Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } } | Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } } | Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } static Function<ProviderMetadata, String> idFunction(); static Function<ProviderMetadata, ApiMetadata> apiMetadataFunction(); static Iterable<ProviderMetadata> fromServiceLoader(); static Iterable<ProviderMetadata> all(); static ProviderMetadata withId(String id); static Iterable<ProviderMetadata> viewableAs(TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> viewableAs(Class<? extends View> viewableAs); static Iterable<ProviderMetadata> apiMetadataAssignableFrom(TypeToken<? extends ApiMetadata> api); static Iterable<ProviderMetadata> contextAssignableFrom(
TypeToken<? extends Context> context); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,
TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,
Class<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,
TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,
Class<? extends View> viewableAs); } | Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } static Function<ProviderMetadata, String> idFunction(); static Function<ProviderMetadata, ApiMetadata> apiMetadataFunction(); static Iterable<ProviderMetadata> fromServiceLoader(); static Iterable<ProviderMetadata> all(); static ProviderMetadata withId(String id); static Iterable<ProviderMetadata> viewableAs(TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> viewableAs(Class<? extends View> viewableAs); static Iterable<ProviderMetadata> apiMetadataAssignableFrom(TypeToken<? extends ApiMetadata> api); static Iterable<ProviderMetadata> contextAssignableFrom(
TypeToken<? extends Context> context); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,
TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,
Class<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,
TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,
Class<? extends View> viewableAs); } |
@Test public void testRanges() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.range(0, 1024); in.startAt(2048); GetOptions expected = new GetOptions(); expected.range(0, 1024); expected.startAt(2048); assertEquals(fn.apply(in), expected); } | @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } |
@Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getEndpoint(), "http: assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } | @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); } |
@Test public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(PROPERTY_ISO3166_CODES, "US-CA"); ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getIso3166Codes(), ImmutableSet.of("US-CA")); assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } | @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); } | UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); } |
@Test public void testLinkedViewBindsViewAndContextSuppliers() { Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class)))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient")))); } | public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } | ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } } | ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } } | ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); } | ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); } |
@Test public void testLinkedContextBindsContextSupplier() { Injector injector = Guice.createInjector(linkContext(contextFor(IntegrationTestClient.class))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); } | public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } | ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } } | ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } } | ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); } | ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); } |
@Test public void testRangesTail() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.tail(1024); GetOptions expected = new GetOptions(); expected.tail(1024); assertEquals(fn.apply(in), expected); } | @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } |
@Test public void testWhenNextMarkerAbsentDoesntAdvance() { GeneratedHttpRequest request = args(ImmutableList.of()); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { fail("The Iterable should not advance"); return null; } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"))).concat().toSet(), ImmutableSet.of("foo", "bar")); } | @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } |
@Test public void testWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = args(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } | @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } |
@Test public void testWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = args(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } | @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } |
@Test public void testFromCallerWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = callerArgs(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } | @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } |
@Test public void testFromCallerWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = callerArgs(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } | @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } | ArgsToPagedIterable implements
Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); } |
@Test public void testShutdownOnClose() throws IOException { Injector i = Guice.createInjector(); Closer closer = i.getInstance(Closer.class); ListeningExecutorService executor = createMock(ListeningExecutorService.class); ExecutorServiceModule.shutdownOnClose(executor, closer); expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce(); replay(executor); closer.close(); verify(executor); } | static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } | ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } } | ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor,
ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor,
ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService); } | ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor,
ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService); } |
@Test public void testRangesStart() { org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions(); in.startAt(1024); GetOptions expected = new GetOptions(); expected.startAt(1024); assertEquals(fn.apply(in), expected); } | @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } | BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> { @Override public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) { checkNotNull(from, "options"); if (from == org.jclouds.blobstore.options.GetOptions.NONE) return GetOptions.NONE; GetOptions httpOptions = new GetOptions(); if (from.getIfMatch() != null) { httpOptions.ifETagMatches(from.getIfMatch()); } if (from.getIfModifiedSince() != null) { httpOptions.ifModifiedSince(from.getIfModifiedSince()); } if (from.getIfNoneMatch() != null) { httpOptions.ifETagDoesntMatch(from.getIfNoneMatch()); } if (from.getIfUnmodifiedSince() != null) { httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince()); } for (String range : from.getRanges()) { String[] firstLast = range.split("\\-", 2); if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1])); else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty()) httpOptions.tail(Long.parseLong(firstLast[1])); else httpOptions.startAt(Long.parseLong(firstLast[0])); } return httpOptions; } @Override GetOptions apply(org.jclouds.blobstore.options.GetOptions from); } |
@Test public void test() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("zone1", "zone2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "zone1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "zone2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.ZONE).id("zone1").description("zone1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.ZONE).id("zone2").description("zone2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } | @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } |
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoZones() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); fn.get(); } | @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } | ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } |
@Test public void test() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "region1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "region2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.REGION).id("region1").description("region1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.REGION).id("region2").description("region2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } | @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } |
@Test(expectedExceptions = IllegalStateException.class) public void testWhenNoRegions() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); fn.get(); } | @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } | RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); } |
@Test public void testGetAll() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("zone1", "zone2", "zone3")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region1, region2, zone1, zone2, zone3)); } | @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); } |
@Test public void testRegionAndZoneFilter() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.<String> of("zone2")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region2, zone2)); } | @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); } | ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,
@Zone Supplier<Set<String>> zoneIdsSupplier,
@Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); } |
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "region eu-central-1 is not in the configured region to zone mappings: .*") public void zoneToRegionMappingsInconsistentOnKeys() { Map<String, Supplier<URI>> regionIdToURIs = Maps.newLinkedHashMap(); regionIdToURIs.put("us-east-1", Suppliers.ofInstance(URI.create("ec2.us-east-1.amazonaws.com"))); regionIdToURIs.put("eu-central-1", Suppliers.ofInstance(URI.create("ec2.eu-central-1.amazonaws.com"))); Map<String, Supplier<Set<String>>> regionIdToZoneIds = Maps.newLinkedHashMap(); regionIdToZoneIds.put("us-east-1", supplyZoneIds("us-east-1a", "us-east-1b")); new ZoneIdToURIFromJoinOnRegionIdToURI(Suppliers.ofInstance(regionIdToURIs), Suppliers.ofInstance(regionIdToZoneIds)).get(); } | @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } | ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } } | ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } @Inject ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds); } | ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } @Inject ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds); @Override Map<String, Supplier<URI>> get(); } | ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } @Inject ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs,
@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds); @Override Map<String, Supplier<URI>> get(); } |
@Override @Test public void testRfc822DateFormat() { String dsString = dateService.rfc822DateFormat(testData[0].date); assertEquals(dsString, testData[0].rfc822DateString); } | public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } | JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } } | JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } } | JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); } | JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); } |
@Test public void testCorrect() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(new File("foo")); } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } |
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testNullIsIllegal() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(null); } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } | ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); } |
@Test public void testWhenRegionNameIsSameAsProviderName() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("leader"), URI.create("http: } | @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } |
@Test public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("1"), URI.create("http: } | @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply(new File("foo")); } | @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeInRegionMapIfSpecified() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply("2"); } | @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } | RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,
@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); } |
@Test public void testCorrect() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); } |
@Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); } | @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); } | RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); } |
@Override @Test(enabled = false) public void testRfc822DateParse() { Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString); assertEquals(dsDate, testData[0].date); } | public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } | JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } } | JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } } | JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); } | JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); } |
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "properties cannot be null") public void testPropertiesMandatory() { new ExpandProperties().apply(null); } | @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); } |
@Test public void testResolveProperties() { Properties props = new Properties(); props.put("number", 1); props.put("two", "2"); props.put("greeting", "hello"); props.put("simple", "simple: ${greeting}"); props.put("nested", "nested: ${simple}"); props.put("mixed", "mixed: ${nested} and ${simple}"); props.put("unexisting", "${foobar} substitution"); props.put("recursive", "variable5 ${recursive} recursive ${unexisting}"); props.put("characters{{$$", "characters"); props.put("ugly", "substitute: ${characters{{$$}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("number"), 1); assertEquals(resolved.get("two"), "2"); assertEquals(resolved.get("greeting"), "hello"); assertEquals(resolved.get("simple"), "simple: hello"); assertEquals(resolved.get("nested"), "nested: simple: hello"); assertEquals(resolved.get("mixed"), "mixed: nested: simple: hello and simple: hello"); assertEquals(resolved.get("unexisting"), "${foobar} substitution"); assertEquals(resolved.get("recursive"), "variable5 ${recursive} recursive ${unexisting}"); assertEquals(resolved.get("ugly"), "substitute: characters"); } | @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } | ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } } | ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } } | ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } @Override Properties apply(final Properties properties); } | ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } @Override Properties apply(final Properties properties); } |
@Test public void testNoLeafs() { Properties props = new Properties(); props.put("one", "${two}"); props.put("two", "${one}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("one"), "${two}"); assertEquals(resolved.get("two"), "${one}"); } | @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); } | ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); } |
@Test public void testIterableLong() { String list = new JoinOnComma().apply(ImmutableList.of(1L, 2L)); assertEquals(list, "1,2"); } | public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } |
@Test public void testLongArray() { String list = new JoinOnComma().apply(new long[] { 1L, 2L }); assertEquals(list, "1,2"); } | public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyArrayIllegalArgumentException() { new JoinOnComma().apply(new long[] {}); } | public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIterableIllegalArgumentException() { new JoinOnComma().apply(ImmutableList.of()); } | public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } |
@Test(expectedExceptions = NullPointerException.class) public void testNullPointer() { new JoinOnComma().apply(null); } | public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } | JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); } |
@Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new UserAuthException(""), ""); } | @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } | SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } } | SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,
LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); } | SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,
LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override ExecChannel execChannel(String command); @Override String getHostAddress(); @Override String getUsername(); } | SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,
LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override ExecChannel execChannel(String command); @Override String getHostAddress(); @Override String getUsername(); } |
@Test public void testAddExecutorServiceModuleIfNotPresent() { List<Module> modules = Lists.newArrayList(); ExecutorServiceModule module = new ExecutorServiceModule(); modules.add(module); ContextBuilder.addExecutorServiceIfNotPresent(modules); assertEquals(modules.size(), 1); assertEquals(modules.remove(0), module); } | @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } | ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } } | ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } protected ContextBuilder(ProviderMetadata providerMetadata); protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata); ContextBuilder(ApiMetadata apiMetadata); } | ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } protected ContextBuilder(ProviderMetadata providerMetadata); protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata); ContextBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(String providerOrApi); static ContextBuilder newBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(ProviderMetadata providerMetadata); @Override String toString(); ContextBuilder name(String name); ContextBuilder credentialsSupplier(Supplier<Credentials> credentialsSupplier); ContextBuilder credentials(String identity, @Nullable String credential); ContextBuilder endpoint(String endpoint); ContextBuilder apiVersion(String apiVersion); ContextBuilder buildVersion(String buildVersion); ContextBuilder modules(Iterable<? extends Module> modules); ContextBuilder overrides(Properties overrides); static String searchPropertiesForProviderScopedProperty(Properties mutable, String prov, String key); Injector buildInjector(); static Injector buildInjector(String name, ProviderMetadata providerMetadata, Supplier<Credentials> creds, List<Module> inputModules); @SuppressWarnings("unchecked") C build(); V build(Class<V> viewType); V buildView(Class<V> viewType); @SuppressWarnings("unchecked") V buildView(TypeToken<V> viewType); @SuppressWarnings("unchecked") C build(TypeToken<C> contextType); A buildApi(Class<A> api); @SuppressWarnings("unchecked") A buildApi(TypeToken<A> apiType); ApiMetadata getApiMetadata(); } | ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } protected ContextBuilder(ProviderMetadata providerMetadata); protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata); ContextBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(String providerOrApi); static ContextBuilder newBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(ProviderMetadata providerMetadata); @Override String toString(); ContextBuilder name(String name); ContextBuilder credentialsSupplier(Supplier<Credentials> credentialsSupplier); ContextBuilder credentials(String identity, @Nullable String credential); ContextBuilder endpoint(String endpoint); ContextBuilder apiVersion(String apiVersion); ContextBuilder buildVersion(String buildVersion); ContextBuilder modules(Iterable<? extends Module> modules); ContextBuilder overrides(Properties overrides); static String searchPropertiesForProviderScopedProperty(Properties mutable, String prov, String key); Injector buildInjector(); static Injector buildInjector(String name, ProviderMetadata providerMetadata, Supplier<Credentials> creds, List<Module> inputModules); @SuppressWarnings("unchecked") C build(); V build(Class<V> viewType); V buildView(Class<V> viewType); @SuppressWarnings("unchecked") V buildView(TypeToken<V> viewType); @SuppressWarnings("unchecked") C build(TypeToken<C> contextType); A buildApi(Class<A> api); @SuppressWarnings("unchecked") A buildApi(TypeToken<A> apiType); ApiMetadata getApiMetadata(); } |
@Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); } | public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } | Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } } | Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } } | Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } static Function<ApiMetadata, String> idFunction(); static Iterable<ApiMetadata> all(); static ApiMetadata withId(String id); static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type); static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type); static Iterable<ApiMetadata> viewableAs(Class<? extends View> type); static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view); } | Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } static Function<ApiMetadata, String> idFunction(); static Iterable<ApiMetadata> all(); static ApiMetadata withId(String id); static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type); static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type); static Iterable<ApiMetadata> viewableAs(Class<? extends View> type); static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view); } |
@SuppressWarnings("rawtypes") @Test public void testGetProviderMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(3, providerMetadataList.size()); assertTrue(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } | public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } |
@SuppressWarnings("rawtypes") @Test public void testGetProviderMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreProviderMetadata.class.getName())).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(2, providerMetadataList.size()); assertFalse(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } | public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } | MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } |
@SuppressWarnings("rawtypes") @Test public void testGetApiMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( JcloudsTestBlobStoreApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(3, apiMetadataList.size()); assertTrue(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); } | public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } |
@SuppressWarnings("rawtypes") @Test public void testGetApiMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreApiMetadata.class.getName())).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(2, apiMetadataList.size()); assertFalse(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); } | public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } | MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); } |
@SuppressWarnings("rawtypes") @Test public void testInstantiateAvailableClassesWhenAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.providers.JcloudsTestComputeProviderMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestComputeProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } | public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); static ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames,
Class<T> type); static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); static ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames,
Class<T> type); static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle); } |
@SuppressWarnings("rawtypes") @Test public void testInstantiateAvailableClassesWhenNotAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.apis.JcloudsTestComputeApiMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } | public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); static ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames,
Class<T> type); static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle); } | Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); static ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames,
Class<T> type); static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlock("a.0.0.0/0").build()); } | public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlock("a.0.0.0/0").build()); } | public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); } | public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } |
@Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); } | public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } | IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); } |
@Test public void testCompareProtocol() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission tcp2 = builder().ipProtocol(IpProtocol.TCP).build(); assertEqualAndComparable(tcp, tcp2); final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build(); assertOrder(tcp, udp); final IpPermission t10 = builder().fromPermission(tcp).fromPort(10).build(); final IpPermission t20 = builder().fromPermission(tcp).fromPort(20).build(); final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build(); final IpPermission t0to10 = builder().fromPermission(tcp).toPort(10).build(); final IpPermission t0to20 = builder().fromPermission(tcp).toPort(20).build(); assertTotalOrder(ImmutableList.of(tcp, t0to10, t0to20, t10, t20, udp, u10)); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test void testConvertWithContent() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn("hello".getBytes()).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(Strings2.toStringAndClose(response.getPayload().openStream()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); } | @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } | ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } } | ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } @Inject ConvertToJcloudsResponse(ContentMetadataCodec contentMetadataCodec); } | ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } @Inject ConvertToJcloudsResponse(ContentMetadataCodec contentMetadataCodec); @Override HttpResponse apply(HTTPResponse gaeResponse); } | ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } @Inject ConvertToJcloudsResponse(ContentMetadataCodec contentMetadataCodec); @Override HttpResponse apply(HTTPResponse gaeResponse); } |
@Test public void testCompareTenantIdGroupNamePairs() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission g1 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1").build(); final IpPermission g2 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group2").build(); final IpPermission g12 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1") .tenantIdGroupNamePair("tenant1", "group2").build(); final IpPermission g21 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group2") .tenantIdGroupNamePair("tenant1", "group1").build(); final IpPermission t2g1 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant2", "group1").build(); assertTotalOrder(ImmutableList.of(tcp, g1, g12, g2, g21, t2g1)); final IpPermission g12b = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1") .tenantIdGroupNamePair("tenant1", "group2").build(); assertEqualAndComparable(g12, g12b); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void testCompareGroupIds() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission aa = builder().fromPermission(tcp) .groupId("a").build(); final IpPermission a = builder().fromPermission(tcp) .groupId("a").build(); final IpPermission ab = builder().fromPermission(tcp) .groupId("a") .groupId("b").build(); final IpPermission ba = builder().fromPermission(tcp) .groupId("b") .groupId("a").build(); assertTotalOrder(ImmutableList.of(tcp, a, ab, ba)); assertEqualAndComparable(a, aa); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void testCompareCidrBlocks() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission everything = builder().fromPermission(tcp) .cidrBlock("0.0.0.0/0").build(); final IpPermission universal = builder().fromPermission(tcp) .cidrBlock("0.0.0.0/0").build(); assertEqualAndComparable(everything, universal); final IpPermission localhost = builder().fromPermission(tcp) .cidrBlock("127.0.0.1/32").build(); final IpPermission tenTwentyOne = builder().fromPermission(tcp) .cidrBlock("10.0.0.21/32").build(); final IpPermission tenTwoHundred = builder().fromPermission(tcp) .cidrBlock("10.0.0.200/32").build(); assertOrder(tenTwoHundred, tenTwentyOne); assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost)); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void testCompareExclusionCidrBlocks() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission everything = builder().fromPermission(tcp) .exclusionCidrBlock("0.0.0.0/0").build(); final IpPermission universal = builder().fromPermission(tcp) .exclusionCidrBlock("0.0.0.0/0").build(); assertEqualAndComparable(everything, universal); final IpPermission localhost = builder().fromPermission(tcp) .exclusionCidrBlock("127.0.0.1/32").build(); final IpPermission stillLocal = builder().fromPermission(tcp) .exclusionCidrBlock("127.0.0.1/32").build(); assertEqualAndComparable(localhost, stillLocal); final IpPermission tenTwentyOne = builder().fromPermission(tcp) .exclusionCidrBlock("10.0.0.21/32").build(); final IpPermission tenTwoHundred = builder().fromPermission(tcp) .exclusionCidrBlock("10.0.0.200/32").build(); assertOrder(tenTwoHundred, tenTwentyOne); assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost)); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void testPairwise() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build(); final IpPermission f10 = builder().fromPermission(tcp).fromPort(10).build(); final IpPermission f20 = builder().fromPermission(tcp).fromPort(20).build(); final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build(); final IpPermission t20 = builder().fromPermission(f10).toPort(20).build(); final IpPermission t30 = builder().fromPermission(f10).toPort(30).build(); final IpPermission t2g1 = builder().fromPermission(t20) .tenantIdGroupNamePair("tenant1", "group1") .build(); final IpPermission t2g2 = builder().fromPermission(t20) .tenantIdGroupNamePair("tenant1", "group2") .build(); final IpPermission gidA = builder().fromPermission(t2g1) .groupId("groupA") .build(); final IpPermission gidB = builder().fromPermission(t2g1) .groupId("groupB") .build(); final IpPermission cidr10 = builder().fromPermission(gidA) .cidrBlock("10.10.10.10/32") .build(); final IpPermission cidr20 = builder().fromPermission(gidA) .cidrBlock("10.10.10.20/32") .build(); final IpPermission ex10 = builder().fromPermission(cidr10) .exclusionCidrBlock("172.16.10.10/32") .build(); final IpPermission ex20 = builder().fromPermission(cidr10) .exclusionCidrBlock("172.16.10.20/32") .build(); assertTotalOrder(ImmutableList.of( tcp, f10, t20, t2g1, gidA, cidr10, ex10, ex20, cidr20, gidB, t2g2, t30, f20, udp, u10 )); } | public static Builder builder() { return new Builder(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,
Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void testInitScriptPattern() throws Exception { InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create(); config.initScriptPattern("/var/tmp/jclouds-%s"); assertEquals(config.getBasedir(), "/var/tmp"); assertEquals(config.getInitScriptPattern(), "/var/tmp/jclouds-%s"); } | @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } | InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } } | InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); } | InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); static InitScriptConfigurationForTasks create(); @Inject(optional = true) InitScriptConfigurationForTasks initScriptPattern(
@Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern); InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames(); InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames(); String getBasedir(); String getInitScriptPattern(); Supplier<String> getAnonymousTaskSuffixSupplier(); } | InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); static InitScriptConfigurationForTasks create(); @Inject(optional = true) InitScriptConfigurationForTasks initScriptPattern(
@Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern); InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames(); InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames(); String getBasedir(); String getInitScriptPattern(); Supplier<String> getAnonymousTaskSuffixSupplier(); static final String PROPERTY_INIT_SCRIPT_PATTERN; } |
@Test(expectedExceptions = NullPointerException.class) public void testRegisterNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.registerImage(null); } | public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } |
@Test(expectedExceptions = NullPointerException.class) public void testRemoveNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.removeImage(null); } | public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } |
@Test public void testRemoveImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); imageCache.removeImage(image.getId()); assertEquals(imageCache.get().size(), 0); } | public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } |
@Test void testConvertRequestGetsTargetAndUri() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getURL().getPath(), "/foo"); } | @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } | ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } } | ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } @Inject ConvertToGaeRequest(HttpUtils utils, ContentMetadataCodec contentMetadataCodec); } | ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } @Inject ConvertToGaeRequest(HttpUtils utils, ContentMetadataCodec contentMetadataCodec); @Override HTTPRequest apply(HttpRequest request); } | ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } @Inject ConvertToGaeRequest(HttpUtils utils, ContentMetadataCodec contentMetadataCodec); @Override HTTPRequest apply(HttpRequest request); static final String USER_AGENT; final Set<String> prohibitedHeaders; } |
@Test public void testLoadImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); } | @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } |
@Test public void testSupplierExpirationReloadsTheCache() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS); assertEquals(imageCache.get().size(), 1); assertFalse(any(imageCache.get(), idEquals("foo"))); } | @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } | ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,
AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); } |
@Test public void testRespectsTimeout() throws Exception { final long timeoutMs = 1000; OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeRunning, userExecutor); Stopwatch stopwatch = Stopwatch.createUnstarted(); stopwatch.start(); try { finder.findOpenSocketOnNode(node, 22, timeoutMs, MILLISECONDS); fail(); } catch (NoSuchElementException success) { } long timetaken = stopwatch.elapsed(MILLISECONDS); assertTrue(timetaken >= timeoutMs - EARLY_GRACE && timetaken <= timeoutMs + SLOW_GRACE, "timetaken=" + timetaken); } | @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |
@Test public void testReturnsReachable() throws Exception { SocketOpen secondSocketOpen = new SocketOpen() { @Override public boolean apply(HostAndPort input) { return HostAndPort.fromParts(PRIVATE_IP, 22).equals(input); } }; OpenSocketFinder finder = new ConcurrentOpenSocketFinder(secondSocketOpen, nodeRunning, userExecutor); HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22)); } | @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |
@Test public void testChecksSocketsConcurrently() throws Exception { ControllableSocketOpen socketTester = new ControllableSocketOpen(ImmutableMap.of( HostAndPort.fromParts(PUBLIC_IP, 22), new SlowCallable<Boolean>(true, 1500), HostAndPort.fromParts(PRIVATE_IP, 22), new SlowCallable<Boolean>(true, 1000))); OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketTester, nodeRunning, userExecutor); HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22)); } | @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |
@Test public void testAbortsWhenNodeNotRunning() throws Exception { OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeNotRunning, userExecutor) { @Override protected <T> Predicate<T> retryPredicate(final Predicate<T> findOrBreak, long timeout, long period, TimeUnit timeUnits) { return new Predicate<T>() { @Override public boolean apply(T input) { try { findOrBreak.apply(input); fail("should have thrown IllegalStateException"); } catch (IllegalStateException e) { } return false; } }; } }; try { finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); fail(); } catch (NoSuchElementException e) { } } | @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |
@Test public void testSocketFinderAllowedInterfacesAll() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.ALL); assertTrue(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } | @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |
@Test public void testSocketFinderAllowedInterfacesPrivate() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE); assertFalse(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } | @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } | ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester,
@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); } |