src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
AdaptedPredicate extends InputAdapted<I, PI> implements Predicate<I> { public Predicate<PI> getPredicate() { return predicate; } AdaptedPredicate(); AdaptedPredicate(final Function<I, PI> inputAdapter, final Predicate<PI> predicate); @Override boolean test(final I input); Predicate<PI> getPredicate(); void setPredicate(final Predicate<PI> predicate); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final AdaptedPredicate original = new AdaptedPredicate(new ToString(), new IsEqual("3")); final String serialised = JsonSerialiser.serialise(original); String expected = "{" + "\"inputAdapter\":{" + "\"class\":\"uk.gov.gchq.koryphe.impl.function.ToString\"" + "}," + "\"predicate\":{" + "\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsEqual\"," + "\"value\":\"3\"" + "}" + "}"; assertEquals(expected, serialised); final AdaptedPredicate deserialised = JsonSerialiser.deserialise(serialised, AdaptedPredicate.class); assertEquals(original.getPredicate().getClass(), deserialised.getPredicate().getClass()); assertEquals(original.getInputAdapter().getClass(), deserialised.getInputAdapter().getClass()); assertEquals(((IsEqual) original.getPredicate()).getControlValue(), ((IsEqual) deserialised.getPredicate()).getControlValue()); }
ExtractValue extends KorypheFunction<Map<K, V>, V> { public K getKey() { return key; } ExtractValue(); ExtractValue(final K key); K getKey(); void setKey(final K key); @Override V apply(final Map<K, V> map); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final ExtractValue<String, Integer> function = new ExtractValue<>("test"); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.ExtractValue\",%n" + " \"key\" : \"test\"%n" + "}"), json); final ExtractValue deserialised = JsonSerialiser.deserialise(json, ExtractValue.class); assertNotNull(deserialised); assertEquals("test", deserialised.getKey()); }
ExtractValue extends KorypheFunction<Map<K, V>, V> { @Override public V apply(final Map<K, V> map) { return null == map ? null : map.get(key); } ExtractValue(); ExtractValue(final K key); K getKey(); void setKey(final K key); @Override V apply(final Map<K, V> map); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldExtractCorrectValueFromMap() { final ExtractValue<String, Integer> function = new ExtractValue<>("secondKey"); final Map<String, Integer> input = new HashMap<>(); input.put("firstKey", 1); input.put("secondKey", 3); input.put("thirdKey", 6); input.put("second", 12); final Integer result = function.apply(input); assertEquals(3, result); } @Test public void shouldThrowExceptionForEmptyInput() { final ExtractValue<String, Integer> function = new ExtractValue<>(); final Integer result = function.apply(null); assertNull(result); }
MultiplyLongBy extends KorypheFunction<Long, Long> { public Long apply(final Long input) { if (null == input) { return null; } else { return input * by; } } MultiplyLongBy(); MultiplyLongBy(final long by); long getBy(); void setBy(final long by); Long apply(final Long input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldMultiplyBy2() { final MultiplyLongBy function = new MultiplyLongBy(2L); long output = function.apply(4L); assertEquals(8L, output); } @Test public void shouldMultiplyBy1IfByIsNotSet() { final MultiplyLongBy function = new MultiplyLongBy(); long output = function.apply(9L); assertEquals(9L, output); } @Test public void shouldReturnNullIfInputIsNull() { final MultiplyLongBy function = new MultiplyLongBy(2L); Long output = function.apply(null); assertNull(output); }
MultiplyLongBy extends KorypheFunction<Long, Long> { public long getBy() { return by; } MultiplyLongBy(); MultiplyLongBy(final long by); long getBy(); void setBy(final long by); Long apply(final Long input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final MultiplyLongBy function = new MultiplyLongBy(4L); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.MultiplyLongBy\",%n" + " \"by\" : 4%n" + "}"), json); final MultiplyLongBy deserialisedMultiplyLongBy = JsonSerialiser.deserialise(json, MultiplyLongBy.class); assertNotNull(deserialisedMultiplyLongBy); assertEquals(4L, deserialisedMultiplyLongBy.getBy()); }
CsvToMaps extends KorypheFunction<String, Iterable<Map<String, Object>>> implements Serializable { @Override public Iterable<Map<String, Object>> apply(final String csv) { if (isNull(csv)) { return null; } try { final CSVParser csvParser = new CSVParser(new StringReader(csv), getCsvFormat()); final CloseableIterable<CSVRecord> csvRecords = IterableUtil.limit(csvParser.getRecords(), firstRow, null, false); return IterableUtil.map(csvRecords, (item) -> extractMap((CSVRecord) item)); } catch (final IOException e) { throw new RuntimeException("Unable to parse csv", e); } } @Override Iterable<Map<String, Object>> apply(final String csv); List<String> getHeader(); void setHeader(final List<String> header); int getFirstRow(); void setFirstRow(final int firstRow); CsvToMaps firstRow(final int firstRow); CsvToMaps header(final String... header); CsvToMaps header(final Collection<String> header); char getDelimiter(); void setDelimiter(final char delimiter); CsvToMaps delimiter(final char delimiter); boolean isQuoted(); void setQuoted(final boolean quoted); CsvToMaps quoted(); CsvToMaps quoted(final boolean quoted); char getQuoteChar(); void setQuoteChar(final char quoteChar); CsvToMaps quoteChar(final char quoteChar); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnNullForNullInput() { final CsvToMaps function = new CsvToMaps(); Object result = function.apply(null); assertNull(result); }
Multiply extends KorypheFunction2<Integer, Integer, Integer> { @Override public Integer apply(final Integer input1, final Integer input2) { if (input2 == null) { return input1; } else if (input1 == null) { return null; } else { return input1 * input2; } } @Override Integer apply(final Integer input1, final Integer input2); }
@Test public void shouldMultiply2() { final Multiply function = new Multiply(); final int output = function.apply(4, 2); assertEquals(8, output); } @Test public void shouldMultiply1IfSecondIsNull() { final Multiply function = new Multiply(); final int output = function.apply(9, null); assertEquals(9, output); } @Test public void shouldMultiply1IfFirstIsNull() { final Multiply function = new Multiply(); final Integer output = function.apply(null, 9); assertEquals(null, output); }
PredicateMap extends KoryphePredicate<Map<?, T>> { @Override public boolean test(final Map<?, T> map) { if (null == predicate) { return true; } if (null == map) { return false; } try { return predicate.test(map.get(key)); } catch (final ClassCastException e) { throw new IllegalArgumentException("Input does not match parametrised type", e); } } PredicateMap(); PredicateMap(final Object key, final Predicate<? super T> predicate); @Override boolean test(final Map<?, T> map); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate<? super T> getPredicate(); void setPredicate(final Predicate<? super T> predicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getKey(); void setKey(final Object key); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenNotPredicateGiven() { final PredicateMap<String> mapFilter = new PredicateMap<>(KEY1, null); boolean accepted = mapFilter.test(map); assertTrue(accepted); } @Test public void shouldAcceptWhenPredicateAccepts() { final PredicateMap<String> mapFilter = new PredicateMap<>(KEY1, predicate); given(predicate.test(VALUE1)).willReturn(true); boolean accepted = mapFilter.test(map); assertTrue(accepted); } @Test public void shouldRejectWhenPredicateRejects() { final PredicateMap<String> mapFilter = new PredicateMap<>(KEY1, predicate); given(predicate.test(VALUE1)).willReturn(false); boolean accepted = mapFilter.test(map); assertFalse(accepted); } @Test public void shouldNotErrorWhenKeyIsNotPresentForPredicate() { final PredicateMap<String> mapFilter = new PredicateMap<>(KEY2, predicate); given(predicate.test(null)).willReturn(false); boolean accepted = mapFilter.test(map); assertFalse(accepted); } @Test public void shouldRejectNullMaps() { final PredicateMap<String> mapFilter = new PredicateMap<>(KEY1, predicate); boolean accepted = mapFilter.test(null); assertFalse(accepted); }
IsEmpty extends KorypheFunction<Iterable, Boolean> { @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") public Boolean apply(final Iterable input) { if (null == input) { throw new IllegalArgumentException("Input cannot be null"); } try { return Iterables.isEmpty(input); } finally { CloseableUtil.close(input); } } @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") Boolean apply(final Iterable input); }
@Test public void shouldReturnTrueForEmptyIterable() { final IsEmpty function = new IsEmpty(); final Iterable input = Sets.newHashSet(); final Boolean result = function.apply(input); assertTrue(result); } @Test public void shouldReturnFalseForPopulatedIterable() { final IsEmpty function = new IsEmpty(); final Iterable input = Arrays.asList(3, 1, 4, 1, 6); final Boolean result = function.apply(input); assertFalse(result); } @Test public void shouldReturnFalseForNullElements() { final IsEmpty function = new IsEmpty(); final Iterable input = Arrays.asList(null, null); final Boolean result = function.apply(input); assertFalse(result); } @Test public void shouldThrowExceptionForNullInput() { final IsEmpty function = new IsEmpty(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertEquals("Input cannot be null", exception.getMessage()); }
IterableLongest extends KorypheFunction<Iterable<?>, Object> { @Override public Object apply(final Iterable<?> items) { if (nonNull(items)) { return getLongest(items); } return null; } IterableLongest(); @Override Object apply(final Iterable<?> items); }
@Test public void shouldHandleNullInput() { final IterableLongest function = getInstance(); final Object result = function.apply(null); assertNull(result); } @Test public void shouldGetLongestItemFromList() { final IterableLongest function = getInstance(); final List<String> list = Lists.newArrayList("a", "ab", "abc"); final Object result = function.apply(list); assertEquals("abc", result); }
ToInteger extends KorypheFunction<Object, Integer> { @Override public Integer apply(final Object value) { if (null == value) { return null; } if (value instanceof Number) { return ((Number) value).intValue(); } if (value instanceof String) { return Integer.valueOf(((String) value)); } throw new IllegalArgumentException("Could not convert value to Integer: " + value); } @Override Integer apply(final Object value); }
@Test public void shouldConvertToInteger() { final ToInteger function = new ToInteger(); Object output = function.apply(new Long(5)); assertEquals(5, output); assertEquals(Integer.class, output.getClass()); }
ToList extends KorypheFunction<Object, List<?>> { @Override public List<?> apply(final Object value) { if (null == value) { return Lists.newArrayList((Object) null); } if (value instanceof Object[]) { return Lists.newArrayList((Object[]) value); } if (value instanceof Iterable) { if (value instanceof List) { return (List<?>) value; } return Lists.newArrayList((Iterable) value); } return Lists.newArrayList(value); } @Override List<?> apply(final Object value); }
@Test public void shouldConvertNullToList() { final ToList function = new ToList(); final Object result = function.apply(null); assertEquals(Lists.newArrayList((Object) null), result); } @Test public void shouldConvertStringToList() { final ToList function = new ToList(); final Object value = "value1"; final Object result = function.apply(value); assertEquals(Lists.newArrayList(value), result); } @Test public void shouldConvertArrayToList() { final ToList function = new ToList(); final Object value = new String[] {"value1", "value2"}; final Object result = function.apply(value); assertEquals(Lists.newArrayList((Object[]) value), result); } @Test public void shouldConvertSetToList() { final ToList function = new ToList(); final Set<String> value = Sets.newLinkedHashSet(Arrays.asList("value1", "value2")); final Object result = function.apply(value); assertEquals(Lists.newArrayList(value), result); } @Test public void shouldReturnAGivenList() { final ToList function = new ToList(); final Object value = Lists.newArrayList("value1", "value2"); final Object result = function.apply(value); assertSame(value, result); }
ReverseString extends KorypheFunction<String, String> { @Override public String apply(final String value) { return StringUtils.reverse(value); } @Override String apply(final String value); }
@Test public void shouldHandleNullInput() { final ReverseString function = new ReverseString(); final String result = function.apply(null); assertNull(result); } @Test public void shouldReverseString() { final ReverseString function = new ReverseString(); final String input = "12345"; final String result = function.apply(input); assertEquals("54321", result); }
ToNull extends KorypheFunction<Object, Object> { @Override public Object apply(final Object value) { return null; } @Override Object apply(final Object value); }
@Test public void shouldReturnNullWhenValueIsNotNull() { final ToNull function = new ToNull(); final Object output = function.apply("test"); assertNull(output); } @Test public void shouldReturnNullWhenValueIsNull() { final ToNull function = new ToNull(); final Object output = function.apply(null); assertNull(output); }
StringAppend extends KorypheFunction<String, String> { @Override public String apply(final String value) { if (null == value) { return null; } if (null == suffix) { return value; } return value + suffix; } StringAppend(); StringAppend(final String suffix); @Override String apply(final String value); String getSuffix(); void setSuffix(final String suffix); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringAppend function = new StringAppend("!"); final String result = function.apply(null); assertNull(result); } @Test public void shouldHandleNullSuffix() { final StringAppend function = new StringAppend(null); final String result = function.apply("Hello"); assertEquals("Hello", result); } @Test public void shouldAppendStringToInput() { final StringAppend function = new StringAppend("!"); final String result = function.apply("Hello"); assertEquals("Hello!", result); } @Test public void shouldHandleUnsetSuffix() { final StringAppend function = new StringAppend(); final String result = function.apply("Hello"); assertEquals("Hello", result); }
CallMethod extends KorypheFunction<Object, Object> { @Override public Object apply(final Object obj) { if (null == obj) { return null; } Class clazz = obj.getClass(); Method method = cache.get(clazz); if (null == method) { method = getMethodFromClass(clazz); Map<Class, Method> newCache = new HashMap<>(cache); newCache.put(clazz, method); cache = newCache; } try { return method.invoke(obj); } catch (final IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Unable to invoke " + getMethod() + " on object class " + clazz, e); } } CallMethod(); CallMethod(final String method); String getMethod(); void setMethod(final String method); @Override Object apply(final Object obj); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldCallMethod() { final CallMethod function = new CallMethod(TEST_METHOD); final Object output = function.apply(this); assertEquals(5, output); }
CallMethod extends KorypheFunction<Object, Object> { public String getMethod() { return method; } CallMethod(); CallMethod(final String method); String getMethod(); void setMethod(final String method); @Override Object apply(final Object obj); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final CallMethod function = new CallMethod(TEST_METHOD); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.CallMethod\",%n" + " \"method\" : \"testMethod\"%n" + "}"), json); final CallMethod deserialisedCallMethod = JsonSerialiser.deserialise(json, CallMethod.class); assertNotNull(deserialisedCallMethod); assertEquals(TEST_METHOD, deserialisedCallMethod.getMethod()); }
Size extends KorypheFunction<Iterable, Integer> { @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") public Integer apply(final Iterable input) { if (null == input) { throw new IllegalArgumentException("Input cannot be null"); } try { return Iterables.size(input); } finally { CloseableUtil.close(input); } } @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") Integer apply(final Iterable input); }
@Test public void shouldReturnSizeForGivenIterable() { final Size function = new Size(); final Iterable input = Arrays.asList(1, 2, 3, 4, 5); final int result = function.apply(input); assertEquals(5, result); } @Test public void shouldHandleIterableWithNullElement() { final Size function = new Size(); final Iterable<Integer> input = Arrays.asList(1, 2, null, 4, 5); final int result = function.apply(input); assertEquals(5, result); } @Test public void shouldHandleIterableOfAllNullElements() { final Size function = new Size(); final Iterable<Object> input = Arrays.asList(null, null, null); final int result = function.apply(input); assertEquals(3, result); } @Test public void shouldThrowExceptionForNullInput() { final Size function = new Size(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertEquals("Input cannot be null", exception.getMessage()); }
Concat extends KorypheFunction2<Object, Object, String> { @Override public String apply(final Object input1, final Object input2) { if (null == input1) { if (null == input2) { return null; } return String.valueOf(input2); } if (null == input2) { return String.valueOf(input1); } return input1 + separator + input2; } Concat(); Concat(final String separator); @Override String apply(final Object input1, final Object input2); String getSeparator(); void setSeparator(final String separator); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldConcatStringsWithDefaultSeparator() { final Concat concat = new Concat(); String output = concat.apply("1", "2"); assertEquals("1,2", output); } @Test public void shouldConvertNullValuesToEmptyStringWhenConcatenating() { final Concat concat = new Concat(); final String output = concat.apply("1", null); assertEquals("1", output); } @Test public void shouldReturnNullForNullInput() { final Concat concat = new Concat(); final String output = concat.apply(null, null); assertNull(output); }
ParseDate extends KorypheFunction<String, Date> { @Override public Date apply(final String dateString) { if (isNull(dateString)) { return null; } try { final Date date; if (isNull(format)) { date = DateUtil.parse(dateString, timeZone); } else { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); if (nonNull(timeZone)) { simpleDateFormat.setTimeZone(timeZone); } date = simpleDateFormat.parse(dateString); } return date; } catch (final ParseException e) { throw new IllegalArgumentException("Date string could not be parsed: " + dateString, e); } } ParseDate(); @Override Date apply(final String dateString); String getFormat(); void setFormat(final String format); ParseDate format(final String format); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneAsString(); @JsonSetter void setTimeZone(final String timeZone); void setTimeZone(final TimeZone timeZone); ParseDate timeZone(final String timeZone); ParseDate timeZone(final TimeZone timeZone); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldParseDate() throws ParseException { final ParseDate function = new ParseDate(); final String input = "2000-01-02 03:04:05.006"; final Date result = function.apply(input); assertEquals(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(input), result); } @Test public void shouldReturnNullForNullInput() { final ParseDate function = new ParseDate(); final Object result = function.apply(null); assertNull(result); }
IterableFlatten extends KorypheFunction<Iterable<I_ITEM>, I_ITEM> { @Override public I_ITEM apply(final Iterable<I_ITEM> items) { if (nonNull(items) && nonNull(operator)) { return StreamSupport.stream(items.spliterator(), false) .onClose(() -> CloseableUtil.close(items)) .reduce(operator) .orElse(null); } return null; } IterableFlatten(); IterableFlatten(final BinaryOperator<I_ITEM> operator); @Override I_ITEM apply(final Iterable<I_ITEM> items); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") BinaryOperator<I_ITEM> getOperator(); void setOperator(final BinaryOperator<I_ITEM> operator); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final IterableFlatten<?> function = new IterableFlatten<>(); final Object result = function.apply(null); assertNull(result); } @Test public void shouldFlattenIterableNumbers() { final IterableFlatten<Number> function = new IterableFlatten<>(new Sum()); final List<Number> input = Lists.newArrayList(1, 2, 3, 4, 5); final Number result = function.apply(input); assertEquals(15, result); } @Test public void shouldFlattenIterableStrings() { final IterableFlatten<String> function = new IterableFlatten<>((a, b) -> a + b); final Set<String> input = Sets.newHashSet("a", "b", "c"); final String result = function.apply(input); assertEquals("abc", result); }
SetValue extends KorypheFunction<Object, Object> { @Override public Object apply(final Object o) { return value; } SetValue(); SetValue(final Object returnValue); @Override Object apply(final Object o); Object getValue(); void setValue(final Object identity); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldSetValue() { final SetValue function = new SetValue(SET_VALUE); Object output = function.apply("test"); assertEquals(SET_VALUE, output); }
SetValue extends KorypheFunction<Object, Object> { public Object getValue() { return value; } SetValue(); SetValue(final Object returnValue); @Override Object apply(final Object o); Object getValue(); void setValue(final Object identity); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldSerialiseAndDeserialiseLong() throws IOException { final SetValue function = new SetValue(1L); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.SetValue\",%n" + " \"value\" : {\"java.lang.Long\" : 1}%n" + "}"), json); final SetValue deserialisedFunction = JsonSerialiser.deserialise(json, SetValue.class); assertEquals(1L, deserialisedFunction.getValue()); }
MapToTuple extends KorypheFunction<Map<K, Object>, Tuple<K>> implements Serializable { @Override public Tuple<K> apply(final Map<K, Object> map) { return new MapTuple<>(map); } @Override Tuple<K> apply(final Map<K, Object> map); }
@Test public void shouldConvertMapIntoMapTuple() { final MapToTuple function = new MapToTuple(); Map<String, Object> input = new HashMap<>(); input.put("A", 1); input.put("B", 2); input.put("C", 3); Tuple output = function.apply(input); assertEquals(new MapTuple<>(input), output); }
IterableFunction extends KorypheFunction<Iterable<I_ITEM>, Iterable<O_ITEM>> { @Override public Iterable<O_ITEM> apply(final Iterable<I_ITEM> items) { return IterableUtil.map(items, functions); } IterableFunction(); IterableFunction(final Function function); IterableFunction(final List<Function> functions); @Override Iterable<O_ITEM> apply(final Iterable<I_ITEM> items); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") List<Function> getFunctions(); void setFunctions(final List<Function> functions); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldConvertIterableOfIntegers() { final IterableFunction<Integer, String> function = new IterableFunction<>(new ToString()); final Iterable<String> result = function.apply(Arrays.asList(1, 2, 3, 4)); assertNotNull(result); assertEquals(Arrays.asList("1", "2", "3", "4"), Lists.newArrayList(result)); } @Test public void shouldReturnEmptyIterableForEmptyInput() { final IterableFunction<Iterable<Integer>, Integer> function = new IterableFunction<>(new FirstItem<>()); final Iterable<Integer> result = function.apply(new ArrayList<>()); assertNotNull(result); assertTrue(Iterables.isEmpty(result)); } @Test public void shouldApplyMultipleFunctions() { final IterableFunction<Integer, Integer> function = new IterableFunction.Builder<Integer>() .first(Object::toString) .then(Integer::valueOf) .build(); final Iterable<Integer> result = function.apply(Arrays.asList(1, 2, 3, 4)); assertEquals(4, Iterables.size(result)); assertEquals(Arrays.asList(1, 2, 3, 4), Lists.newArrayList(result)); } @Test public void shouldReturnNullForNullInputIterable() { final IterableFunction function = new IterableFunction(); final Object result = function.apply(null); assertNull(result); } @Test public void shouldNotModifyInputForEmptyListOfFunctions() { final IterableFunction<Integer, Integer> function = new IterableFunction<>(new ArrayList<>()); final Iterable<Integer> result = function.apply(Arrays.asList(1, 2, 3)); assertEquals(Arrays.asList(1, 2, 3), Lists.newArrayList(result)); } @Test public void shouldThrowErrorForNullListOfFunctions() { final List<Function> functions = null; final IterableFunction<Integer, Integer> function = new IterableFunction<>(functions); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(Arrays.asList(1, 2, 3))); assertEquals("List of functions cannot be null", exception.getMessage()); } @Test public void shouldThrowErrorForListOfFunctionsWithNullFunction() { final List<Function> functions = new ArrayList<>(); functions.add(new ToString()); functions.add(null); final IterableFunction<Integer, Integer> function = new IterableFunction<>(functions); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(Arrays.asList(1, 2, 3))); assertEquals("Functions list cannot contain a null function", exception.getMessage()); }
IterableFunction extends KorypheFunction<Iterable<I_ITEM>, Iterable<O_ITEM>> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public List<Function> getFunctions() { return functions; } IterableFunction(); IterableFunction(final Function function); IterableFunction(final List<Function> functions); @Override Iterable<O_ITEM> apply(final Iterable<I_ITEM> items); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") List<Function> getFunctions(); void setFunctions(final List<Function> functions); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldPopulateFunctionFromBuilder() { final Function<Integer, String> func = Object::toString; final Function<String, Integer> func1 = Integer::valueOf; final Function<Integer, String> func2 = Object::toString; final IterableFunction<Integer, String> function = new IterableFunction.Builder<Integer>() .first(func) .then(func1) .then(func2) .build(); assertEquals(3, function.getFunctions().size()); assertEquals(Arrays.asList(func, func1, func2), function.getFunctions()); }
ToLowerCase extends KorypheFunction<Object, String> { @Override public String apply(final Object value) { if (null == value) { return null; } if (value instanceof String) { return StringUtils.lowerCase((String) value); } return StringUtils.lowerCase(value.toString()); } @Override String apply(final Object value); }
@Test public void shouldLowerCaseInputString() { final Function function = getInstance(); final Object output = function.apply(TEST_STRING); assertEquals(StringUtils.lowerCase(TEST_STRING), output); } @Test public void shouldLowerCaseInputObject() { final Function function = getInstance(); final ToLowerCaseTestObject input = new ToLowerCaseTestObject(); final Object output = function.apply(input); assertEquals(StringUtils.lowerCase(input.getClass().getSimpleName().toUpperCase()), output); } @Test public void shouldHandleNullInput() { final Function function = getInstance(); Object output = function.apply(null); assertNull(output); }
PredicateMap extends KoryphePredicate<Map<?, T>> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) public Object getKey() { return key; } PredicateMap(); PredicateMap(final Object key, final Predicate<? super T> predicate); @Override boolean test(final Map<?, T> map); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate<? super T> getPredicate(); void setPredicate(final Predicate<? super T> predicate); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Object getKey(); void setKey(final Object key); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final PredicateMap<String> mapFilter = new PredicateMap<>(DATE_KEY, new IsA(Map.class)); final String json = JsonSerialiser.serialise(mapFilter); JsonSerialiser.assertEquals(String.format("{\n" + " \"class\" : \"uk.gov.gchq.koryphe.predicate.PredicateMap\",\n" + " \"predicate\" : {\n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.IsA\",\n" + " \"type\" : \"java.util.Map\"\n" + " },\n" + " \"key\" : {\n" + " \"java.util.Date\" : " + DATE_KEY.getTime() + "%n" + " }\n" + "}"), json); final PredicateMap deserialisedFilter = JsonSerialiser.deserialise(json, PredicateMap.class); assertNotNull(deserialisedFilter); assertEquals(DATE_KEY, deserialisedFilter.getKey()); }
DeserialiseXml extends KorypheFunction<String, Map<String, Object>> implements Serializable { @Override public Map<String, Object> apply(final String xml) { if (isNull(xml)) { return null; } return XML.toJSONObject(xml).toMap(); } @Override Map<String, Object> apply(final String xml); }
@Test public void shouldParseXml() { final DeserialiseXml function = new DeserialiseXml(); final String input = "<root><element1><element2 attr=\"attr1\">value1</element2></element1><element1><element2>value2</element2></element1></root>"; Map<String, Object> result = function.apply(input); Map<String, Object> element2aMap = new HashMap<>(); Map<String, Object> element2aAttrContentMap = new HashMap<>(); element2aAttrContentMap.put("attr", "attr1"); element2aAttrContentMap.put("content", "value1"); element2aMap.put("element2", element2aAttrContentMap); Map<String, Object> element2bMap = new HashMap<>(); element2bMap.put("element2", "value2"); HashMap<Object, Object> element1Map = new HashMap<>(); element1Map.put("element1", Arrays.asList(element2aMap, element2bMap)); HashMap<Object, Object> expectedRootMap = new HashMap<>(); expectedRootMap.put("root", element1Map); assertEquals(expectedRootMap, result); } @Test public void shouldReturnNullForNullInput() { final DeserialiseXml function = new DeserialiseXml(); Map<String, Object> result = function.apply(null); assertNull(result); }
IterableFilter extends KorypheFunction<Iterable<I_ITEM>, Iterable<I_ITEM>> { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") public Predicate<I_ITEM> getPredicate() { return predicate; } IterableFilter(); IterableFilter(final Predicate predicate); @Override Iterable<I_ITEM> apply(final Iterable<I_ITEM> items); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") Predicate<I_ITEM> getPredicate(); IterableFilter<I_ITEM> predicate(final Predicate predicate); IterableFilter<I_ITEM> setPredicate(final Predicate<I_ITEM> predicate); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final IterableFilter predicate = getInstance(); final String json = JsonSerialiser.serialise(predicate); JsonSerialiser.assertEquals("{" + "\"class\":\"uk.gov.gchq.koryphe.impl.function.IterableFilter\"," + "\"predicate\":{\"class\":\"uk.gov.gchq.koryphe.impl.predicate.IsMoreThan\",\"orEqualTo\":false,\"value\":1}" + "}", json); final IterableFilter deserialised = JsonSerialiser.deserialise(json, IterableFilter.class); assertNotNull(deserialised); assertEquals(1, ((IsMoreThan) deserialised.getPredicate()).getControlValue()); }
MultiplyBy extends KorypheFunction<Integer, Integer> { public Integer apply(final Integer input) { if (input == null) { return null; } else { return input * by; } } MultiplyBy(); MultiplyBy(final int by); int getBy(); void setBy(final int by); Integer apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldMultiplyBy2() { final MultiplyBy function = new MultiplyBy(2); int output = function.apply(4); assertEquals(8, output); } @Test public void shouldMultiplyBy1IfByIsNotSet() { final MultiplyBy function = new MultiplyBy(); int output = function.apply(9); assertEquals(9, output); } @Test public void shouldReturnNullIfInputIsNull() { final MultiplyBy function = new MultiplyBy(2); Integer output = function.apply(null); assertNull(output); }
MultiplyBy extends KorypheFunction<Integer, Integer> { public int getBy() { return by; } MultiplyBy(); MultiplyBy(final int by); int getBy(); void setBy(final int by); Integer apply(final Integer input); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final MultiplyBy function = new MultiplyBy(4); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.MultiplyBy\",%n" + " \"by\" : 4%n" + "}"), json); final MultiplyBy deserialisedMultiplyBy = JsonSerialiser.deserialise(json, MultiplyBy.class); assertNotNull(deserialisedMultiplyBy); assertEquals(4, deserialisedMultiplyBy.getBy()); }
StringReplace extends KorypheFunction<String, String> { @Override public String apply(final String input) { return StringUtils.replace(input, searchString, replacement); } StringReplace(); StringReplace(final String searchString, final String replacement); @Override String apply(final String input); String getReplacement(); void setReplacement(final String replacement); String getSearchString(); void setSearchString(final String searchString); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringReplace function = new StringReplace(); final String result = function.apply(null); assertNull(result); } @Test public void shouldHandleNullSearchString() { final StringReplace function = new StringReplace(null, "output"); final String input = "An input string."; final String result = function.apply(input); assertEquals("An input string.", result); } @Test public void shouldHandleNullReplacement() { final StringReplace function = new StringReplace("input", null); final String input = "An input string."; final String result = function.apply(input); assertEquals("An input string.", result); } @Test public void shouldHandleNullSearchStringAndReplacement() { final StringReplace function = new StringReplace(null, null); final String input = "An input string."; final String result = function.apply(input); assertEquals("An input string.", result); } @Test public void shouldReplaceInString() { final StringReplace function = new StringReplace("input", "output"); final String input = "An input string."; final String result = function.apply(input); assertEquals("An output string.", result); }
AdaptedBinaryOperator extends Adapted<T, OT, OT, T, T> implements BinaryOperator<T> { @Override public T apply(final T state, final T input) { if (binaryOperator == null) { throw new IllegalArgumentException("BinaryOperator cannot be null"); } return adaptOutput(binaryOperator.apply(adaptInput(state), adaptInput(input)), state); } AdaptedBinaryOperator(); AdaptedBinaryOperator(final BinaryOperator<OT> binaryOperator, final Function<T, OT> inputAdapter, final BiFunction<T, OT, T> outputAdapter); AdaptedBinaryOperator(final BinaryOperator<OT> binaryOperator, final Function<T, OT> inputAdapter, final Function<OT, T> outputAdapter); @Override T apply(final T state, final T input); BinaryOperator<OT> getBinaryOperator(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") void setBinaryOperator(final BinaryOperator<OT> binaryOperator); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void IfNoOutputAdapterIsSpecifiedShouldReturnNewState() { AdaptedBinaryOperator abo = new AdaptedBinaryOperator(new Product(), new ToLong(), (BinaryOperator<Number>) null); Object aggregated = abo.apply(2, 5); assertEquals(10L, aggregated); } @Test public void shouldAdaptOutputIfOutputAdapterIsSpecified() { AdaptedBinaryOperator abo = new AdaptedBinaryOperator(new Product(), new ToLong(), new MultiplyLongBy(5L)); Object aggregated = abo.apply(2, 5); assertEquals(50L, aggregated); } @Test public void shouldConsiderStateWhenOutputAdapterIsBiFunction() { ArrayTuple state = new ArrayTuple(); state.put(0, "tuple"); ArrayTuple input = new ArrayTuple(); state.put(0, "test");; TupleInputAdapter<Integer, String> inputAdapter = new TupleInputAdapter<>(); inputAdapter.setSelection(new Integer[] { 0 }); TupleOutputAdapter<Integer, String> outputAdapter = new TupleOutputAdapter<>(); outputAdapter.setProjection(new Integer[] { 0 }); AdaptedBinaryOperator abo = new AdaptedBinaryOperator(new StringConcat(" "), inputAdapter, outputAdapter); Object aggregated = abo.apply(state, input); ArrayTuple expected = new ArrayTuple(); state.put(0, "tuple test"); assertEquals(expected, aggregated); } @Test public void shouldThrowExceptionIfNoBinaryOperatorIsSpecified() { AdaptedBinaryOperator abo = new AdaptedBinaryOperator(); try { abo.apply("will", "fail"); fail("Expected an exception"); } catch (Exception e) { assertNotNull(e.getMessage()); } } @Test public void shouldPassInputDirectlyToBinaryOperatorIfNoInputAdapterIsSpecified() { AdaptedBinaryOperator abo = new AdaptedBinaryOperator(new Product(), null, new MultiplyBy(10)); Object aggregated = abo.apply(2, 5); assertEquals(Integer.class, aggregated.getClass()); assertEquals(100, aggregated); } @Test public void shouldJustDelegateToBinaryOperatorIfNoAdaptersAreSpecified() { AdaptedBinaryOperator abo = new AdaptedBinaryOperator(new Product(), null, (BiFunction) null); Object aggregated = abo.apply(2, 5); assertEquals(Integer.class, aggregated.getClass()); assertEquals(10, aggregated); }
Longest extends KorypheFunction2<T, T, T> { @Override public T apply(final T first, final T second) { final int firstLength = delegate.apply(first); final int secondLength = delegate.apply(second); return (firstLength - secondLength) > 0 ? first : second; } Longest(); @Override T apply(final T first, final T second); }
@Test public void shouldHandleNullInputs() { final Longest function = getInstance(); final Object result = function.apply(null, null); assertNull(result); } @Test public void shouldThrowExceptionForIncompatibleInputType() { final Longest function = getInstance(); final Object input1 = new Concat(); final Object input2 = new Concat(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(input1, input2)); assertEquals("Could not determine the size of the provided value", exception.getMessage()); } @Test public void shouldReturnLongestStringInput() { final Longest<String> function = new Longest<>(); final String input1 = "A short string"; final String input2 = "A longer string"; final String result = function.apply(input1, input2); assertEquals(input2, result); } @Test public void shouldReturnLongestObjectArrayInput() { final Longest<Object[]> function = new Longest<>(); final Object[] input1 = new Object[5]; final Object[] input2 = new Object[10]; final Object[] result = function.apply(input1, input2); assertArrayEquals(input2, result); } @Test public void shouldReturnLongestListInput() { final Longest<List<Integer>> function = new Longest<>(); final List<Integer> input1 = Lists.newArrayList(1); final List<Integer> input2 = Lists.newArrayList(1, 2, 3); final List<Integer> result = function.apply(input1, input2); assertEquals(input2, result); } @Test public void shouldReturnLongestSetInput() { final Longest<Set<Integer>> function = new Longest<>(); final Set<Integer> input1 = Sets.newHashSet(1); final Set<Integer> input2 = Sets.newHashSet(1, 2, 3); final Set<Integer> result = function.apply(input1, input2); assertEquals(input2, result); } @Test public void shouldReturnLongestMapInput() { final Longest<Map<String, String>> function = new Longest<>(); final Map<String, String> input1 = new HashMap<>(); final Map<String, String> input2 = Maps.asMap(Sets.newHashSet("1"), k -> k); final Map<String, String> result = function.apply(input1, input2); assertEquals(input2, result); }
ExtractValues extends KorypheFunction<Map<K, V>, Iterable<V>> { @Override public Iterable<V> apply(final Map<K, V> map) { return null == map ? null : map.values(); } @Override Iterable<V> apply(final Map<K, V> map); }
@Test public void shouldExtractValuesFromGivenMap() { final ExtractValues<String, Integer> function = new ExtractValues<>(); final Map<String, Integer> input = new HashMap<>(); input.put("first", 1); input.put("second", 2); input.put("third", 3); final Iterable<Integer> results = function.apply(input); assertThat(results, containsInAnyOrder(1, 2, 3)); } @Test public void shouldReturnEmptySetForEmptyMap() { final ExtractValues<String, Integer> function = new ExtractValues<>(); final Iterable<Integer> results = function.apply(new HashMap<>()); assertTrue(Iterables.isEmpty(results)); } @Test public void shouldReturnNullForNullInput() { final ExtractValues<String, String> function = new ExtractValues<>(); final Map<String, String> input = null; final Iterable result = function.apply(input); assertNull(result); }
IterableConcat extends KorypheFunction<Iterable<Iterable<I_ITEM>>, Iterable<I_ITEM>> { @Override public Iterable<I_ITEM> apply(final Iterable<Iterable<I_ITEM>> items) { return IterableUtil.concat(items); } @Override Iterable<I_ITEM> apply(final Iterable<Iterable<I_ITEM>> items); }
@Test public void shouldFlattenNestedIterables() { final IterableConcat<Integer> function = new IterableConcat<>(); final Iterable<Integer> result = function.apply(Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6))); assertNotNull(result); assertEquals(Arrays.asList(1, 2, 3, 4, 5, 6), Lists.newArrayList(result)); } @Test public void shouldHandleNullInputIterable() { final IterableConcat<Integer> function = new IterableConcat<>(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertEquals("iterables are required", exception.getMessage()); } @Test public void shouldReturnEmptyIterableForEmptyInput() { final IterableConcat<Integer> function = new IterableConcat<>(); final Iterable<Iterable<Integer>> input = new ArrayList<>(); final Iterable<Integer> results = function.apply(input); assertTrue(Iterables.isEmpty(results)); } @Test public void shouldHandleNullElementsOfInnerIterable() { final IterableConcat<Integer> function = new IterableConcat<>(); final Iterable<Iterable<Integer>> input = Arrays.asList( Arrays.asList(1, 2, null, 4), Arrays.asList(5, null, 7)); final Iterable<Integer> results = function.apply(input); assertEquals(Arrays.asList(1, 2, null, 4, 5, null, 7), Lists.newArrayList(results)); }
DefaultIfEmpty extends KorypheFunction<Object, Object> { @Override public Object apply(final Object iterable) { if (null == iterable) { return null; } return (delegate.apply(iterable) == 0) ? defaultValue : iterable; } DefaultIfEmpty(); DefaultIfEmpty(final Object defaultValue); @Override Object apply(final Object iterable); Object getDefaultValue(); void setDefaultValue(final Object defaultValue); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final DefaultIfEmpty function = new DefaultIfEmpty(); final Object result = function.apply(null); assertNull(result); } @Test public void shouldReturnDefaultValueIfEmpty() { final DefaultIfEmpty defaultIfEmpty = new DefaultIfEmpty(DEFAULT_VALUE); final Object result = defaultIfEmpty.apply(Collections.emptyList()); assertEquals(DEFAULT_VALUE, result); } @Test public void shouldReturnOriginalValueIfNotEmpty() { final List<String> iterable = Lists.newArrayList("first", "second"); final DefaultIfEmpty defaultIfEmpty = new DefaultIfEmpty(DEFAULT_VALUE); final Object result = defaultIfEmpty.apply(iterable); assertEquals(iterable, result); }
ApplyBiFunction extends KorypheFunction2<T, U, R> implements WrappedBiFunction<T, U, R> { @Override public R apply(final T t, final U u) { return nonNull(function) ? function.apply(t, u) : null; } ApplyBiFunction(); ApplyBiFunction(final BiFunction<T, U, R> function); @Override R apply(final T t, final U u); @Override @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") BiFunction<T, U, R> getFunction(); void setFunction(final BiFunction<T, U, R> function); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldApplyBiFunction() { final ApplyBiFunction<Number, Number, Number> function = new ApplyBiFunction<>(new Sum()); final Tuple2<Number, Number> input = new Tuple2<>(1, 2); final Number result = function.apply(input); assertEquals(3, result); } @Test public void shouldReturnNullForNullFunction() { final ApplyBiFunction<Number, Number, Number> function = new ApplyBiFunction<>(); final Tuple2<Number, Number> input = new Tuple2<>(1, 2); final Object result = function.apply(input); assertNull(result); }
Base64Decode extends KorypheFunction<byte[], byte[]> { @SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification = "Returning null means the input was null") @Override public byte[] apply(final byte[] base64Encoded) { if (isNull(base64Encoded)) { return null; } if (base64Encoded.length == 0) { return new byte[0]; } return Base64.decodeBase64(base64Encoded); } @SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS", justification = "Returning null means the input was null") @Override byte[] apply(final byte[] base64Encoded); }
@Test public void shouldDecodeBase64() { final Base64Decode function = new Base64Decode(); byte[] input = "test string".getBytes(); final byte[] base64 = Base64.encodeBase64(input); final byte[] result = function.apply(base64); assertArrayEquals(input, result); } @Test public void shouldReturnNullForNullInput() { final Base64Decode function = new Base64Decode(); final byte[] result = function.apply(null); assertNull(result); }
ToSet extends KorypheFunction<Object, Set<?>> { @Override public Set<?> apply(final Object value) { if (null == value) { return Sets.newHashSet((Object) null); } if (value instanceof Object[]) { return Sets.newHashSet((Object[]) value); } if (value instanceof Iterable) { if (value instanceof Set) { return (Set<?>) value; } return Sets.newHashSet((Iterable) value); } return Sets.newHashSet(value); } @Override Set<?> apply(final Object value); }
@Test public void shouldConvertNullToSet() { final ToSet function = new ToSet(); final Object result = function.apply(null); assertEquals(Sets.newHashSet((Object) null), result); } @Test public void shouldConvertStringToSet() { final ToSet function = new ToSet(); final Object value = "value1"; final Object result = function.apply(value); assertEquals(Sets.newHashSet(value), result); } @Test public void shouldConvertArrayToSet() { final ToSet function = new ToSet(); final Object value = new String[] {"value1", "value2"}; Object result = function.apply(value); assertEquals(Sets.newHashSet((Object[]) value), result); } @Test public void shouldConvertListToSet() { final ToSet function = new ToSet(); final Object value = Lists.newArrayList("value1", "value2"); final Object result = function.apply(value); assertEquals(Sets.newHashSet((List) value), result); } @Test public void shouldReturnAGivenSet() { final ToSet function = new ToSet(); final Object value = Sets.newHashSet("value1", "value2"); final Object result = function.apply(value); assertSame(value, result); }
CreateObject extends KorypheFunction<Object, Object> { @Override public Object apply(final Object value) { if (isNull(objectClass)) { return null; } if (isNull(value)) { try { return objectClass.newInstance(); } catch (final InstantiationException | IllegalAccessException e) { throw new RuntimeException("Unable to create a new instance of " + objectClass.getName() + " using the no-arg constructor", e); } } for (final Constructor<?> constructor : objectClass.getConstructors()) { if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].isAssignableFrom(value.getClass())) { try { return constructor.newInstance(value); } catch (final InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Unable to create a new instance of " + objectClass.getName() + " using the constructor with single argument type " + value.getClass().getName(), e); } } } throw new RuntimeException("Unable to create a new instance of " + objectClass.getName() + ". No constructors were found that accept a " + value.getClass().getName()); } CreateObject(); CreateObject(final Class<?> objectClass); @Override Object apply(final Object value); Class<?> getObjectClass(); void setObjectClass(final Class<?> objectClass); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldCreateNewObjectUsingNoArgConstructor() { final CreateObject function = new CreateObject(ArrayList.class); Object output = function.apply(null); assertEquals(new ArrayList<>(), output); } @Test public void shouldCreateNewObjectUsingSingleArgConstructor() { final CreateObject function = new CreateObject(ArrayList.class); List<Integer> value = Arrays.asList(1, 2, 3); Object output = function.apply(value); assertEquals(value, output); assertNotSame(value, output); } @Test public void shouldThrowExceptionIfNoConstructorWithArgTypeIsFound() { final CreateObject function = new CreateObject(ArrayList.class); Map<String, String> value = new HashMap<>(); final Exception exception = assertThrows(RuntimeException.class, () -> function.apply(value)); final String expected = "Unable to create a new instance of java.util.ArrayList. No constructors were found " + "that accept a java.util.HashMap"; assertEquals(expected, exception.getMessage()); } @Test public void shouldThrowExceptionIfPrivateConstructor() { final CreateObject function = new CreateObject(TestClass.class); final Exception exception = assertThrows(RuntimeException.class, () -> function.apply(null)); final String expected = "Unable to create a new instance of " + "uk.gov.gchq.koryphe.impl.function.CreateObjectTest$TestClass using the no-arg constructor"; assertEquals(expected, exception.getMessage()); }
CreateObject extends KorypheFunction<Object, Object> { public Class<?> getObjectClass() { return objectClass; } CreateObject(); CreateObject(final Class<?> objectClass); @Override Object apply(final Object value); Class<?> getObjectClass(); void setObjectClass(final Class<?> objectClass); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test @Override public void shouldJsonSerialiseAndDeserialise() throws IOException { final CreateObject function = new CreateObject(ArrayList.class); final String json = JsonSerialiser.serialise(function); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.function.CreateObject\",%n" + " \"objectClass\" : \"" + ArrayList.class.getName() + "\"%n" + "}"), json); final CreateObject deserialised = JsonSerialiser.deserialise(json, CreateObject.class); assertNotNull(deserialised); assertEquals(ArrayList.class, deserialised.getObjectClass()); }
StringTrim extends KorypheFunction<String, String> { @Override public String apply(final String input) { return StringUtils.trim(input); } StringTrim(); @Override String apply(final String input); }
@Test public void shouldHandleNullInput() { final StringTrim function = new StringTrim(); final String result = function.apply(null); assertNull(result); } @Test public void shouldTrimInputString() { final StringTrim function = new StringTrim(); final String input = " Input String "; final String result = function.apply(input); assertEquals("Input String", result); }
DefaultIfNull extends KorypheFunction<Object, Object> { @Override public Object apply(final Object input) { return null == input ? defaultValue : input; } DefaultIfNull(); DefaultIfNull(final Object defaultValue); @Override Object apply(final Object input); void setDefaultValue(final Object defaultValue); Object getDefaultValue(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnDefaultValueIfNull() { final DefaultIfNull defaultIfNull = new DefaultIfNull(DEFAULT_VALUE); final Object result = defaultIfNull.apply(null); assertEquals(result, DEFAULT_VALUE); } @Test public void shouldReturnOriginalValueIfNotNull() { final DefaultIfNull defaultIfNull = new DefaultIfNull(DEFAULT_VALUE); final Object result = defaultIfNull.apply("input"); assertEquals(result, "input"); }
StringTruncate extends KorypheFunction<String, String> { @Override public String apply(final String input) { if (null == input) { return null; } String truncated = input.substring(0, Math.min(input.length(), length)); if (ellipses && truncated.length() < input.length()) { truncated += ELLIPSES; } return truncated; } StringTruncate(); StringTruncate(final int length); StringTruncate(final int length, final boolean ellipses); @Override String apply(final String input); int getLength(); void setLength(final int length); boolean isEllipses(); void setEllipses(final boolean ellipses); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringTruncate function = new StringTruncate(); final String result = function.apply(null); assertNull(result); } @Test public void shouldTruncateString() { final StringTruncate function = new StringTruncate(10); final String input = "A long input string"; final String result = function.apply(input); assertEquals("A long inp", result); } @Test public void shouldTruncateStringWithEllipses() { final StringTruncate function = new StringTruncate(10, true); final String input = "A long input string"; final String result = function.apply(input); assertEquals("A long inp...", result); } @Test public void shouldReturnFullStringIfInputShorterThanMaxLength() { final StringTruncate function = new StringTruncate(10); final String input = "123 56"; final String result = function.apply(input); assertEquals(result, input); }
ToArray extends KorypheFunction<Object, Object[]> { @Override public Object[] apply(final Object value) { if (null == value) { return new Object[]{null}; } if (value instanceof Object[]) { return ((Object[]) value); } if (value instanceof Iterable) { return Iterables.toArray(((Iterable) value), Object.class); } return new Object[]{value}; } @Override Object[] apply(final Object value); }
@Test public void shouldConvertNullToArray() { final ToArray function = new ToArray(); final Object[] result = function.apply(null); assertArrayEquals(new Object[] {null}, result); } @Test public void shouldConvertStringToArray() { final ToArray function = new ToArray(); final Object value = "value1"; final Object[] result = function.apply(value); assertArrayEquals(new Object[] {value}, result); } @Test public void shouldConvertListToArray() { final ToArray function = new ToArray(); final Object value = Lists.newArrayList("value1", "value2"); final Object[] result = function.apply(value); assertArrayEquals(new Object[] {"value1", "value2"}, result); } @Test public void shouldConvertSetToArray() { final ToArray function = new ToArray(); final Object value = Sets.newLinkedHashSet(Arrays.asList("value1", "value2")); final Object[] result = function.apply(value); assertArrayEquals(new Object[] {"value1", "value2"}, result); } @Test public void shouldReturnAGivenArray() { final ToArray function = new ToArray(); final Object value = new Object[] {"value1"}; final Object[] result = function.apply(value); assertSame(value, result); }
FirstItem extends KorypheFunction<Iterable<T>, T> { @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") public T apply(final Iterable<T> input) { if (null == input) { throw new IllegalArgumentException("Input cannot be null"); } try { return Iterables.getFirst(input, null); } finally { CloseableUtil.close(input); } } @Override @SuppressFBWarnings(value = "DE_MIGHT_IGNORE", justification = "Any exceptions are to be ignored") T apply(final Iterable<T> input); }
@Test public void shouldReturnCorrectValueWithInteger() { final FirstItem<Integer> function = new FirstItem<>(); final Integer result = function.apply(Arrays.asList(1, 2, 3, 4)); assertNotNull(result); assertEquals(1, result); } @Test public void shouldReturnCorrectValueWithString() { final FirstItem<String> function = new FirstItem<>(); final String result = function.apply(Arrays.asList("these", "are", "test", "strings")); assertNotNull(result); assertEquals("these", result); } @Test public void shouldReturnNullForNullElement() { final FirstItem<String> function = new FirstItem<>(); final String result = function.apply(Arrays.asList(null, "two", "three")); assertNull(result); } @Test public void shouldThrowErrorForNullInput() { final FirstItem<String> function = new FirstItem<>(); final Exception exception = assertThrows(IllegalArgumentException.class, () -> function.apply(null)); assertTrue(exception.getMessage().contains("Input cannot be null")); }
ToUpperCase extends KorypheFunction<Object, String> { @Override public String apply(final Object value) { if (null == value) { return null; } if (value instanceof String) { return StringUtils.upperCase((String) value); } return StringUtils.upperCase(value.toString()); } @Override String apply(final Object value); }
@Test public void shouldUpperCaseInputString() { final Function function = getInstance(); final Object output = function.apply(TEST_STRING); assertEquals(StringUtils.upperCase(TEST_STRING), output); } @Test public void shouldUpperCaseInputObject() { final Function function = getInstance(); final ToUpperCaseTestObject input = new ToUpperCaseTestObject(); final Object output = function.apply(input); assertEquals(StringUtils.upperCase(input.getClass().getSimpleName().toLowerCase()), output); } @Test public void shouldHandleNullInput() { final Function function = getInstance(); Object output = function.apply(null); assertNull(output); }
Cast extends KorypheFunction<I, O> { @Override public O apply(final I value) { return outputClass.cast(value); } Cast(); Cast(final Class<O> outputClass); @Override O apply(final I value); Class<O> getOutputClass(); void setOutputClass(final Class<O> outputClass); @Override boolean equals(final Object o); @Override int hashCode(); }
@Disabled @Test public void shouldCast() { final Cast function = new Cast(Integer.class); Object output = function.apply(new Long(5)); assertEquals(Integer.class, output.getClass()); }
StringRegexReplace extends KorypheFunction<String, String> { @Override public String apply(final String input) { if (null == input) { return null; } return input.replaceAll(regex, replacement); } StringRegexReplace(); StringRegexReplace(final String regex, final String replacement); @Override String apply(final String input); String getRegex(); void setRegex(final String regex); String getReplacement(); void setReplacement(final String replacement); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringRegexReplace function = new StringRegexReplace(); final String result = function.apply(null); assertNull(result); } @Test public void shouldReplaceStringSimple() { final StringRegexReplace function = new StringRegexReplace("input","output"); final String input = "An input string."; final String result = function.apply(input); assertEquals("An output string.", result); } @Test public void shouldReplaceStringRegex() { final StringRegexReplace function = new StringRegexReplace("t\\s+s"," "); final String input = "An input string."; final String result = function.apply(input); assertEquals("An inpu tring.", result); }
If extends KorypheFunction<I, O> { @Override public O apply(final I input) { boolean conditionTmp; if (null == condition) { conditionTmp = null != predicate && predicate.test(input); } else { conditionTmp = condition; } if (conditionTmp) { if (null != then) { return then.apply(input); } return (O) input; } if (null != otherwise) { return otherwise.apply(input); } return (O) input; } @Override O apply(final I input); Boolean getCondition(); void setCondition(final boolean condition); If<I, O> condition(final boolean condition); Predicate<? super I> getPredicate(); void setPredicate(final Predicate<?> predicate); If<I, O> predicate(final Predicate<?> predicate); If<I, O> predicate(final Integer selection, final Predicate<?> predicate); If<I, O> predicate(final Integer[] selection, final Predicate<?> predicate); Function<? super I, O> getThen(); void setThen(final Function<?, ?> then); If<I, O> then(final Function<?, ?> then); If<I, O> then(final Integer selectionProjection, final Function<?, ?> then); If<I, O> then(final Integer selection, final Function<?, ?> then, final Integer projection); If<I, O> then(final Integer[] selectionProjection, final Function<?, ?> then); If<I, O> then(final Integer[] selection, final Function<?, ?> then, final Integer[] projection); Function<? super I, O> getOtherwise(); void setOtherwise(final Function<?, ?> otherwise); If<I, O> otherwise(final Function<?, ?> otherwise); If<I, O> otherwise(final Integer selectionProjection, final Function<?, ?> then); If<I, O> otherwise(final Integer selection, final Function<?, ?> then, final Integer projection); If<I, O> otherwise(final Integer[] selectionProjection, final Function<?, ?> then); If<I, O> otherwise(final Integer[] selection, final Function<?, ?> then, final Integer[] projection); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldReturnInputWithNullFunctions() { final Object input = "testValue"; final If<Object, Object> function = new If<>(); final Object result = function.apply(input); assertEquals(input, result); }
ParseTime extends KorypheFunction<String, Long> { @Override public Long apply(final String dateString) { if (isNull(dateString)) { return null; } try { final Long time; if (isNull(format)) { time = DateUtil.parseTime(dateString, timeZone); } else { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); if (nonNull(timeZone)) { simpleDateFormat.setTimeZone(timeZone); } time = simpleDateFormat.parse(dateString).getTime(); } return timeUnit.fromMilliSeconds(time); } catch (final ParseException e) { throw new IllegalArgumentException("Date string could not be parsed: " + dateString, e); } } ParseTime(); @Override Long apply(final String dateString); String getFormat(); void setFormat(final String format); ParseTime format(final String format); TimeZone getTimeZone(); @JsonGetter("timeZone") String getTimeZoneAsString(); @JsonSetter void setTimeZone(final String timeZone); void setTimeZone(final TimeZone timeZone); ParseTime timeZone(final String timeZone); ParseTime timeZone(final TimeZone timeZone); TimeUnit getTimeUnit(); @JsonSetter void setTimeUnit(final TimeUnit timeUnit); void setTimeUnit(final String timeUnit); ParseTime timeUnit(final String timeUnit); ParseTime timeUnit(final TimeUnit timeUnit); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldParseTime() throws ParseException { final ParseTime function = new ParseTime(); final String input = "2000-01-02 03:04:05.006"; long result = function.apply(input); assertEquals(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(input).getTime(), result); } @Test public void shouldReturnNullForNullInput() { final ParseTime function = new ParseTime(); final Object result = function.apply(null); assertNull(result); }
BinaryOperatorMap extends KorypheBinaryOperator<Map<K, T>> { public void setBinaryOperator(final BinaryOperator<? super T> binaryOperator) { this.binaryOperator = binaryOperator; } BinaryOperatorMap(); BinaryOperatorMap(final BinaryOperator<? super T> binaryOperator); void setBinaryOperator(final BinaryOperator<? super T> binaryOperator); BinaryOperator<? super T> getBinaryOperator(); @Override Map<K, T> _apply(final Map<K, T> state, final Map<K, T> input); }
@Test public void testMapAggregation() { int inA = 1; int inB = 2; int noInputs = 3; Map<String, Integer>[] inputs = new HashMap[noInputs]; for (int i = 0; i < noInputs; i++) { inputs[i] = new HashMap<>(); inputs[i].put("a", inA); inputs[i].put("b", inB); } BinaryOperator<Integer> aggregator = mock(BinaryOperator.class); for (int i = 0; i < noInputs; i++) { Integer expectedA = null; Integer expectedB = null; if (i > 0) { expectedA = i * inA; expectedB = i * inB; } given(aggregator.apply(expectedA, inA)).willReturn(inA + (expectedA == null ? 0 : expectedA)); given(aggregator.apply(expectedB, inB)).willReturn(inB + (expectedB == null ? 0 : expectedB)); } BinaryOperatorMap<String, Integer> mapBinaryOperator = new BinaryOperatorMap<>(); mapBinaryOperator.setBinaryOperator(aggregator); Map<String, Integer> state = null; for (Map<String, Integer> input : inputs) { state = mapBinaryOperator.apply(state, input); } assertEquals(noInputs * inA, (int) state.get("a")); assertEquals(noInputs * inB, (int) state.get("b")); }
ToString extends KorypheFunction<Object, String> { @Override public String apply(final Object o) { if (null == o) { return null; } if (o instanceof byte[]) { return new String(((byte[]) o), charset); } if (o instanceof Object[]) { return Arrays.toString((Object[]) o); } return String.valueOf(o); } ToString(); ToString(final String charsetString); ToString(final Charset charset); @Override String apply(final Object o); Charset getCharset(); void setCharset(final Charset charset); @JsonSetter("charset") void setCharset(final String charsetString); @JsonGetter("charset") String getCharsetAsString(); @Override boolean equals(final Object o); @Override int hashCode(); static final Charset DEFAULT_CHARSET; }
@Test public void shouldReturnString() { final ToString ts = new ToString(); final String output = ts.apply("test string"); assertEquals("test string", output); } @Test public void shouldHandleArray() { final ToString ts = new ToString(); final String[] testArray = new String[] {"test", "string"}; final String output = ts.apply(testArray); assertEquals("[test, string]", output); } @Test public void shouldHandleByteArrayWithUtf8Charset() { final ToString ts = new ToString(StandardCharsets.UTF_8); final byte[] bytes = "test string".getBytes(StandardCharsets.UTF_8); final String output = ts.apply(bytes); assertEquals("test string", output); } @Test public void shouldHandleByteArrayWithUtf16Charset() { final ToString ts = new ToString(StandardCharsets.UTF_16); final byte[] bytes = "test string".getBytes(StandardCharsets.UTF_16); final String output = ts.apply(bytes); assertEquals("test string", output); } @Test public void shouldHandleNullObject() { final ToString ts = new ToString(); final String output = ts.apply(null); assertNull(output); }
StringPrepend extends KorypheFunction<String, String> { @Override public String apply(final String input) { if (null == input) { return null; } if (null == prefix) { return input; } return prefix + input; } StringPrepend(); StringPrepend(final String prefix); @Override String apply(final String input); String getPrefix(); void setPrefix(final String prefix); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringPrepend function = new StringPrepend("!"); final String result = function.apply(null); assertNull(result); } @Test public void shouldHandleNullPrefix() { final StringPrepend function = new StringPrepend(null); final String result = function.apply("Hello"); assertEquals("Hello", result); } @Test public void shouldHandleUnsetSuffix() { final StringPrepend function = new StringPrepend(); final String result = function.apply("Hello"); assertEquals("Hello", result); } @Test public void shouldPrependInputWithString() { final StringPrepend function = new StringPrepend("!"); final String result = function.apply("Hello"); assertEquals("!Hello", result); }
StringSplit extends KorypheFunction<String, List<String>> { @Override public List<String> apply(final String input) { final String[] arr = StringUtils.split(input, delimiter); if (null == arr) { return null; } return Arrays.asList(arr); } StringSplit(); StringSplit(final String delimiter); @Override List<String> apply(final String input); String getDelimiter(); void setDelimiter(final String delimiter); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldHandleNullInput() { final StringSplit function = new StringSplit(); final List<String> result = function.apply(null); assertNull(result); } @Test public void shouldHandleNullDelimiter() { final StringSplit function = new StringSplit(null); final String input = "first,second,third"; final List<String> result = function.apply(input); assertThat(result, hasItems("first,second,third")); assertThat(result, hasSize(1)); } @Test public void shouldSplitString() { final StringSplit function = new StringSplit(","); final String input = "first,second,third"; final List<String> result = function.apply(input); assertThat(result, hasItems("first", "second", "third")); } @Test public void shouldSplitEmptyString() { final StringSplit function = new StringSplit(","); final String input = ""; final List<String> result = function.apply(input); assertThat(result, is(empty())); }
BinaryOperatorComposite extends Composite<C> implements BinaryOperator<T> { @Override public T apply(final T state, final T input) { T result = state; for (final BinaryOperator<T> component : this.components) { result = component.apply(result, input); } return result; } BinaryOperatorComposite(); BinaryOperatorComposite(final List<C> binaryOperators); @JsonProperty("operators") List<C> getComponents(); @Override T apply(final T state, final T input); }
@Test public void shouldExecuteEachBinaryOperatorInOrder() { BinaryOperatorComposite instance = getInstance(); BinaryOperatorComposite reversed = new BinaryOperatorComposite(Arrays.asList( new Product(), new Sum() )); Object aggregated = instance.apply(5, 10); Object aggregatedInReverseOrder = reversed.apply(5, 10); assertEquals(150, aggregated); assertEquals(60, aggregatedInReverseOrder); }
Increment extends KorypheFunction<Number, Number> { @Override public Number apply(final Number input) { if (isNull(input)) { return increment; } if (isNull(increment) || isNull(type)) { return input; } Number result; switch (type) { case INTEGER: result = ((Integer) increment) + input.intValue(); result = result.intValue(); break; case LONG: result = ((Long) increment) + input.longValue(); result = result.longValue(); break; case SHORT: result = ((Short) increment) + input.shortValue(); result = result.shortValue(); break; case DOUBLE: result = ((Double) increment) + input.doubleValue(); result = result.doubleValue(); break; case FLOAT: result = ((Float) increment) + input.floatValue(); result = result.floatValue(); break; default: throw new IllegalArgumentException("Unrecognised Number type: " + increment.getClass() + ". Allowed types: " + Arrays.toString(Type.values())); } return result; } Increment(); Increment(final Number increment); @Override Number apply(final Number input); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) Number getIncrement(); void setIncrement(final Number increment); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnIncrementIfInputIsNull() { Increment increment = new Increment(5); Number value = increment.apply(null); assertEquals(5, value); } @Test public void shouldReturnInputIfIncrementIsNull() { Increment increment = new Increment(); Number output = increment.apply(8); assertEquals(8, output); } @Test public void shouldMatchOutputTypeWithIncrementType() { Increment increment = new Increment(10L); Number output = increment.apply(2); assertEquals(Long.class, output.getClass()); } @Test public void shouldIncrementByTheSetIncrement() { Increment increment = new Increment(10L); Number output = increment.apply(2); assertEquals(12, output.intValue()); } @Test public void shouldBeAbleToHandleDifferentInputAndIncrementTypes() { Increment increment = new Increment(10.5); Number output = increment.apply(2); assertEquals(12.5, output); }
InputAdapted { protected AI adaptInput(final I input) { return inputAdapter == null ? (AI) input : inputAdapter.apply(input); } InputAdapted(); InputAdapted(final Function<I, AI> inputAdapter); Function<I, AI> getInputAdapter(); @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class") void setInputAdapter(final Function<I, AI> inputAdapter); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldApplyInputAdapterToInput() { Integer input = 5; InputAdapted<Object, Long> inputAdapted = new InputAdapted<>(new ToLong()); Long output = inputAdapted.adaptInput(input); assertEquals(Long.class, output.getClass()); assertEquals(5L, output); }
StateAgnosticOutputAdapter implements BiFunction<T, U, R> { @Override public R apply(final T ignoredState, final U output) { if (adapter == null) { return (R) output; } return adapter.apply(output); } StateAgnosticOutputAdapter(); StateAgnosticOutputAdapter(final Function<U, R> adapter); @Override R apply(final T ignoredState, final U output); Function<U, R> getAdapter(); void setAdapter(final Function<U, R> adapter); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnTheUnadaptedOutputIfNoAdapterIsProvided() { StateAgnosticOutputAdapter<Object, Object, Object> soa = new StateAgnosticOutputAdapter<>(); Object output = soa.apply(null, "input"); assertEquals("input", output); } @Test public void shouldApplyAnOutputAdapter() { StateAgnosticOutputAdapter<Object, Integer, Integer> soa = new StateAgnosticOutputAdapter<>(new MultiplyBy(10)); Object output = soa.apply(null, 10); assertEquals(100, output); }
SimpleClassDeserializer extends FromStringDeserializer<Class> { @Override protected Class<?> _deserialize(final String value, final DeserializationContext ctxt) throws IOException { try { return ctxt.findClass(SimpleClassNameIdResolver.getClassName(value)); } catch (final Exception e) { throw ctxt.instantiationException(_valueClass, ClassUtil.getRootCause(e)); } } SimpleClassDeserializer(); }
@Test public void shouldDeserialiseFromSimpleClassName() throws IOException, ClassNotFoundException { final SimpleClassDeserializer deserialiser = new SimpleClassDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = IsA.class; final String id = expectedClass.getSimpleName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = deserialiser._deserialize(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); } @Test public void shouldDeserialiseFromFullClassName() throws IOException, ClassNotFoundException { final SimpleClassDeserializer deserialiser = new SimpleClassDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = IsA.class; final String id = expectedClass.getName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = deserialiser._deserialize(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); } @Test public void shouldDeserialiseFromFullClassNameForUnknownClass() throws IOException, ClassNotFoundException { final SimpleClassDeserializer deserialiser = new SimpleClassDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = UnsignedLong.class; final String id = expectedClass.getName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = deserialiser._deserialize(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); }
SimpleClassKeySerializer extends StdKeySerializer { @Override public void serialize(final Object value, final JsonGenerator g, final SerializerProvider provider) throws IOException { String str; Class<?> cls = value.getClass(); if (cls == String.class) { str = (String) value; } else if (cls.isEnum()) { Enum<?> en = (Enum<?>) value; if (provider.isEnabled(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)) { str = en.toString(); } else { str = en.name(); } } else if (value instanceof Date) { provider.defaultSerializeDateKey((Date) value, g); return; } else if (cls == Class.class) { str = SimpleClassNameCache.getSimpleClassName(((Class<?>) value)); } else { str = value.toString(); } g.writeFieldName(str); } @Override void serialize(final Object value, final JsonGenerator g, final SerializerProvider provider); }
@Test public void shouldSerialiseToSimpleClassName() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(false); final SimpleClassKeySerializer serialiser = new SimpleClassKeySerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = IsA.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeFieldName(clazz.getSimpleName()); } @Test public void shouldSerialiseToFullClassName() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(true); final SimpleClassKeySerializer serialiser = new SimpleClassKeySerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = IsA.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeFieldName(clazz.getName()); } @Test public void shouldSerialiseToFullClassNameWhenUnknown() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(false); final SimpleClassKeySerializer serialiser = new SimpleClassKeySerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = UnsignedLong.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeFieldName(clazz.getName()); }
SimpleClassSerializer extends ClassSerializer { @Override public void serialize(final Class<?> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeString(SimpleClassNameCache.getSimpleClassName(value)); } static SimpleModule getModule(); @Override void serialize(final Class<?> value, final JsonGenerator jgen, final SerializerProvider provider); }
@Test public void shouldSerialiseToSimpleClassName() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(false); final SimpleClassSerializer serialiser = new SimpleClassSerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = IsA.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeString(clazz.getSimpleName()); } @Test public void shouldSerialiseToFullClassName() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(true); final SimpleClassSerializer serialiser = new SimpleClassSerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = IsA.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeString(clazz.getName()); } @Test public void shouldSerialiseToFullClassNameWhenUnknown() throws IOException { SimpleClassNameCache.setUseFullNameForSerialisation(false); final SimpleClassSerializer serialiser = new SimpleClassSerializer(); final JsonGenerator jgen = mock(JsonGenerator.class); final Class clazz = UnsignedLong.class; serialiser.serialize(clazz, jgen, null); verify(jgen).writeString(clazz.getName()); }
SimpleClassKeyDeserializer extends KeyDeserializer { @Override public Object deserializeKey(final String key, final DeserializationContext ctxt) throws IOException { try { return ctxt.findClass(SimpleClassNameIdResolver.getClassName(key)); } catch (final Exception e) { throw ctxt.mappingException("Cannot find class %s", key); } } @Override Object deserializeKey(final String key, final DeserializationContext ctxt); }
@Test public void shouldDeserialiseFromSimpleClassName() throws IOException, ClassNotFoundException { final SimpleClassKeyDeserializer deserialiser = new SimpleClassKeyDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = IsA.class; final String id = expectedClass.getSimpleName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = (Class<?>) deserialiser.deserializeKey(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); } @Test public void shouldDeserialiseFromFullClassName() throws IOException, ClassNotFoundException { final SimpleClassKeyDeserializer deserialiser = new SimpleClassKeyDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = IsA.class; final String id = expectedClass.getName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = (Class<?>) deserialiser.deserializeKey(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); } @Test public void shouldDeserialiseFromFullClassNameForUnknownClass() throws IOException, ClassNotFoundException { final SimpleClassKeyDeserializer deserialiser = new SimpleClassKeyDeserializer(); final DeserializationContext context = mock(DeserializationContext.class); final Class expectedClass = UnsignedLong.class; final String id = expectedClass.getName(); given(context.findClass(expectedClass.getName())).willReturn(expectedClass); final Class<?> clazz = (Class<?>) deserialiser.deserializeKey(id, context); assertEquals(expectedClass, clazz); verify(context).findClass(expectedClass.getName()); }
FunctionComposite extends Composite<C> implements Function<I, O> { @Override public O apply(final I input) { Object result = input; if (nonNull(components)) { for (final Function function : this.components) { result = function.apply(result); } } return (O) result; } FunctionComposite(); FunctionComposite(final List<C> functions); @JsonProperty("functions") List<C> getComponents(); @Override O apply(final I input); }
@Test public void shouldReturnInputIfNoComponentsAreProvided() { FunctionComposite<String, String, Function> functionComposite = new FunctionComposite<>(); String output = functionComposite.apply("test"); assertEquals("test", output); } @Test public void shouldApplyFunctionsInOrder() { FunctionComposite<String, Long, Function> functionComposite = new FunctionComposite<>(Arrays.asList( new ToLong(), new MultiplyLongBy(100L) )); Long transformed = functionComposite.apply("4"); assertEquals(400L, transformed); } @Test public void shouldThrowExceptionIfInputsAndOutputsDontMatch() { FunctionComposite<Integer, Long, Function> functionComposite = new FunctionComposite<>(Arrays.asList( new ToLong(), new StringSplit(" ") )); ClassCastException e = assertThrows(ClassCastException.class, () -> { functionComposite.apply(5); }); assertNotNull(e.getMessage()); }
StreamIterable implements CloseableIterable<T> { @Override public CloseableIterator<T> iterator() { return new StreamIterator<>(streamSupplier.get()); } StreamIterable(final Supplier<Stream<T>> streamSupplier); @Override void close(); @Override CloseableIterator<T> iterator(); @JsonIgnore Stream<T> getStream(); }
@Test public void shouldDelegateIteratorToIterable() { final Supplier<Stream<Object>> streamSupplier = mock(Supplier.class); final Stream<Object> stream = mock(Stream.class); given(streamSupplier.get()).willReturn(stream); final StreamIterable<Object> wrappedIterable = new StreamIterable<>(streamSupplier); final Iterator<Object> iterator = mock(Iterator.class); given(stream.iterator()).willReturn(iterator); final CloseableIterator<Object> result = wrappedIterable.iterator(); result.hasNext(); verify(iterator).hasNext(); }
ValidationResult { public boolean isValid() { return isValid; } ValidationResult(); ValidationResult(final String errorMsg); void addError(final String msg); void add(final ValidationResult validationResult); void add(final ValidationResult validationResult, final String errorMessage); boolean isValid(); Set<String> getErrors(); void logErrors(); void logWarns(); void logInfo(); void logDebug(); void logTrace(); @JsonIgnore String getErrorString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@Test public void shouldInitiallyBeValid() { ValidationResult validationResult = new ValidationResult(); boolean valid = validationResult.isValid(); assertTrue(valid); }
ValidationResult { public Set<String> getErrors() { if (null == errors) { return Collections.emptySet(); } return errors; } ValidationResult(); ValidationResult(final String errorMsg); void addError(final String msg); void add(final ValidationResult validationResult); void add(final ValidationResult validationResult, final String errorMessage); boolean isValid(); Set<String> getErrors(); void logErrors(); void logWarns(); void logInfo(); void logDebug(); void logTrace(); @JsonIgnore String getErrorString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@Test public void shouldReturnEmptySetIfValid() { ValidationResult validationResult = new ValidationResult(); Set<String> errors = validationResult.getErrors(); assertEquals(new HashSet<>(), errors); }
ValidationResult { @JsonIgnore public String getErrorString() { return "Validation errors: " + System.lineSeparator() + StringUtils.join(getErrors(), System.lineSeparator()); } ValidationResult(); ValidationResult(final String errorMsg); void addError(final String msg); void add(final ValidationResult validationResult); void add(final ValidationResult validationResult, final String errorMessage); boolean isValid(); Set<String> getErrors(); void logErrors(); void logWarns(); void logInfo(); void logDebug(); void logTrace(); @JsonIgnore String getErrorString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@Test public void shouldReturnStringForErrorStringIfNoErrorsArePresent() { ValidationResult validationResult = new ValidationResult(); String errorString = validationResult.getErrorString(); assertEquals("Validation errors: " + System.lineSeparator(), errorString); }
TupleOutputAdapter implements BiFunction<Tuple<R>, FO, Tuple<R>> { @Override public Tuple<R> apply(final Tuple<R> state, final FO output) { if (null == projection) { throw new IllegalArgumentException("Projection is required"); } if (null != state) { if (1 == projection.length) { state.put(projection[0], output); } else { int i = 0; for (final Object obj : (Iterable) output) { state.put(projection[i++], obj); } } } return state; } TupleOutputAdapter(); TupleOutputAdapter(final R[] projection); @Override Tuple<R> apply(final Tuple<R> state, final FO output); @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Cloning the array would be expensive - we will have to reply on users not modifying the array") void setProjection(final R[] projection); R[] getProjection(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldAddToTuple() { ArrayTuple state = new ArrayTuple(3); state.put(0, "thing"); state.put(1, 50L); TupleOutputAdapter<Integer, Object> adapter = new TupleOutputAdapter<>(new Integer[]{2}); Tuple<Integer> adapted = adapter.apply(state, "test"); assertEquals("test", adapted.get(2)); } @Test public void shouldReplaceAnyExistingValueInTuple() { ArrayTuple state = new ArrayTuple(3); state.put(0, "thing"); state.put(1, 50L); state.put(2, "Replace me"); TupleOutputAdapter<Integer, Object> adapter = new TupleOutputAdapter<>(new Integer[]{2}); Tuple<Integer> adapted = adapter.apply(state, "test"); assertEquals("test", adapted.get(2)); }
TupleInputAdapter extends KorypheFunction<Tuple<R>, FI> { @Override public FI apply(final Tuple<R> input) { if (null == selection) { throw new IllegalArgumentException("Selection is required"); } if (null != input) { if (1 == selection.length) { return (FI) input.get(selection[0]); } } return (FI) new ReferenceArrayTuple<>(input, selection); } TupleInputAdapter(); TupleInputAdapter(final R[] selection); @Override FI apply(final Tuple<R> input); R[] getSelection(); @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Cloning the array would be expensive - we will have to reply on users not modifying the array") void setSelection(final R[] selection); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void shouldReturnObjectIfSingleSelectionIsProvided() { MapTuple<String> objects = new MapTuple<>(); objects.put("one", 1); objects.put("two", 2); TupleInputAdapter<String, Object> inputAdapter = new TupleInputAdapter<>(new String[]{"one"}); Object adapted = inputAdapter.apply(objects); assertEquals(1, adapted); } @Test public void shouldReturnNullIfTheObjectReferencedDoesntExist() { MapTuple<String> objects = new MapTuple<>(); objects.put("one", 1); objects.put("two", 2); TupleInputAdapter<String, Object> inputAdapter = new TupleInputAdapter<>(new String[]{ "three" }); Object adapted = inputAdapter.apply(objects); assertNull(adapted); } @Test public void shouldReturnAReferenceArrayTupleIfMoreThanOneSelectionIsProvided() { MapTuple<String> objects = new MapTuple<>(); objects.put("one", 1); objects.put("two", 2); objects.put("three", 3); TupleInputAdapter<String, Object> inputAdapter = new TupleInputAdapter<>(new String[]{ "one", "two" }); Object adapted = inputAdapter.apply(objects); ReferenceArrayTuple<String> expected = new ReferenceArrayTuple<>(objects, new String[]{"one", "two"}); assertEquals(expected, adapted); }
DateUtil { public static Long parseTime(final String dateString) { return parseTime(dateString, TIME_ZONE_DEFAULT); } private DateUtil(); static TimeZone getTimeZoneDefault(); static Date parse(final String dateString); static Date parse(final String dateString, final TimeZone timeZone); static Long parseTime(final String dateString); static Long parseTime(final String dateString, final TimeZone timeZone); static final double MICROSECONDS_TO_MILLISECONDS; static final long SECONDS_TO_MILLISECONDS; static final long MINUTES_TO_MILLISECONDS; static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final String TIME_ZONE; }
@Test public void shouldParseTimestampInMilliseconds() { final long timestamp = System.currentTimeMillis(); final Long result = DateUtil.parseTime(Long.toString(timestamp)); assertEquals(timestamp, (long) result); } @Test public void shouldParseTimestampInMillisecondsWithTimeZone() { final long timestamp = System.currentTimeMillis(); final Long result = DateUtil.parseTime(Long.toString(timestamp), TimeZone.getTimeZone("Etc/GMT+6")); assertEquals(timestamp, (long) result); }
TupleAdaptedBinaryOperator extends AdaptedBinaryOperator<Tuple<R>, OT> { @JsonIgnore @Override public TupleInputAdapter<R, OT> getInputAdapter() { return (TupleInputAdapter<R, OT>) super.getInputAdapter(); } TupleAdaptedBinaryOperator(); TupleAdaptedBinaryOperator(final BinaryOperator<OT> binaryOperator, final R[] selection); R[] getSelection(); void setSelection(final R[] selection); @JsonIgnore @Override TupleInputAdapter<R, OT> getInputAdapter(); @JsonIgnore @Override TupleOutputAdapter<R, OT> getOutputAdapter(); }
@Test public void shouldJsonSerialiseAndDeserialise() throws IOException { TupleAdaptedBinaryOperator<String, Integer> binaryOperator = new TupleAdaptedBinaryOperator<>(); MockBinaryOperator function = new MockBinaryOperator(); TupleInputAdapter<String, Integer> inputAdapter = new TupleInputAdapter(); binaryOperator.setInputAdapter(inputAdapter); binaryOperator.setBinaryOperator(function); String json = JsonSerialiser.serialise(binaryOperator); TupleAdaptedBinaryOperator<String, Integer> deserialisedBinaryOperator = JsonSerialiser.deserialise(json, TupleAdaptedBinaryOperator.class); assertNotSame(binaryOperator, deserialisedBinaryOperator); BinaryOperator<Integer> deserialisedFunction = deserialisedBinaryOperator.getBinaryOperator(); assertNotSame(function, deserialisedFunction); assertTrue(deserialisedFunction instanceof MockBinaryOperator); Function<Tuple<String>, Integer> deserialisedInputMask = deserialisedBinaryOperator.getInputAdapter(); assertNotSame(inputAdapter, deserialisedInputMask); assertTrue(deserialisedInputMask instanceof Function); }
ReflectiveTuple implements Tuple<String> { @Override public Object get(final String reference) { requireNonNull(reference, "field reference is required"); if (reference.isEmpty()) { throw new IllegalArgumentException("field reference is required"); } if (THIS.equals(reference)) { return this; } Object selection; final int index = reference.indexOf("."); if (index > -1) { final String referencePart = reference.substring(0, index); selection = get(referencePart); final boolean hasNestedField = index + 1 < reference.length(); if (!hasNestedField) { throw new IllegalArgumentException("nested field reference is required"); } else { final Tuple<String> selectionAsTuple = selection instanceof Tuple ? ((Tuple) selection) : new ReflectiveTuple(selection); final String subReference = reference.substring(index + 1, reference.length()); selection = selectionAsTuple.get(subReference); } } else { try { selection = invokeMethodGet(record, reference); } catch (final IllegalAccessException | NoSuchMethodException | InvocationTargetException ignored) { try { selection = invokeFieldGet(record, reference); } catch (final IllegalAccessException | NoSuchFieldException ignore) { throw new RuntimeException(String.format(SELECTION_S_DOES_NOT_EXIST, reference)); } } } return selection; } ReflectiveTuple(final Object record); protected ReflectiveTuple(final Object record, final Cache<Field> fieldCache, final Cache<Method> methodCache); Object getRecord(); @Override Object get(final String reference); @Override void put(final String reference, final Object value); @Override Iterable<Object> values(); @Override boolean equals(final Object o); @Override int hashCode(); static final String SELECTION_S_DOES_NOT_EXIST; static final String ERROR_WRONG_PARAM; }
@Test public void shouldNotFindMissingField() { final Exception exception = assertThrows(RuntimeException.class, () -> testObj.get(FIELD_X)); assertEquals(String.format(SELECTION_S_DOES_NOT_EXIST, FIELD_X), exception.getMessage()); } @Test public void shouldNotFindMissingMethod() { final Exception exception = assertThrows(RuntimeException.class, () -> testObj.get("get" + FIELD_X)); assertEquals(String.format(SELECTION_S_DOES_NOT_EXIST, "get" + FIELD_X), exception.getMessage()); } @Test public void shouldFindPublicField() { assertEquals("fa", testObj.get(FIELD_A)); } @Test public void shouldNotFindPublicFieldIfSubfieldNameIsBlank() { testObj = new ReflectiveTuple(new ExampleNestedObj1()); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.get("nestedField.")); assertEquals("nested field reference is required", exception.getMessage()); } @Test public void shouldNotFindPublicFieldWithDotAtStart() { final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.get("." + FIELD_A)); assertEquals("field reference is required", exception.getMessage()); } @Test public void shouldNotFindPublicFieldWith2Dots() { testObj = new ReflectiveTuple(new ExampleNestedObj1()); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.get("nestedField.." + FIELD_A)); assertEquals("field reference is required", exception.getMessage()); } @Test public void shouldGetNestedField() { testObj = new ReflectiveTuple(new ExampleNestedObj1()); assertEquals("fa", testObj.get(NESTED_FIELD)); } @Test public void shouldNotFindPrivateField() { final Exception exception = assertThrows(RuntimeException.class, () -> testObj.get(FIELD_B)); assertEquals(String.format(SELECTION_S_DOES_NOT_EXIST, FIELD_B), exception.getMessage()); } @Test public void shouldFindPublicMethod() { assertEquals("ma", testObj.get("methodA")); } @Test public void shouldNotFindPrivateMethod() { final Exception exception = assertThrows(RuntimeException.class, () -> testObj.get(METHOD_B)); assertEquals(String.format(SELECTION_S_DOES_NOT_EXIST, METHOD_B), exception.getMessage()); } @Test public void shouldGetInOrderOfMethodGetIs() { testObj = new ReflectiveTuple(new ExampleObj2()); assertEquals("fa", testObj.get("valueA")); assertEquals("mb", testObj.get("valueB")); assertEquals("isc", testObj.get("valueC")); }
ReflectiveTuple implements Tuple<String> { @Override public void put(final String reference, final Object value) { requireNonNull(reference, "field reference is required"); if (reference.isEmpty()) { throw new IllegalArgumentException("field reference is required"); } final int index = reference.indexOf("."); if (index > -1) { final String referencePart = reference.substring(0, index); final boolean hasNestedField = index + 1 < reference.length(); if (!hasNestedField) { throw new IllegalArgumentException("nested field reference is required"); } final Object nestedField = get(referencePart); final Tuple<String> selectionAsTuple = nestedField instanceof Tuple ? ((Tuple) nestedField) : new ReflectiveTuple(nestedField); final String subReference = reference.substring(index + 1, reference.length()); selectionAsTuple.put(subReference, value); } else { try { invokeMethodPut(record, reference, value); } catch (final IllegalAccessException | NoSuchMethodException | InvocationTargetException ignored) { try { invokeFieldPut(record, reference, value); } catch (final IllegalAccessException | NoSuchFieldException ignore) { throw new RuntimeException(String.format(SELECTION_S_DOES_NOT_EXIST, reference)); } } } } ReflectiveTuple(final Object record); protected ReflectiveTuple(final Object record, final Cache<Field> fieldCache, final Cache<Method> methodCache); Object getRecord(); @Override Object get(final String reference); @Override void put(final String reference, final Object value); @Override Iterable<Object> values(); @Override boolean equals(final Object o); @Override int hashCode(); static final String SELECTION_S_DOES_NOT_EXIST; static final String ERROR_WRONG_PARAM; }
@Test public void shouldPutField() { final ExampleObj3 record = new ExampleObj3(); testObj = new ReflectiveTuple(record); testObj.put("fieldA", "changed"); assertEquals("changed", record.fieldA); } @Test public void shouldNotPutFieldWithWrongParam() { final ExampleObj3 record = new ExampleObj3(); testObj = new ReflectiveTuple(record); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.put("fieldA", 1)); final String expected = String.format(ReflectiveTuple.ERROR_WRONG_PARAM, "field", "fieldA", String.class, Integer.class.getSimpleName()); assertEquals(expected, exception.getMessage()); } @Test public void shouldPutMethod() { final ExampleObj3 record = new ExampleObj3(); testObj = new ReflectiveTuple(record); testObj.put("fieldB", "changed"); assertEquals("changed", record.fieldB); } @Test public void shouldNotPutFieldIfSubfieldIsBlank() { testObj = new ReflectiveTuple(new ExampleNestedObj1()); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.put("nestedField.", "changed")); assertEquals("nested field reference is required", exception.getMessage()); } @Test public void shouldNotPutFieldWithDotAtStart() { final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.put("." + FIELD_A, "changed")); assertEquals("field reference is required", exception.getMessage()); } @Test public void shouldNotPutFieldWith2Dots() { testObj = new ReflectiveTuple(new ExampleNestedObj1()); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.put("nestedField.." + FIELD_A, "changed")); assertEquals("field reference is required", exception.getMessage()); } @Test public void shouldNotPutMethodWithWrongParam() { final ExampleObj3 record = new ExampleObj3(); testObj = new ReflectiveTuple(record); final Exception exception = assertThrows(IllegalArgumentException.class, () -> testObj.put("fieldB", 1)); final String expected = String.format(ReflectiveTuple.ERROR_WRONG_PARAM, "method", "setFieldB", Collections.singletonList(String.class), Integer.class.getSimpleName()); assertEquals(expected, exception.getMessage()); } @Test public void shouldNotPutMethod() { final ExampleObj3 record = new ExampleObj3(); testObj = new ReflectiveTuple(record); final Exception exception = assertThrows(RuntimeException.class, () -> testObj.put("fieldC", 1)); assertEquals(String.format(ReflectiveTuple.SELECTION_S_DOES_NOT_EXIST, "fieldC"), exception.getMessage()); } @Test public void shouldPutNestedField() { final ExampleNestedObj1 record = new ExampleNestedObj1(); testObj = new ReflectiveTuple(record); testObj.put(NESTED_FIELD, "changed"); assertEquals("changed", record.getNestedField().fieldA); }
DateUtil { public static Date parse(final String dateString) { return parse(dateString, null); } private DateUtil(); static TimeZone getTimeZoneDefault(); static Date parse(final String dateString); static Date parse(final String dateString, final TimeZone timeZone); static Long parseTime(final String dateString); static Long parseTime(final String dateString, final TimeZone timeZone); static final double MICROSECONDS_TO_MILLISECONDS; static final long SECONDS_TO_MILLISECONDS; static final long MINUTES_TO_MILLISECONDS; static final long HOURS_TO_MILLISECONDS; static final long DAYS_TO_MILLISECONDS; static final String TIME_ZONE; }
@Test public void shouldParseDatesTimeZone() throws ParseException { final String dateString = "2017-01-02 01:02:30.123"; final String timeZone = "Etc/GMT+6"; final Date result = DateUtil.parse(dateString, TimeZone.getTimeZone(timeZone)); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); final Date expected = sdf.parse(dateString); assertEquals(expected, result); } @Test public void shouldNotParseInvalidDate() { final Exception exception = assertThrows(IllegalArgumentException.class, () -> DateUtil.parse("2017/1")); final String expected = "The provided date string 2017/1 could not be parsed. Please use a timestamp in " + "milliseconds or one of the following formats: [yyyy/MM, yyyy/MM/dd, yyyy/MM/dd HH, yyyy/MM/dd HH:mm, " + "yyyy/MM/dd HH:mm:ss, yyyy/MM/dd HH:mm:ss.SSS]. You can use a space, '-', '/', '_', ':', '|', or '.' " + "to separate the parts."; assertEquals(expected, exception.getMessage()); }
ReflectiveTuple implements Tuple<String> { @Override public Iterable<Object> values() { throw new UnsupportedOperationException("This " + getClass().getSimpleName() + " does not support listing all values."); } ReflectiveTuple(final Object record); protected ReflectiveTuple(final Object record, final Cache<Field> fieldCache, final Cache<Method> methodCache); Object getRecord(); @Override Object get(final String reference); @Override void put(final String reference, final Object value); @Override Iterable<Object> values(); @Override boolean equals(final Object o); @Override int hashCode(); static final String SELECTION_S_DOES_NOT_EXIST; static final String ERROR_WRONG_PARAM; }
@Test public void shouldNotValues() { assertThrows(UnsupportedOperationException.class, () -> testObj.values()); }
StringContains extends KoryphePredicate<String> { @Override public boolean test(final String input) { if (null == input || null == value) { return false; } if (ignoreCase) { return StringUtils.containsIgnoreCase(input, value); } return input.contains(value); } StringContains(); StringContains(final String value); StringContains(final String value, final boolean ignoreCase); String getValue(); void setValue(final String value); boolean getIgnoreCase(); void setIgnoreCase(final boolean ignoreCase); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void shouldAcceptWhenStringInValue() { final StringContains stringContains = new StringContains("used"); boolean accepted = stringContains.test(INPUT); assertTrue(accepted); } @Test public void shouldRejectMismatchedCases() { final StringContains stringContains = new StringContains("stringcontains"); boolean accepted = stringContains.test(INPUT); assertFalse(accepted); } @Test public void shouldAcceptEmptyString() { final StringContains stringContains = new StringContains(""); boolean accepted = stringContains.test(INPUT); assertTrue(accepted); } @Test public void shouldRejectNullValue() { final StringContains stringContains = new StringContains(null); boolean accepted = stringContains.test(INPUT); assertFalse(accepted); } @Test public void shouldRejectNullInput() { final StringContains stringContains = new StringContains("test"); boolean accepted = stringContains.test(null); assertFalse(accepted); }
StringContains extends KoryphePredicate<String> { public String getValue() { return value; } StringContains(); StringContains(final String value); StringContains(final String value, final boolean ignoreCase); String getValue(); void setValue(final String value); boolean getIgnoreCase(); void setIgnoreCase(final boolean ignoreCase); @Override boolean test(final String input); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }
@Override @Test public void shouldJsonSerialiseAndDeserialise() throws IOException { final String value = "stringcontains"; final StringContains filter = new StringContains(value); final String json = JsonSerialiser.serialise(filter); JsonSerialiser.assertEquals(String.format("{%n" + " \"class\" : \"uk.gov.gchq.koryphe.impl.predicate.StringContains\",%n" + " \"value\" : \"stringcontains\",%n" + " \"ignoreCase\" : false%n" + "}"), json); final StringContains deserialisedFilter = JsonSerialiser.deserialise(json, StringContains.class); assertNotNull(deserialisedFilter); assertEquals(value, deserialisedFilter.getValue()); }
TemplatingFunctions { public ContentMap asContentMap(Node content) { return content == null ? null : new ContentMap(content); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testAsContentMapfromNode() throws RepositoryException { ContentMap result = functions.asContentMap(topPage); assertMapEqualsNode(topPage, result); }
TemplatingFunctions { public boolean isEditMode() { return isAuthorInstance() && !isPreviewMode(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testIsEditModeNotAuthorAndPreview() { boolean res = false; setAdminMode(false); setEditMode(true); res = functions.isEditMode(); assertFalse("Should not be in Edit Mode ", res); } @Test public void testIsEditModeAuthorAndNotPreview() { boolean res = false; setAdminMode(true); setEditMode(false); res = functions.isEditMode(); assertTrue("Should be in Edit Mode ", res); } @Test public void testIsEditModeNotAuthorAndNotPreview() { boolean res = false; setAdminMode(false); setEditMode(false); res = functions.isEditMode(); assertFalse("Should not be in Edit Mode ", res); } @Test public void testIsEditModeAuthorAndPreview() { boolean res = false; setAdminMode(true); setEditMode(true); res = functions.isEditMode(); assertFalse("Should not be in Edit Mode ", res); }
TemplatingFunctions { public boolean isPreviewMode() { return this.aggregationStateProvider.get().isPreviewMode(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testIsPreviewModeTrue() { boolean res = false; setEditMode(true); res = functions.isPreviewMode(); assertTrue("Should be in Preview Mode ", res); } @Test public void testIsPreviewModeFalse() { boolean res = false; setEditMode(false); res = functions.isPreviewMode(); assertFalse("Should Not be in Preview Mode ", res); }
TemplatingFunctions { public boolean isAuthorInstance() { return Components.getComponent(ServerConfiguration.class).isAdmin(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testIsAuthorInstanceTrue() { boolean res = false; setAdminMode(true); res = functions.isAuthorInstance(); assertTrue("should be Author ", res); } @Test public void testIsAuthorInstanceFalse() { boolean res = true; setAdminMode(false); res = functions.isAuthorInstance(); assertFalse("should not be Author ", res); }
TemplatingFunctions { public boolean isPublicInstance() { return !isAuthorInstance(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testIsPublicInstanceTrue() { boolean res = true; setAdminMode(true); res = functions.isPublicInstance(); assertFalse("should be Public ", res); } @Test public void testIsPublicInstanceFalse() { boolean res = false; setAdminMode(false); res = functions.isPublicInstance(); assertTrue("should not be Public ", res); }
TemplatingFunctions { public String createHtmlAttribute(String name, String value) { value = StringUtils.trim(value); if (StringUtils.isNotEmpty(value)) { return new StringBuffer().append(name).append("=\"").append(value).append("\"").toString(); } return StringUtils.EMPTY; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testCreateHtmlAttribute(){ String value = " value "; String name = "name"; String res = functions.createHtmlAttribute(name, value); assertEquals(name+"=\""+value.trim()+"\"", res); } @Test public void testCreateHtmlAttributeNoValue(){ String value = ""; String name = "name"; String res = functions.createHtmlAttribute(name, value); assertEquals("", res); }
TemplatingFunctions { public ContentMap root(ContentMap contentMap) throws RepositoryException { return contentMap == null ? null : asContentMap(this.root(contentMap.getJCRNode())); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testRootFromPageNodeDepth3() throws RepositoryException { Node resultNode = functions.root(childPageSubPage); assertNodeEqualsNode(root, resultNode); } @Test public void testRootFromComponentNodeDepth1() throws RepositoryException { Node resultNode = functions.root(topPageComponent); assertNodeEqualsNode(root, resultNode); } @Test public void testRootFromComponentNodeDepth2() throws RepositoryException { Node resultNode = functions.root(childPageComponent); assertNodeEqualsNode(root, resultNode); } @Test public void testRootPageFromPageNodeDepth1() throws RepositoryException { Node resultNode = functions.root(topPage, NodeTypes.Page.NAME); assertNull(resultNode); } @Test public void testRootPageFromPageNodeDepth2() throws RepositoryException { Node resultNode = functions.root(childPage, NodeTypes.Page.NAME); assertNodeEqualsNode(topPage, resultNode); } @Test public void testRootPageFromPageNodeDepth3() throws RepositoryException { Node resultNode = functions.root(childPageSubPage, NodeTypes.Page.NAME); assertNodeEqualsNode(topPage, resultNode); } @Test public void testRootPageFromComponentNodeDepth1() throws RepositoryException { Node resultNode = functions.root(topPageComponent, NodeTypes.Page.NAME); assertNodeEqualsNode(topPage, resultNode); } @Test public void testRootPageFromComponentNodeDepth2() throws RepositoryException { Node resultNode = functions.root(childPageComponent, NodeTypes.Page.NAME); assertNodeEqualsNode(topPage, resultNode); } @Test public void testRootFromPageContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.root(topPageContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testRootFromPageContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testRootFromPageContentMapDepth3() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageSubPageContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testRootFromComponentContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.root(topPageComponentContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testRootFromComponentContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageComponentContentMap); assertMapEqualsMap(rootContentMap, resultContentMap); } @Test public void testRootPageFromPageContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.root(topPageContentMap, NodeTypes.Page.NAME); assertNull(resultContentMap); } @Test public void testRootPageFromPageContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testRootPageFromPageContentMapDepth3() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageSubPageContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testRootPageFromComponentContentMapDepth1() throws RepositoryException { ContentMap resultContentMap = functions.root(topPageComponentContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testRootPageFromComponentContentMapDepth2() throws RepositoryException { ContentMap resultContentMap = functions.root(childPageComponentContentMap, NodeTypes.Page.NAME); assertMapEqualsMap(topPageContentMap, resultContentMap); } @Test public void testRootFromPageNodeDepth1() throws RepositoryException { Node resultNode = functions.root(topPage); assertNodeEqualsNode(root, resultNode); } @Test public void testRootFromPageNodeDepth2() throws RepositoryException { Node resultNode = functions.root(childPage); assertNodeEqualsNode(root, resultNode); }
TemplatingFunctions { public SiblingsHelper siblings(Node node) throws RepositoryException { return SiblingsHelper.of(ContentUtil.asContent(node)); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testSiblings() throws RepositoryException{ SiblingsHelper s = functions.siblings(topPage); assertEquals("Indexes are 0-based ", 0, s.getIndex()); s.next(); s.next(); assertEquals("Should have skipped nodes of different type.",2, s.getIndex()); } @Test public void testSiblingsContentMap() throws RepositoryException{ SiblingsHelper s = functions.siblings(topPageContentMap); assertEquals("Indexes are 0-based ", 0, s.getIndex()); s.next(); s.next(); assertEquals("Should have skipped nodes of different type.",2, s.getIndex()); }
TemplatingFunctions { public Node contentByIdentifier(String id){ return contentByIdentifier(RepositoryConstants.WEBSITE, id); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testGetContentByIdentifier() throws RepositoryException{ String id = childPage.getIdentifier(); Session session = childPage.getSession(); MockUtil.setSessionAndHierarchyManager(session); String repository = session.getWorkspace().getName(); Node returnedNode1 = functions.contentByIdentifier(repository, id); assertEquals(childPage, returnedNode1); Node returnedNode2 = functions.contentByIdentifier(id); assertEquals(childPage, returnedNode2); }
AbstractContentTemplatingElement extends AbstractTemplatingElement { protected void setAttributesInWebContext(final Map<String, Object> attributes, int scope) { if(attributes == null){ return; } switch(scope) { case WebContext.APPLICATION_SCOPE: case WebContext.SESSION_SCOPE: case WebContext.LOCAL_SCOPE: break; default: throw new IllegalArgumentException("Scope is not valid. Use one of the scopes defined in info.magnolia.context.WebContext"); } final WebContext webContext = MgnlContext.getWebContext(); for(Entry<String, Object> entry : attributes.entrySet()) { final String key = entry.getKey(); if(webContext.containsKey(key)) { savedCtxAttributes.put(key, webContext.get(key)); } webContext.setAttribute(key, entry.getValue(), scope); } } AbstractContentTemplatingElement(ServerConfiguration server, RenderingContext renderingContext); Node getContent(); void setContent(Node node); String getWorkspace(); void setWorkspace(String workspace); String getNodeIdentifier(); void setNodeIdentifier(String nodeIdentifier); String getPath(); void setPath(String path); }
@Test public void testSetAttributesInWebContext() throws Exception { final RenderingContext aggregationState = mock(RenderingContext.class); final WebContext ctx = new MockWebContext(); ctx.setAttribute("foo", "foo value", WebContext.LOCAL_SCOPE); ctx.setAttribute("bar", 1, WebContext.LOCAL_SCOPE); ctx.setAttribute("baz", true, WebContext.LOCAL_SCOPE); MgnlContext.setInstance(ctx); assertEquals(3, ctx.getAttributes().size()); final AbstractContentTemplatingElement compo = new DummyComponent(null, aggregationState); Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("foo", "new foo"); attributes.put("qux", "blah"); compo.setAttributesInWebContext(attributes, WebContext.LOCAL_SCOPE); assertEquals(4, ctx.getAttributes().size()); assertEquals("new foo", ctx.getAttribute("foo")); assertEquals("blah", ctx.getAttribute("qux")); }
AbstractContentTemplatingElement extends AbstractTemplatingElement { protected void restoreAttributesInWebContext(final Map<String, Object> attributes, int scope) { if(attributes == null) { return; } switch(scope) { case WebContext.APPLICATION_SCOPE: case WebContext.SESSION_SCOPE: case WebContext.LOCAL_SCOPE: break; default: throw new IllegalArgumentException("Scope is not valid. Use one of the scopes defined in info.magnolia.context.WebContext"); } final WebContext webContext = MgnlContext.getWebContext(); for(Entry<String, Object> entry : attributes.entrySet()) { final String key = entry.getKey(); if(webContext.containsKey(key) && savedCtxAttributes.get(key) != null) { webContext.setAttribute(key, savedCtxAttributes.get(key), scope); continue; } webContext.removeAttribute(key, scope); } } AbstractContentTemplatingElement(ServerConfiguration server, RenderingContext renderingContext); Node getContent(); void setContent(Node node); String getWorkspace(); void setWorkspace(String workspace); String getNodeIdentifier(); void setNodeIdentifier(String nodeIdentifier); String getPath(); void setPath(String path); }
@Test public void testRestoreAttributesInWebContext() throws Exception { final RenderingContext aggregationState = mock(RenderingContext.class); final WebContext ctx = new MockWebContext(); ctx.setAttribute("foo", "foo value", WebContext.LOCAL_SCOPE); ctx.setAttribute("bar", 1, WebContext.LOCAL_SCOPE); ctx.setAttribute("baz", true, WebContext.LOCAL_SCOPE); MgnlContext.setInstance(ctx); assertEquals(3, ctx.getAttributes().size()); final AbstractContentTemplatingElement compo = new DummyComponent(null, aggregationState); Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("foo", "new foo"); attributes.put("qux", "blah"); compo.setAttributesInWebContext(attributes, WebContext.LOCAL_SCOPE); assertEquals(4, ctx.getAttributes().size()); assertEquals("new foo", ctx.getAttribute("foo")); assertEquals("blah", ctx.getAttribute("qux")); compo.restoreAttributesInWebContext(attributes, WebContext.LOCAL_SCOPE); assertEquals(3, ctx.getAttributes().size()); assertEquals("foo value", ctx.getAttribute("foo")); assertNull(ctx.getAttribute("qux")); }
InitElement extends AbstractContentTemplatingElement { @Override public void begin(Appendable out) throws IOException, RenderException { if (!isAdmin()) { return; } Node content = getPassedContent(); if(content == null){ content = currentContent(); } TemplateDefinition templateDefinition = getRequiredTemplateDefinition(); dialog = resolveDialog(templateDefinition); Sources src = new Sources(MgnlContext.getContextPath()); MarkupHelper helper = new MarkupHelper(out); helper.append("<!-- begin js and css added by @cms.init -->\n"); helper.append("<meta name=\"gwt:property\" content=\"locale=" + i18nContentSupport.getLocale() +"\"/>\n"); helper.append(src.getHtmlCss()); helper.append(src.getHtmlJs()); helper.openComment(CMS_PAGE_TAG); if(content != null) { helper.attribute(AreaDirective.CONTENT_ATTRIBUTE, getNodePath(content)); } helper.attribute("dialog", dialog); helper.attribute("preview", String.valueOf(MgnlContext.getAggregationState().isPreviewMode())); if (i18nAuthoringSupport.isEnabled() && i18nContentSupport.isEnabled() && i18nContentSupport.getLocales().size()>1){ Content currentPage = MgnlContext.getAggregationState().getMainContent(); String currentUri = createURI(currentPage, i18nContentSupport.getLocale()); helper.attribute("currentURI", currentUri); List<String> availableLocales = new ArrayList<String>(); for (Locale locale : i18nContentSupport.getLocales()) { String uri = createURI(currentPage, locale); String label = StringUtils.capitalize(locale.getDisplayLanguage(locale)); if(StringUtils.isNotEmpty(locale.getCountry())){ label += " (" + StringUtils.capitalize(locale.getDisplayCountry()) + ")"; } availableLocales.add(label + ":" + uri); } helper.attribute("availableLocales", StringUtils.join(availableLocales, ",")); } helper.append(" -->\n"); helper.closeComment(CMS_PAGE_TAG); } InitElement(ServerConfiguration server, RenderingContext renderingContext); @Override void begin(Appendable out); @Override void end(Appendable out); void setDialog(String dialog); static final String PAGE_EDITOR_JS_SOURCE; static final String PAGE_EDITOR_CSS; }
@Test @Ignore("See SCRUM-1239. Will most likely be removed in 5.0") public void testOutputContainsPageEditorJavascript() throws Exception { element.begin(out); assertThat(out.toString(), containsString(InitElement.PAGE_EDITOR_JS_SOURCE)); } @Test public void testOutputContainsSourcesJavascript() throws Exception { element.begin(out); assertThat(out.toString(), containsString("/.magnolia/pages/javascript.js")); assertThat(out.toString(), containsString("/.resources/admin-js/dialogs/dialogs.js")); } @Test public void testOutputContainsSourcesCss() throws Exception { element.begin(out); assertThat(out.toString(), containsString("/.resources/admin-css/admin-all.css")); } @Test public void testOutputContainsGwtLocaleMetaProperty() throws Exception { element.begin(out); assertThat(out.toString(), containsString("<meta name=\"gwt:property\" content=\"locale=en\"/>")); } @Test @Ignore("See SCRUM-1239. Will most likely be removed in 5.0") public void testOutputContainsPageEditorStyles() throws Exception { element.begin(out); assertThat(out.toString(), containsString(InitElement.PAGE_EDITOR_CSS)); } @Test public void testOutputContainsContent() throws Exception { element.begin(out); assertThat(out.toString(), containsString("<!-- cms:page content=\"website:/foo/bar/paragraphs\" dialog=\"dialog\" preview=\"false\" -->")); assertThat(out.toString(), containsString("<!-- /cms:page -->")); } @Test public void testOutputWithoutContent() throws Exception { getAggregationState().setCurrentContent(null); element.begin(out); assertThat(out.toString(), containsString("<!-- cms:page dialog=\"dialog\" preview=\"false\" -->")); }
InitElement extends AbstractContentTemplatingElement { @Override public void end(Appendable out) throws IOException, RenderException { if (!isAdmin()) { return; } MarkupHelper helper = new MarkupHelper(out); helper.append("\n<!-- end js and css added by @cms.init -->\n"); } InitElement(ServerConfiguration server, RenderingContext renderingContext); @Override void begin(Appendable out); @Override void end(Appendable out); void setDialog(String dialog); static final String PAGE_EDITOR_JS_SOURCE; static final String PAGE_EDITOR_CSS; }
@Test public void testOutputEndPart() throws Exception { element.end(out); assertThat(out.toString(), containsString("<!-- end js and css added by @cms.init -->")); }
ComponentElement extends AbstractContentTemplatingElement { @Override public void begin(Appendable out) throws IOException, RenderException { content = getPassedContent(); if(content == null) { throw new RenderException("The 'content' or 'workspace' and 'path' attribute have to be set to render a component."); } if(isAdmin() && hasPermission(content)){ try { this.componentDefinition = templateDefinitionAssignment.getAssignedTemplateDefinition(content); } catch (RegistrationException e) { throw new RenderException("No template definition found for the current content", e); } final Messages messages = MessagesManager.getMessages(componentDefinition.getI18nBasename()); if (isRenderEditbar()) { MarkupHelper helper = new MarkupHelper(out); helper.openComment("cms:component"); helper.attribute(AreaDirective.CONTENT_ATTRIBUTE, getNodePath(content)); if(content instanceof InheritanceNodeWrapper) { if (((InheritanceNodeWrapper) content).isInherited()) { helper.attribute("inherited", "true"); } } this.editable = resolveEditable(); if (this.editable != null) { helper.attribute("editable", String.valueOf(this.editable)); } if(StringUtils.isEmpty(dialog)) { dialog = resolveDialog(); } helper.attribute("dialog", dialog); String label = StringUtils.defaultIfEmpty(componentDefinition.getTitle(),componentDefinition.getName()); helper.attribute("label", messages.getWithDefault(label, label)); if(StringUtils.isNotEmpty(componentDefinition.getDescription())){ helper.attribute("description", componentDefinition.getDescription()); } helper.append(" -->\n"); } } WebContext webContext = MgnlContext.getWebContext(); webContext.push(webContext.getRequest(), webContext.getResponse()); setAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE); try { if(componentDefinition != null) { renderingEngine.render(content, componentDefinition, new HashMap<String, Object>(), new AppendableOnlyOutputProvider(out)); } else { renderingEngine.render(content, new AppendableOnlyOutputProvider(out)); } } finally { webContext.pop(); webContext.setPageContext(null); restoreAttributesInWebContext(contextAttributes, WebContext.LOCAL_SCOPE); } } @Inject ComponentElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine, TemplateDefinitionAssignment templateDefinitionAssignment ); @Override void begin(Appendable out); @Override void end(Appendable out); Map<String, Object> getContextAttributes(); void setContextAttributes(Map<String, Object> contextAttributes); void setDialog(String dialog); void setEditable(Boolean editable); Boolean getEditable(); boolean isRenderEditbar(); void setRenderEditbar(boolean renderEditbar); }
@Test public void testRenderBeginOnlyContent() throws Exception { element.setContent(getComponentNode()); element.begin(out); assertEquals("<!-- cms:component content=\"website:/foo/bar/paragraphs/0\" dialog=\"dialog\" label=\"Title\" description=\"Description\" -->\n", out.toString()); }
ComponentElement extends AbstractContentTemplatingElement { @Override public void end(Appendable out) throws IOException, RenderException { if(isAdmin()){ if (renderEditbar) { new MarkupHelper(out).closeComment("cms:component"); } } } @Inject ComponentElement(ServerConfiguration server, RenderingContext renderingContext, RenderingEngine renderingEngine, TemplateDefinitionAssignment templateDefinitionAssignment ); @Override void begin(Appendable out); @Override void end(Appendable out); Map<String, Object> getContextAttributes(); void setContextAttributes(Map<String, Object> contextAttributes); void setDialog(String dialog); void setEditable(Boolean editable); Boolean getEditable(); boolean isRenderEditbar(); void setRenderEditbar(boolean renderEditbar); }
@Test public void testPostRender() throws Exception { element.end(out); assertEquals("<!-- /cms:component -->\n", out.toString()); }
MarkupHelper implements Appendable { public MarkupHelper attribute(String name, String value) throws IOException { if (value != null) { appendable.append(SPACE).append(name).append(EQUALS).append(QUOTE).append(value).append(QUOTE); } return this; } MarkupHelper(Appendable appendable); MarkupHelper attribute(String name, String value); MarkupHelper startContent(Node node); MarkupHelper endContent(Node node); MarkupHelper openTag(String tagName); MarkupHelper closeTag(String tagName); MarkupHelper openComment(String tagName); MarkupHelper closeComment(String tagName); @Override Appendable append(CharSequence charSequence); @Override Appendable append(CharSequence charSequence, int i, int i1); @Override Appendable append(char c); }
@Test public void testParam() throws Exception { final StringWriter out = new StringWriter(); final MarkupHelper compo = new MarkupHelper(out); final String paramName = "param1"; final String paramValue = "value1"; compo.attribute(paramName, paramValue); assertEquals(out.toString(), " param1=\"value1\"", out.toString()); } @Test public void testParamsKeepCamelCaseNotation() throws Exception { final StringWriter out = new StringWriter(); final MarkupHelper compo = new MarkupHelper(out); final String paramName = "iAmACamelCaseParamName"; final String paramValue = "iAmACamelCaseParamValue"; compo.attribute(paramName, paramValue); assertEquals(out.toString(), " iAmACamelCaseParamName=\"iAmACamelCaseParamValue\"", out.toString()); }
AbstractDirective implements TemplateDirectiveModel { protected void checkBody(TemplateDirectiveBody body, boolean needsBody) throws TemplateModelException { if ((body == null) == needsBody) { throw new TemplateModelException("This directive " + (needsBody ? "needs a body" : "does not support a body")); } } @Override void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body); static final String PATH_ATTRIBUTE; static final String UUID_ATTRIBUTE; static final String WORKSPACE_ATTRIBUTE; static final String CONTENT_ATTRIBUTE; }
@Test public void testBodyCheck() throws TemplateModelException { final TemplateDirectiveBody dummyDirBody = new TemplateDirectiveBody() { @Override public void render(Writer out) throws TemplateException, IOException { } }; final AbstractDirective dir = new TestAbstractDirective(); dir.checkBody(null, false); dir.checkBody(dummyDirBody, true); try { dir.checkBody(null, true); fail("should have failed"); } catch (TemplateModelException e) { assertEquals("This directive needs a body", e.getMessage()); } try { dir.checkBody(dummyDirBody, false); fail("should have failed"); } catch (TemplateModelException e) { assertEquals("This directive does not support a body", e.getMessage()); } }
AbstractDirective implements TemplateDirectiveModel { protected void initContentElement(Map<String, TemplateModel> params, AbstractContentTemplatingElement component) throws TemplateModelException { Node content = node(params, CONTENT_ATTRIBUTE, null); String workspace = string(params, WORKSPACE_ATTRIBUTE, null); String nodeIdentifier = string(params, UUID_ATTRIBUTE, null); String path = string(params, PATH_ATTRIBUTE, null); component.setContent(content); component.setWorkspace(workspace); component.setNodeIdentifier(nodeIdentifier); component.setPath(path); } @Override void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body); static final String PATH_ATTRIBUTE; static final String UUID_ATTRIBUTE; static final String WORKSPACE_ATTRIBUTE; static final String CONTENT_ATTRIBUTE; }
@Test public void testInitContentComponent() throws TemplateModelException { final AbstractDirective dir = new TestAbstractDirective(); AbstractContentTemplatingElement component = mock(AbstractContentTemplatingElement.class); Map<String, TemplateModel> params = new LinkedHashMap<String, TemplateModel>(); dir.initContentElement(params, component); }
AppendableWriter extends Writer { @Override public void write(char[] chars, int start, int end) throws IOException { appendable.append(new String(chars), start, end); } AppendableWriter(Appendable appendable); @Override void close(); @Override void flush(); @Override void write(char[] chars, int start, int end); }
@Test public void testWrite() throws IOException { StringBuilder builder = new StringBuilder(); AppendableWriter writer = new AppendableWriter(builder); try { writer.append("superLongWord", 5, 9); assertEquals("Long", builder.toString()); } finally { writer.close(); } }
CopyGenerator implements Generator<AutoGenerationConfiguration> { @Override public void generate(AutoGenerationConfiguration autoGenerationConfig) throws RenderException { if(autoGenerationConfig == null) { throw new IllegalArgumentException("Expected an instance of AutoGenerationConfiguration but got null instead"); } createNode(parent, autoGenerationConfig.getContent()); } CopyGenerator(final Node parent); @Override void generate(AutoGenerationConfiguration autoGenerationConfig); }
@Test public void testSameLevelNodesCreation() throws Exception{ Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> firstNodeProps = new HashMap<String, Object>(); firstNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); firstNodeProps.put(TEMPLATE_ID, null); firstNodeProps.put("anotherProp", "some value"); content.put("autogen-foo", firstNodeProps); Map<String, Object> secondNodeProps = new HashMap<String, Object>(); secondNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); secondNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); secondNodeProps.put("someProp", "a different value"); content.put("same-level-autogen", secondNodeProps); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); Node newNode = session.getNode("/foo/autogen-foo"); assertNodeAndMetaData(newNode, null, USER_NAME); assertPropertyEquals(newNode, "anotherProp", "some value", PropertyType.STRING); Node secondNode = session.getNode("/foo/same-level-autogen"); assertNodeAndMetaData(secondNode, TEMPLATE_ID_VALUE, USER_NAME); assertPropertyEquals(secondNode, "someProp", "a different value", PropertyType.STRING); } @Test public void testNestedNodesCreation() throws Exception { Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> firstNodeProps = new HashMap<String, Object>(); firstNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); firstNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); firstNodeProps.put("anotherProp", "some value"); Map<String, Object> nestedNodeProps = new HashMap<String, Object>(); nestedNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); nestedNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); nestedNodeProps.put("someProp", "a different value"); Map<String, Object> nestedSubNodeProps = new HashMap<String, Object>(); nestedSubNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); nestedSubNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); nestedNodeProps.put("nestedSubNode-autogen", nestedSubNodeProps); firstNodeProps.put("nested-autogen", nestedNodeProps); content.put("autogen-foo", firstNodeProps); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); Node newNode = session.getNode("/foo/autogen-foo"); assertNodeAndMetaData(newNode, TEMPLATE_ID_VALUE, USER_NAME); assertPropertyEquals(newNode, "anotherProp", "some value", PropertyType.STRING); Node secondNode = session.getNode("/foo/autogen-foo/nested-autogen"); assertNodeAndMetaData(secondNode, TEMPLATE_ID_VALUE, USER_NAME); assertPropertyEquals(secondNode, "someProp", "a different value", PropertyType.STRING); Node secondSubNode = session.getNode("/foo/autogen-foo/nested-autogen/nestedSubNode-autogen"); assertNodeAndMetaData(secondSubNode, TEMPLATE_ID_VALUE, USER_NAME); } @Test public void testSameLevelNestedNodesCreation() throws Exception { Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> firstNodeProps = new HashMap<String, Object>(); firstNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); firstNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); content.put("autogen-foo", firstNodeProps); Map<String, Object> sameLevelNodeProps = new HashMap<String, Object>(); sameLevelNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); sameLevelNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); content.put("same-level-autogen-foo", sameLevelNodeProps); Map<String, Object> nestedNodeProps = new HashMap<String, Object>(); nestedNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); nestedNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); firstNodeProps.put("nested-autogen", nestedNodeProps); Map<String, Object> sameLevelNestedNodeProps = new HashMap<String, Object>(); sameLevelNestedNodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); sameLevelNestedNodeProps.put(TEMPLATE_ID, TEMPLATE_ID_VALUE); firstNodeProps.put("same-level-as-nested", sameLevelNestedNodeProps); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); Node newNode = session.getNode("/foo/autogen-foo"); assertNodeAndMetaData(newNode, TEMPLATE_ID_VALUE, USER_NAME); Node secondNode = session.getNode("/foo/same-level-autogen-foo"); assertNodeAndMetaData(secondNode, TEMPLATE_ID_VALUE, USER_NAME); Node nestedNode = session.getNode("/foo/autogen-foo/nested-autogen"); assertNodeAndMetaData(nestedNode, TEMPLATE_ID_VALUE, USER_NAME); Node sameLevelAsNested = session.getNode("/foo/autogen-foo/same-level-as-nested"); assertNodeAndMetaData(sameLevelAsNested, TEMPLATE_ID_VALUE, USER_NAME); } @Test(expected=RenderException.class) public void testGenerateThrowsRenderExceptionIfNodeTypeIsNotFound() throws Exception { Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> nodeConfig = new HashMap<String, Object>(); nodeConfig.put("foo", "bar"); content.put("autogen-foo", nodeConfig); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); } @Test public void testNewPropertyValueIsNotOverwritten() throws Exception{ Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> nodeProps = new HashMap<String, Object>(); nodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); nodeProps.put(TEMPLATE_ID, null); nodeProps.put("someProp", "original value"); content.put("autogen-foo", nodeProps); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); Node newNode = session.getNode("/foo/autogen-foo"); assertPropertyEquals(newNode, "someProp", "original value", PropertyType.STRING); newNode.getProperty("someProp").setValue("a different value"); newNode.getSession().save(); assertPropertyEquals(newNode, "someProp", "a different value", PropertyType.STRING); new CopyGenerator(parent).generate(config); assertPropertyEquals(newNode, "someProp", "a different value", PropertyType.STRING); } @Test public void testCreateDifferentPropertyTypes() throws Exception{ Node parent = session.getNode("/foo"); AutoGenerationConfiguration config = mock(AutoGenerationConfiguration.class); Map<String, Object> content = new HashMap<String, Object>(); Map<String, Object> nodeProps = new HashMap<String, Object>(); nodeProps.put(NODE_TYPE, NodeTypes.ContentNode.NAME); nodeProps.put(TEMPLATE_ID, null); nodeProps.put("stringProp", "a string"); nodeProps.put("booleanProp", true); nodeProps.put("longProp", 100L); nodeProps.put("doubleProp", 3.14d); nodeProps.put("calendarProp", Calendar.getInstance()); content.put("autogen-foo", nodeProps); when(config.getContent()).thenReturn(content); new CopyGenerator(parent).generate(config); Node newNode = session.getNode("/foo/autogen-foo"); assertPropertyEquals(newNode, "stringProp", "a string", PropertyType.STRING); assertPropertyEquals(newNode, "booleanProp", true, PropertyType.BOOLEAN); assertPropertyEquals(newNode, "longProp", 100L, PropertyType.LONG); assertPropertyEquals(newNode, "doubleProp", 3.14d, PropertyType.DOUBLE); assertPropertyEquals(newNode, "calendarProp", null, PropertyType.DATE); }