Skip to content

Commit

Permalink
fixes NullPointerException when handling a List with a null item
Browse files Browse the repository at this point in the history
  • Loading branch information
cfieber committed Sep 23, 2015
1 parent 496546d commit b733482
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,24 @@ private static Optional<List<Object>> notEmpty(List<Object> properties) {
return Optional.ofNullable(properties).filter(v -> !v.isEmpty());
}

private static <R> Optional<R> firstValue(List<Object> properties, Function<Object, R> transform) {
return notEmpty(properties).map(v -> transform.apply(v.get(0)));
/**
* Extracts and transforms the first item from a list.
*
* @param properties
* The list of properties to filter, may be null or empty
* @param transform
* The transform to apply to the extracted list item. The
* transform is only applied if the list contains a non-null
* item at index 0.
* @param <R>
* The transform return type
* @return
* The transformed value, or Optional.empty() if there is no
* non-null item at index 0 of the list.
*/
//VisibleForTesting
static <R> Optional<R> firstValue(List<Object> properties, Function<Object, R> transform) {
return notEmpty(properties).map(v -> v.get(0)).map(transform::apply);
}

private static boolean isError(AWSRequestMetrics metrics) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -88,4 +89,12 @@ public void testMetricCollection() {
assertTrue(expectedCounter.isPresent());
assertEquals(12345L, expectedCounter.get().count());
}

@Test
public void testListFiltering() {
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(null, Object::toString));
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(Collections.emptyList(), Object::toString));
assertEquals(Optional.of("1"), SpectatorRequestMetricCollector.firstValue(Collections.singletonList(1L), Object::toString));
assertEquals(Optional.empty(), SpectatorRequestMetricCollector.firstValue(Collections.singletonList(null), Object::toString));
}
}

0 comments on commit b733482

Please sign in to comment.