ReduceHandler implements OutputOperationHandler<Reduce<T>, T> { @Override public T doOperation(final Reduce<T> operation, final Context context, final Store store) throws OperationException { if (null == operation) { throw new OperationException("Operation cannot be null"); } Iterable<? extends T> input = operation.getInput(); if (null == input) { throw new OperationException("Input cannot be null"); } final T identity = operation.getIdentity(); final BinaryOperator aggregateFunction = operation.getAggregateFunction(); return (T) Streams.toStream(input) .reduce(identity, aggregateFunction, aggregateFunction); }  @Override T doOperation(final Reduce<T> operation, final Context context, final Store store);  }
@Test public void shouldAggregateResults() throws Exception { final List<Integer> input = Arrays.asList(1, 2, 3, 4, 5); final Integer expectedResult = 15; final Reduce<Integer> reduce = new Reduce.Builder<Integer>() .input(input) .aggregateFunction(new Sum()) .build(); final ReduceHandler<Integer> handler = new ReduceHandler<>(); final Integer result = handler.doOperation(reduce, null, null); assertTrue(result instanceof Integer); assertEquals(expectedResult, result); }
@Test public void shouldAggregateResultsWithIdentity() throws Exception { final List<Integer> input = Arrays.asList(1, 2, 3, 4, 5); final Integer identity = 10; final Integer expectedResult = 10; final Reduce<Integer> reduce = new Reduce.Builder<Integer>() .input(input) .identity(10) .aggregateFunction(new Max()) .build(); final ReduceHandler<Integer> handler = new ReduceHandler<>(); final Integer result = handler.doOperation(reduce, null, null); assertTrue(result instanceof Integer); assertEquals(expectedResult, result); }
@Test public void shouldAggregateResultsWithNullIdentity() throws Exception { final List<Integer> input = Arrays.asList(1, 2, 3, 4, 5); final Integer expectedResult = 5; final Reduce<Integer> reduce = new Reduce.Builder<Integer>() .input(input) .identity(null) .aggregateFunction(new Max()) .build(); final ReduceHandler<Integer> handler = new ReduceHandler<>(); final Integer result = handler.doOperation(reduce, null, null); assertTrue(result instanceof Integer); assertEquals(expectedResult, result); }
@Test public void shouldHandleNullInput() throws Exception { final Iterable<Integer> input = null; final Reduce<Integer> reduce = new Reduce.Builder<Integer>() .input(input) .build(); final ReduceHandler<Integer> handler = new ReduceHandler<>(); try { final Integer result = handler.doOperation(reduce, null, null); } catch (final OperationException oe) { assertThat(oe.getMessage(), is("Input cannot be null")); } }
@Test public void shouldHandleNullOperation() throws Exception { final ReduceHandler<Integer> handler = new ReduceHandler<>(); try { final Integer result = handler.doOperation(null, null, null); } catch (final OperationException oe) { assertThat(oe.getMessage(), is("Operation cannot be null")); } }