src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
EuGrantTransferRestServiceImpl extends BaseRestService implements EuGrantTransferRestService { @Override public RestResult<Void> deleteGrantAgreement(long applicationId) { String url = format("%s/%s/%s", REST_URL, "grant-agreement", applicationId); return deleteWithRestResult(url); } @Override RestResult<Void> uploadG...
@Test public void deleteGrantAgreement() { long applicationId = 78L; setupDeleteWithRestResultExpectations(format("%s/%s/%s", REST_URL, "grant-agreement", applicationId)); service.deleteGrantAgreement(applicationId); setupDeleteWithRestResultVerifications(format("%s/%s/%s", REST_URL, "grant-agreement", applicationId));...
EuGrantTransferRestServiceImpl extends BaseRestService implements EuGrantTransferRestService { @Override public RestResult<ByteArrayResource> downloadGrantAgreement(long applicationId) { String url = format("%s/%s/%s", REST_URL, "grant-agreement", applicationId); return getWithRestResult(url, ByteArrayResource.class); ...
@Test public void downloadGrantAgreement() { final long applicationId = 912L; ByteArrayResource expected = new ByteArrayResource("1u6536748".getBytes()); setupGetWithRestResultExpectations(format("%s/%s/%s", REST_URL, "grant-agreement", applicationId), ByteArrayResource.class, expected, OK); final ByteArrayResource res...
EuGrantTransferRestServiceImpl extends BaseRestService implements EuGrantTransferRestService { @Override public RestResult<EuGrantTransferResource> findDetailsByApplicationId(long applicationId) { String url = format("%s/%d", REST_URL, applicationId); return getWithRestResult(url, EuGrantTransferResource.class); } @Ov...
@Test public void findDetailsByApplicationId() { final long applicationId = 912L; EuGrantTransferResource euGrantTransferResource = newEuGrantTransferResource().build(); setupGetWithRestResultExpectations(format("%s/%s", REST_URL, applicationId), EuGrantTransferResource.class, euGrantTransferResource, OK); RestResult<E...
EuGrantTransferRestServiceImpl extends BaseRestService implements EuGrantTransferRestService { @Override public RestResult<Void> updateGrantTransferDetails(EuGrantTransferResource euGrantResource, long applicationId) { String url = format("%s/%d", REST_URL, applicationId); return postWithRestResult(url, euGrantResource...
@Test public void updateGrantTransferDetails() { final long applicationId = 912L; EuGrantTransferResource euGrantTransferResource = newEuGrantTransferResource().build(); setupPostWithRestResultExpectations(format("%s/%s", REST_URL, applicationId), euGrantTransferResource, OK); RestResult<Void> result = service.updateGr...
SurveyRestServiceImpl extends BaseRestService implements SurveyRestService { @Override @HystrixCommand(fallbackMethod = "saveFallback") public RestResult<Void> save(SurveyResource surveyResource) { return postWithRestResultAnonymous( "/survey", surveyResource, Void.class); } @Override @Value("${ifs.survey.data.service...
@Test public void save() { String baseUrl = "base"; surveyRestService.setServiceUrl(baseUrl); SurveyResource surveyResource = newSurveyResource().build(); RestResult<Void> expected = mock(RestResult.class); when(rootAnonymousUserRestTemplateAdaptor.postWithRestResult(baseUrl + "/survey", surveyResource, Void.class)).th...
RestResult extends BaseFailingOrSucceedingResult<T, RestFailure> { public static <T> RestResult<List<T>> aggregate(final List<RestResult<T>> input) { return BaseFailingOrSucceedingResult.aggregate( input, (f1, f2) -> new RestFailure(combineLists(f1.getErrors(), f2.getErrors())), restSuccess(emptyList())); } RestResult(...
@Test public void testAggregateSuccess() { final List<RestResult<String>> list = asList("1", "2", "3").stream().map(RestResult::restSuccess).collect(toList()); final RestResult<List<String>> RestResult = aggregate(list); assertTrue(RestResult.isSuccess()); assertFalse(RestResult.getSuccess().isEmpty()); assertEquals(as...
ServiceResult extends BaseFailingOrSucceedingResult<T, ServiceFailure> implements Serializable { public static <T> ServiceResult<List<T>> aggregate(final List<ServiceResult<T>> input) { return BaseFailingOrSucceedingResult.aggregate( input, (f1, f2) -> new ServiceFailure(combineLists(f1.getErrors(), f2.getErrors())), s...
@Test public void testAggregateSuccess() { final List<ServiceResult<String>> list = asList("1", "2", "3").stream().map(ServiceResult::serviceSuccess).collect(toList()); final ServiceResult<List<String>> serviceResult = aggregate(list); assertTrue(serviceResult.isSuccess()); assertFalse(serviceResult.getSuccess().isEmpt...
ServiceResult extends BaseFailingOrSucceedingResult<T, ServiceFailure> implements Serializable { @SafeVarargs public static <T> ServiceResult<Void> processAnyFailuresOrSucceed(ServiceResult<T>... results) { return processAnyFailuresOrSucceed(asList(results)); } private ServiceResult(Either<ServiceFailure, T> result); ...
@Test public void testProcessAnyFailuresOrSucceed() { List<ServiceResult<Void>> resultsWithErrors = asList(serviceFailure(badRequestError("Error 1")), serviceSuccess(), serviceFailure(asList(internalServerErrorError(), badRequestError("Error 3")))); ServiceResult<String> result = processAnyFailuresOrSucceed(resultsWith...
DefaultPermissionMethodHandler implements PermissionMethodHandler { @Override public boolean hasPermission(Authentication authentication, Object targetObject, Object permission, Class<?> targetClass) { ListOfOwnerAndMethod securingMethods = lookupAndCacheSecuringMethodsForClassAndPermission(permission, targetClass); fo...
@Test public void testPermissionCheckerRunsThroughAllPermissionMethods() { DefaultPermissionMethodHandler handler = new DefaultPermissionMethodHandler(permissionMethods); when(permissionMethodOwnerMock.readApplicationPermissionMethod1(application, authentication.getDetails())).thenReturn(false); when(permissionMethodOw...
PrioritySorting { public List<T> unwrap() { return sortedList; } <E extends Comparable<? super E>> PrioritySorting(List<T> list, T priority, Function<T, E> field); List<T> unwrap(); }
@Test public void sortingEmptyListReturnsEmptyList() { List<String> list = new PrioritySorting<>(new ArrayList<String>(), "exceptionElement", Function.identity()).unwrap(); assertTrue(list.isEmpty()); } @Test public void sortingListWorksAsExpectedWithIdentity() { List<String> list = new PrioritySorting<>(asList("C", "A...
OrganisationPatternMatcher { @NotSecured(value = "Is a 'static' comparison function", mustBeSecuredByOtherServices = false) public boolean organisationTypeIsResearch(Organisation organisation) { try { return OrganisationTypeEnum.isResearch(organisation.getOrganisationType().getId()); } catch(NullPointerException e) { L...
@Test public void organisationTypeIsResearch() throws Exception { Organisation organisation = newOrganisation().withOrganisationType(OrganisationTypeEnum.RESEARCH).build(); boolean result = service.organisationTypeIsResearch(organisation); assertTrue(result); } @Test public void organisationTypeIsResearch_noMatchIfType...
StringFunctions { public static int countWords(String content) { return ofNullable(stripToNull(stripHtml(content))).map(contentValue -> contentValue.split("\\s+").length).orElse(0); } private StringFunctions(); static int countWords(String content); static String stripHtml(String content); static String plainTextToHtm...
@Test public void countWords() throws Exception { assertEquals(15, StringFunctions.countWords(join(" ", nCopies(15, "content")))); } @Test public void countWords_valueWithHtml() throws Exception { assertEquals(15, StringFunctions.countWords("<td><p style=\"font-variant: small-caps\">This value is made up of fifteen wor...
StringFunctions { public static String stripHtml(String content) { return ofNullable(content).map(contentValue -> { String cleaned = Jsoup.clean(content, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)); return cleaned.trim().replaceAll("[ \t]+", " "); } ).orElse(null); } private StringFunctions...
@Test public void stripHtml() throws Exception { assertEquals("This value is made up of: a table cell a paragraph and a list.", StringFunctions.stripHtml( "<tr>" + " <td>" + " <p style=\"font-variant: small-caps\">This value is made up of:</p>" + " </td>" + " <td>" + " <ul>" + " <li>a table cell</li>" + " <li>a paragra...
StringFunctions { public static String plainTextToHtml(String content) { String escaped = StringEscapeUtils.escapeHtml4(content); if (escaped != null) { return escaped.replaceAll("\\R", "<br/>"); } return escaped; } private StringFunctions(); static int countWords(String content); static String stripHtml(String conten...
@Test public void plainTextToHtml() throws Exception { assertEquals("This text is split<br/>over several<br/>lines.<br/><br/>It contains characters &lt; &gt; &amp; &quot; which need escaping.", StringFunctions.plainTextToHtml("This text is split\nover several\nlines.\n\nIt contains characters < > & \" which need escapi...
CollectionFunctions { public static <T, R, S> Map<S, Map<T,R>> simpleGroupBy(Map<T, R> map, Function<T, S> filterFn) { Map<S, List<Entry<T, R>>> intermediate = map.entrySet().stream().collect(groupingBy(e -> filterFn.apply(e.getKey()))); return simpleMapKeyAndValue(intermediate, identity(), value -> simpleToMap(value, ...
@Test public void simpleGroupBy() { Map<String, String> map = new HashMap<>(); map.put("formInput[1].MMYYYY.year", "2001"); map.put("formInput[1].MMYYYY.month", "11"); map.put("formInput[2].MMYYYY.year", "1968"); map.put("formInput[2].MMYYYY.month", "2"); map.put("formInput[3].MMYYYY.year", "2001"); map.put("formInput[...
CollectionFunctions { public static <T> List<T> flattenLists(Collection<? extends Collection<T>> toFlatten){ return flattenLists(toFlatten, Function.identity()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlat...
@Test public void flattenLists() { List<List<Integer>> deepList = asList(asList(1, 2, 3), asList(4, 5), singletonList(6)); List<Integer> expectedFlatList = asList(1, 2, 3, 4, 5, 6); assertEquals(expectedFlatList, CollectionFunctions.flattenLists(deepList)); } @Test public void flattenLists_nullSafe() { List<List<Intege...
CollectionFunctions { public static <T> Set<T> flattenSets(Set<Set<T>> lists) { return lists.stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .collect(toSet()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collec...
@Test public void flattenSets() { Set<Set<Integer>> deepList = CollectionFunctions.asLinkedSet( CollectionFunctions.asLinkedSet(1, 2, 3), CollectionFunctions.asLinkedSet(4, 5), singleton(6)); Set<Integer> expectedFlatList = CollectionFunctions.asLinkedSet(1, 2, 3, 4, 5, 6); assertEquals(expectedFlatList, CollectionFunc...
CollectionFunctions { @SafeVarargs public static <T> List<T> combineLists(List<T>... lists) { return doCombineLists(lists); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatten, Function<S, ? extends Collection<...
@Test public void combineLists() { List<Integer> list1 = asList(1, 2, 3); List<Integer> list2 = asList(4, 5); List<Integer> list3 = singletonList(6); List<Integer> expectedCombinedList = asList(1, 2, 3, 4, 5, 6); assertEquals(expectedCombinedList, CollectionFunctions.combineLists(list1, list2, list3)); } @Test public v...
CollectionFunctions { public static <T> void forEachWithIndex(List<T> list, BiConsumer<Integer, T> consumer) { forEachConsumer(consumer).accept(list); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatten, Functi...
@Test public void forEachWithIndex() { final List<Integer> indicesSeen = new ArrayList<>(); final List<String> valuesSeen = new ArrayList<>(); final List<String> valuesToIterateOver = asList("string 1", "string 2", "string 3"); CollectionFunctions.forEachWithIndex(valuesToIterateOver, (i, value) -> { indicesSeen.add(i)...
OrganisationPatternMatcher { @NotSecured(value = "Is a 'static' comparison function", mustBeSecuredByOtherServices = false) public boolean organisationTypeMatches(Organisation organisation, OrganisationResource organisationResource) { try { return organisation.getOrganisationType().getId().equals(organisationResource.g...
@Test public void organisationTypeMatches() throws Exception { Organisation organisation = newOrganisation().withOrganisationType(OrganisationTypeEnum.BUSINESS).build(); OrganisationResource organisationResource = newOrganisationResource().withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()).build(); boolean res...
CollectionFunctions { public static <T, R> List<R> mapWithIndex(List<T> list, BiFunction<Integer, T, R> function) { return forEachFunction(function).apply(list); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlat...
@Test public void mapWithIndex() { final List<Integer> indicesSeen = new ArrayList<>(); final List<String> valuesToIterateOver = asList("string 1", "string 2", "string 3"); List<String> newStrings = CollectionFunctions.mapWithIndex(valuesToIterateOver, (i, value) -> { indicesSeen.add(i); return value + " changed"; }); ...
CollectionFunctions { public static <T> List<T> reverse(List<T> original) { List<T> reversed = original != null ? new ArrayList<>(original) : new ArrayList<>(); Collections.reverse(reversed); return reversed; } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); s...
@Test public void reverse() { List<String> originalList = asList("string 1", "another string 2", "string 3"); List<String> reversed = CollectionFunctions.reverse(originalList); assertEquals(asList("string 3", "another string 2", "string 1"), reversed); } @Test public void reverse_nullElements() { List<String> originalL...
CollectionFunctions { public static <T> T getOnlyElement(List<T> list) { if (list == null || list.isEmpty()) { throw new IllegalArgumentException("No elements were available in list " + list + ", so cannot return only element"); } if (list.size() > 1) { throw new IllegalArgumentException("More than one element was avai...
@Test public void getOnlyElement() { assertEquals("hi there", CollectionFunctions.getOnlyElement(singletonList("hi there"))); } @Test public void nullElement() { List<Object> nullElementList = new ArrayList<>(); nullElementList.add(null); assertNull(CollectionFunctions.getOnlyElement(nullElementList)); } @Test public v...
CollectionFunctions { public static <S, T, R> List<R> simpleMap(Map<S, T> map, BiFunction<S, T, R> mappingFn) { return simpleMap(map.entrySet(), entry -> mappingFn.apply(entry.getKey(), entry.getValue())); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); stat...
@Test public void simpleMap() { assertEquals(asList("123 string", "456 string"), CollectionFunctions.simpleMap(asList(123, 456), i -> i + " string")); } @Test public void simpleMap_nullList() { assertEquals(emptyList(), CollectionFunctions.simpleMap((List<?>) null, i -> i + " string")); } @Test public void simpleMap_nu...
CollectionFunctions { public static <S, T, R> Map<R, T> simpleMapKey(Map<S, T> map, Function<S, R> mappingFn) { return simpleMapKeyAndValue(map, mappingFn, value -> value); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collectio...
@Test public void simpleMapKey() { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); Map<Integer, String> expected = new HashMap<>(); expected.put(2, "a"); expected.put(4, "b"); assertEquals(expected, CollectionFunctions.simpleMapKey(map, key -> key * 2)); }
CollectionFunctions { public static <S, T, R> Map<S, R> simpleMapValue(Map<S, T> map, Function<T, R> mappingFn) { return simpleMapKeyAndValue(map, key -> key, mappingFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<...
@Test public void simpleMapValue() { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); Map<Integer, String> expected = new HashMap<>(); expected.put(1, "a!"); expected.put(2, "b!"); assertEquals(expected, CollectionFunctions.simpleMapValue(map, value -> value + "!")); }
CollectionFunctions { public static <S, T, R, U> Map<R, U> simpleMapEntry(Map<S, T> map, Function<Entry<S, T>, R> keyMapping, Function<Entry<S,T>, U> valueMapping) { return map.entrySet().stream().collect(toMap(keyMapping, valueMapping)); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extend...
@Test public void simpleMapEntry() { Map<Integer, String> map = new HashMap<>(); map.put(1, "a"); map.put(2, "b"); Map<String, String> expected = new HashMap<>(); expected.put("2a!", "4a?"); expected.put("4b!", "8b?"); assertEquals(expected, CollectionFunctions.simpleMapEntry(map, entry -> entry.getKey() * 2 + entry.ge...
CollectionFunctions { public static <T, R> List<R> simpleMapWithIndex(T[] list, BiFunction<T, Integer, R> mappingFn) { return simpleMapWithIndex(asList(list), mappingFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<...
@Test public void simpleMapWithIndex() { assertEquals(asList("123 string 0", "456 string 1"), CollectionFunctions.simpleMapWithIndex(asList(123, 456), (element, index) -> element + " string " + index)); } @Test public void simpleMapWithIndex_emptyList() { assertEquals(emptyList(), CollectionFunctions.simpleMapWithIndex...
CollectionFunctions { @SuppressWarnings("unchecked") public static <T, R> R[] simpleMapArray(T[] array, Function<T, R> mappingFn, Class<R> clazz) { if (array == null || array.length == 0){ return (R[]) Array.newInstance(clazz, 0); } else { R[] result = (R[]) Array.newInstance(clazz, array.length); for (int index = 0; i...
@Test public void simpleMapArray() { assertEquals(new String[]{"123 string", "456 string"}, CollectionFunctions.simpleMapArray(new Integer[]{123, 456}, element -> element + " string", String.class)); } @Test public void simpleMapArray_nullArray() { assertEquals(new String[]{}, CollectionFunctions.simpleMapArray(null, e...
CollectionFunctions { public static <T, R> Set<R> simpleMapSet(Set<T> list, Function<T, R> mappingFn) { if (null == list || list.isEmpty()) { return emptySet(); } return list.stream().map(mappingFn).collect(toSet()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFla...
@Test public void simpleMapSet() { assertEquals(CollectionFunctions.asLinkedSet("123 string", "456 string"), CollectionFunctions.simpleMapSet(CollectionFunctions.asLinkedSet(123, 456), i -> i + " string")); } @Test public void simpleMapSet_null() { assertEquals(emptySet(), CollectionFunctions.simpleMapSet((Set<?>) null...
CollectionFunctions { public static <T, R> LinkedHashSet<R> simpleToLinkedHashSet(T[] array, Function<T, R> mappingFn) { if (array == null) { return new LinkedHashSet<>(); } return simpleToLinkedHashSet(asList(array), mappingFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collect...
@Test public void simpleToLinkedHashSetWithCollection() { assertEquals(new LinkedHashSet<>(asList("123 string", "456 string")), CollectionFunctions.simpleToLinkedHashSet(asList(123, 456), i -> i + " string")); } @Test public void simpleToLinkedHashSetWithCollection_nullList() { assertEquals(new LinkedHashSet<String>(),...
CollectionFunctions { public static <T, R> Map<T, R> simpleFilter(Map<T, R> map, Predicate<T> filterFn) { return simpleFilter(map, (k, v) -> filterFn.test(k)); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatte...
@Test public void simpleFilter() { assertEquals(singletonList(789), CollectionFunctions.simpleFilter(asList(123, 456, 789), i -> i > 456)); } @Test public void simpleFilter_nullList() { assertEquals(emptyList(), CollectionFunctions.simpleFilter((Collection<?>) null, i -> false)); } @Test public void simpleFilter_nullEl...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "The System Registration User can see Organisations on behalf of non-logged in users " + "whilst the Organisation is not yet linked to an Application") public boolean systemRegistrationUserCanSeeOrganisationsNotYetConnectedToApplications(Organi...
@Test public void systemRegistrationUserCanViewAnOrganisationThatIsNotYetLinkedToAnApplication() { when(processRoleRepository.existsByOrganisationId(anyLong())).thenReturn(false); allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanSeeOrganisations...
CollectionFunctions { public static <T, R> Map<T, R> simpleFilterNot(Map<T, R> map, Predicate<T> filterFn) { return simpleFilter(map, filterFn.negate()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatten, Fun...
@Test public void simpleFilterNot() { assertEquals(asList(123, 456), CollectionFunctions.simpleFilterNot(asList(123, 456, 789), i -> i > 456)); } @Test public void simpleFilterNot_nullList() { assertEquals(emptyList(), CollectionFunctions.simpleFilterNot((List<?>) null, i -> false)); } @Test public void simpleFilterNot...
CollectionFunctions { public static <T> Optional<T> simpleFindAny(Collection<T> list, Predicate<T> filterFn) { if (list == null || list.isEmpty()) { return empty(); } return list.stream().filter(filterFn).findAny(); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlat...
@Test public void simpleFindAnyWithNullList() { assertEquals(empty(), CollectionFunctions.simpleFindAny(null, i -> true)); } @Test public void simpleFindAnyWithNullElements() { assertEquals(Optional.of(789), CollectionFunctions.simpleFindAny(asList(123, null, 455, 789), i -> i != null && i > 456)); } @Test public void ...
CollectionFunctions { public static <T, K, U> Collector<T, ?, Map<K, U>> toLinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return toMap(keyMapper, valueMapper, (u, v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); }, LinkedHashMap::new)...
@Test public void testToLinkedMap() { List<String> orderedList = asList("1", "2", "3", "4", "5"); Map<String, String> orderedMap = orderedList.stream().collect(CollectionFunctions.toLinkedMap(item -> item, item -> item + item)); int index = 0; for (Entry<String, String> entry : orderedMap.entrySet()) { assertEquals(ord...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "Internal Users can see all Organisations") public boolean internalUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user) { return isInternal(user); } @PermissionRule(value = "READ", description = "Internal Users can...
@Test public void internalUsersCanViewAnyOrganisation() { allGlobalRoleUsers.forEach(user -> { if (allInternalUsers.contains(user)) { assertTrue(rules.internalUsersCanSeeAllOrganisations(newOrganisationResource().build(), user)); } else { assertFalse(rules.internalUsersCanSeeAllOrganisations(newOrganisationResource().b...
CollectionFunctions { public static <T> String simpleJoiner(Collection<T> list, String joinString) { if (list == null || list.isEmpty()) { return ""; } return list.stream().map(element -> element != null ? element.toString() : "").collect(joining(joinString)); } private CollectionFunctions(); static List<T> flattenLis...
@Test public void simpleJoiner() { assertEquals("123, 456, 789", CollectionFunctions.simpleJoiner(asList(123, 456, 789), ", ")); } @Test public void simpleJoiner_nullList() { assertEquals("", CollectionFunctions.simpleJoiner(null, ", ")); } @Test public void simpleJoiner_nullElements() { assertEquals("123, , 789", Coll...
CollectionFunctions { public static <T, K, U> Map<K, U> simpleToMap( Collection<T> list, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { if (list == null || list.isEmpty()) { return Collections.emptyMap(); } Map<K,U> map = new HashMap<K,U>(); list.forEach(item -> map.put(keyM...
@Test public void testSimpleToMapWithKeyAndValueMappers() { Map<Integer, String> toMap = CollectionFunctions.simpleToMap(asList(1, 2, 3), element -> element + 10, element -> element + " value"); assertEquals(3, toMap.size()); assertTrue(toMap.keySet().contains(11)); assertTrue(toMap.keySet().contains(12)); assertTrue(t...
CollectionFunctions { public static <T, K, U> Map<K, U> simpleToLinkedMap( List<T> list, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { if (list == null || list.isEmpty()) { return Collections.emptyMap(); } return list.stream().collect(toMap(keyMapper, valueMapper, throwingM...
@Test public void simpleToLinkedMapWhenInputListIsNull() { Map<Integer, Integer> toLinkedMap = CollectionFunctions.simpleToLinkedMap(null, identity(), identity()); assertTrue(toLinkedMap.isEmpty()); } @Test public void simpleToLinkedMapWhenInputListIsEmpty() { Map<Integer, Integer> toLinkedMap = CollectionFunctions.sim...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "Stakeholders can see all Organisations") public boolean stakeholdersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user) { return isStakeholder(user); } @PermissionRule(value = "READ", description = "Internal Users can...
@Test public void stakeholdersCanSeeAllOrganisations() { allGlobalRoleUsers.forEach(user -> { if (user.hasRole(STAKEHOLDER)) { assertTrue(rules.stakeholdersCanSeeAllOrganisations(newOrganisationResource().build(), user)); } else { assertFalse(rules.stakeholdersCanSeeAllOrganisations(newOrganisationResource().build(), u...
CollectionFunctions { public static <S, T, R, U> Map<R, U> simpleLinkedMapKeyAndValue(Map<S, T> map, Function<S, R> keyMappingFn, Function<T, U> valueMappingFn) { List<Pair<R, U>> list = simpleMap(map.entrySet(), entry -> Pair.of(keyMappingFn.apply(entry.getKey()), valueMappingFn.apply(entry.getValue()))); return simpl...
@Test public void simpleLinkedMapKeyAndValue() { Map<Integer, String> inputMap = new LinkedHashMap<>(); inputMap.put(1, "Test1"); inputMap.put(2, "Test2"); inputMap.put(3, "Test3"); Map<Integer, String> toLinkedMap = CollectionFunctions.simpleLinkedMapKeyAndValue(inputMap, element -> element + 10, element -> element + ...
CollectionFunctions { public static <S, T, R> Map<R, T> simpleLinkedMapKey(Map<S, T> map, Function<S, R> mappingFn) { return simpleLinkedMapKeyAndValue(map, mappingFn, value -> value); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLis...
@Test public void simpleLinkedMapKey() { Map<Integer, String> inputMap = new LinkedHashMap<>(); inputMap.put(1, "Test1"); inputMap.put(2, "Test2"); inputMap.put(3, "Test3"); Map<Integer, String> toLinkedMap = CollectionFunctions.simpleLinkedMapKey(inputMap, element -> element + 10); int inputKey = 1; for (Entry<Integer...
CollectionFunctions { public static <S, T, R> Map<S, R> simpleLinkedMapValue(Map<S, T> map, Function<T, R> mappingFn) { return simpleLinkedMapKeyAndValue(map, key -> key, mappingFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists...
@Test public void simpleLinkedMapValue() { Map<Integer, String> inputMap = new LinkedHashMap<>(); inputMap.put(1, "Test1"); inputMap.put(2, "Test2"); inputMap.put(3, "Test3"); Map<Integer, String> toLinkedMap = CollectionFunctions.simpleLinkedMapValue(inputMap, element -> element + " value"); int inputKey = 1; for (Ent...
CollectionFunctions { public static <T> List<List<T>> findPermutations(List<T> excludedWords) { List<List<List<T>>> allPermutations = mapWithIndex(excludedWords, (i, currentWord) -> findPermutations(emptyList(), currentWord, removeElement(excludedWords, i))); return flattenLists(allPermutations); } private CollectionF...
@Test public void testFindPermutations() { List<List<String>> permutations = CollectionFunctions.findPermutations(asList("a", "b", "c")); assertEquals(3 * 2, permutations.size()); List<List<String>> expectedPermutations = asList( asList("a", "b", "c"), asList("b", "a", "c"), asList("c", "a", "b"), asList("a", "c", "b")...
CollectionFunctions { public static <T> List<T> removeElement(List<T> list, int index) { List<T> copy = new ArrayList<>(list); copy.remove(index); return copy; } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatte...
@Test public void removeElement() { List<String> tokens = asList("a", "b", "c"); assertEquals(asList("a", "c"), CollectionFunctions.removeElement(tokens, 1)); assertEquals(asList("a", "b", "c"), tokens); }
CollectionFunctions { public static <T> List<T> removeDuplicates(Collection<T> list) { if (list == null) { return emptyList(); } return list.stream().distinct().collect(toList()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Co...
@Test public void removeDuplicates() { List<String> tokens = asList("a", "b", "c", "b", "e", "c"); assertEquals(asList("a", "b", "c", "e"), CollectionFunctions.removeDuplicates(tokens)); assertEquals(asList("a", "b", "c", "b", "e", "c"), tokens); }
CollectionFunctions { public static <T extends Comparable> List<T> sort(Collection<T> list) { if (list == null || list.isEmpty()) { return emptyList(); } return list.stream().sorted().collect(toList()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static ...
@Test public void sort() { assertEquals(asList("a", "b", "c"), CollectionFunctions.sort(asList("b", "c", "a"))); } @Test public void sort_nullSafe() { assertEquals(emptyList(), CollectionFunctions.sort(null)); } @Test public void sortWithComparator() { assertEquals(asList("c", "b", "a"), CollectionFunctions.sort(asList...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "Competition finance users can see all Organisations") public boolean competitionFinanceUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user) { return isExternalFinanceUser(user); } @PermissionRule(value = "READ", d...
@Test public void competitionFinanceUsersCanSeeAllOrganisations() { allGlobalRoleUsers.forEach(user -> { if (user.hasRole(EXTERNAL_FINANCE)) { assertTrue(rules.competitionFinanceUsersCanSeeAllOrganisations(newOrganisationResource().build(), user)); } else { assertFalse(rules.competitionFinanceUsersCanSeeAllOrganisation...
CollectionFunctions { public static <T> Pair<List<T>, List<T>> simplePartition(List<T> list, Predicate<T> test) { if (list == null || list.isEmpty()) { return Pair.of(emptyList(), emptyList()); } Map<Boolean, List<T>> partitioned = list.stream().collect(partitioningBy(test)); return Pair.of(partitioned.get(true), parti...
@Test public void testSimplePartition() { Pair<List<String>, List<String>> partitioned = CollectionFunctions.simplePartition(asList("a1", "b1", "a2", "c1"), string -> string.startsWith("a")); assertEquals(asList("a1", "a2"), partitioned.getLeft()); assertEquals(asList("b1", "c1"), partitioned.getRight()); } @Test publi...
CollectionFunctions { public static <T, R> boolean containsAll(Collection<T> containing, Collection<R> contained, BiFunction<T, R, Boolean> equalsFunction){ if (containing == null && contained != null) { return false; } else if (contained == null) { return true; } boolean notContained = contained.stream().anyMatch(cont...
@Test public void testContainsAllEqualsFunction() { List<Pair<Integer, String>> containingList = asList(of(1, "two"), of(2, "pair")); List<String> containedList = asList("two", "pair"); List<String> anotherSmallerContainedList = singletonList("two"); List<String> isNotContainedList = singletonList("not present"); asser...
CollectionFunctions { public static <R, S, T> SortedMap<T, List<R>> toSortedMapWithList(List<S> orderedList, Function<S, T> keyTransform, Function<S, R> valueTransform) { SortedMap<T, List<R>> orderedMap = new TreeMap<>(); if (orderedList != null) { orderedList.forEach(s -> { if (s != null) { T key = keyTransform.apply...
@Test public void testToSorted() { String firstLabel = "getLabel 1"; String secondLabel = "getLabel 2"; String firstEntry = "1st entry"; String secondEntry = "2nd entry"; String thirdEntry = "3rd entry"; String fourthEntry = "4th entry"; List<Pair<String, String>> sortedList = asList(of(firstLabel, firstEntry), of(firs...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "Monitoring officers can see Organisations on their projects") public boolean monitoringOfficersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user) { List<MonitoringOfficer> projectMonitoringOfficers = projectMonitoring...
@Test public void monitoringOfficersCanSeeAllOrganisations() { long organisationId = 1L; Organisation organisation = newOrganisation() .withId(organisationId) .build(); List<PartnerOrganisation> partnerOrganisations = newPartnerOrganisation() .withOrganisation(organisation) .build(1); Project project = newProject() .wi...
CollectionFunctions { public static <S, T> T unique(Collection<S> collectionToSearch, Function<S, T> property) { List<T> distinct = collectionToSearch.stream().map(property).distinct().collect(toList()); if (distinct.size() != 1) { throw new IllegalArgumentException("Collection to search:" + collectionToSearch + " does...
@Test public void testUnique() { List<String> uniqueList = asList("one", "one", "one"); assertEquals("one", unique(uniqueList, identity())); List<String> notUniqueList = asList("one", "two", "three"); try { unique(notUniqueList, identity()); fail("Should have thrown and IllegalArgumentException"); } catch (IllegalArgum...
CollectionFunctions { public static <T, S> void zip(List<T> list1, List<S> list2, BiConsumer<T, S> consumer) { forEachWithIndex(list1, (i, item1) -> consumer.accept(item1, list2.get(i))); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flatten...
@Test public void zip() { List<String> list1 = asList("a", "b", "c"); List<Integer> list2 = asList(1, 2, 3); List<String> results = new ArrayList<>(); CollectionFunctions.zip(list1, list2, (string, integer) -> results.add(string + integer)); assertEquals(asList("a1", "b2", "c3"), results); } @Test public void zipTriple...
CollectionFunctions { public static <T, S> void zipWithIndex(List<T> list1, List<S> list2, TriConsumer<T, S, Integer> consumer) { forEachWithIndex(list1, (i, item1) -> consumer.accept(item1, list2.get(i), i)); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); ...
@Test public void zipWithIndex() { List<String> list1 = asList("a", "b", "c"); List<Integer> list2 = asList(1, 2, 3); List<String> results = new ArrayList<>(); CollectionFunctions.zipWithIndex(list1, list2, (string, integer, index) -> results.add(string + integer + "" + index)); assertEquals(asList("a10", "b21", "c32")...
CollectionFunctions { public static <T, R, S> List<R> zipAndMap(List<T> list1, List<S> list2, BiFunction<T, S, R> biFunction) { return zipAndMapWithIndex(list1, list2, (o1, o2, i) -> biFunction.apply(o1, o2)); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); ...
@Test public void zipAndMap() { List<String> list1 = asList("a", "b", "c"); List<Integer> list2 = asList(1, 2, 3); List<String> results = CollectionFunctions.zipAndMap(list1, list2, (string, integer) -> string + integer); assertEquals(asList("a1", "b2", "c3"), results); }
CollectionFunctions { public static <T, R, S> List<R> zipAndMapWithIndex(List<T> list1, List<S> list2, TriFunction<T, S, Integer, R> triFunction) { List<R> resultList = new ArrayList<>(); zipWithIndex(list1, list2, (o1, o2, index) -> resultList.add(triFunction.apply(o1, o2, index))); return resultList; } private Colle...
@Test public void zipAndMapWithIndex() { List<String> list1 = asList("a", "b", "c"); List<Integer> list2 = asList(1, 2, 3); List<String> results = CollectionFunctions.zipAndMapWithIndex(list1, list2, (string, integer, index) -> string + integer + "" + index); assertEquals(asList("a10", "b21", "c32"), results); }
OrganisationPermissionRules { @PermissionRule(value = "UPDATE", description = "A project finance user can update any Organisation") public boolean projectFinanceUserCanUpdateAnyOrganisation(OrganisationResource organisation, UserResource user) { return isProjectFinanceUser(user); } @PermissionRule(value = "READ", desc...
@Test public void projectFinanceUserCanUpdateAllOrganisations() { allGlobalRoleUsers.forEach(user -> { if (user.equals(projectFinanceUser())) { assertTrue(rules.projectFinanceUserCanUpdateAnyOrganisation(newOrganisationResource().build(), user)); } else { assertFalse(rules.projectFinanceUserCanUpdateAnyOrganisation(new...
CollectionFunctions { @SafeVarargs public static <T> Predicate<T> and(Predicate<? super T>... predicates){ return t -> { for (Predicate<? super T> predicate : predicates){ if (!predicate.test(t)){ return false; } } return true; }; } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collec...
@Test public void and() { List<Integer> list = asList(1, 2, 3, 4, 5, 6, 7, 8); Predicate<Integer> compoundPredicate = CollectionFunctions.and( i -> i > 3, i -> (i % 2) == 0); List<Integer> filtered = CollectionFunctions.simpleFilter(list, compoundPredicate); assertEquals(asList(4, 6, 8), filtered); }
CollectionFunctions { public static <T> Optional<T> getOnlyElementOrEmpty(List<T> list) { if (list == null || list.isEmpty()) { return empty(); } if (list.size() > 1) { throw new IllegalArgumentException("More than one element was available in list " + list + ", so cannot return only element"); } return Optional.of(lis...
@Test public void getOnlyElementOrEmpty() { assertEquals(Optional.of(1), CollectionFunctions.getOnlyElementOrEmpty(singletonList(1))); } @Test(expected = IllegalArgumentException.class) public void getOnlyElementOrEmpty_MoreThanOneElement() { CollectionFunctions.getOnlyElementOrEmpty(asList(1, 2)); } @Test public void ...
CollectionFunctions { public static <R, T> Map<R, T> pairsToMap(List<Pair<R, T>> pairs) { return simpleToMap(pairs, Pair::getKey, Pair::getValue); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatten, Function<S...
@Test public void pairsToMap() { Map<Integer, String> expected = new LinkedHashMap<>(); expected.put(1, "a"); expected.put(2, "b"); assertEquals(expected, CollectionFunctions.pairsToMap(asList(Pair.of(1, "a"), Pair.of(2, "b")))); }
CollectionFunctions { public static <T> Optional<T> simpleFindFirst(Collection<T> list, Predicate<T> filterFn) { if (list == null || list.isEmpty()) { return empty(); } return list.stream().filter(filterFn).findFirst(); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> to...
@Test public void simpleFindFirst() { assertEquals(Optional.of(3), CollectionFunctions.simpleFindFirst(asList(1, 2, 3), i -> i > 2)); } @Test public void simpleFindFirst_notFound() { assertEquals(Optional.empty(), CollectionFunctions.simpleFindFirst(asList(1, 2, 3), i -> i > 3)); } @Test public void simpleFindFirst_nul...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "System Registration User can see all Organisations, in order to view particular Organisations during registration and invite") public boolean systemRegistrationUserCanSeeAllOrganisations(OrganisationResource organisation, UserResource user) { ...
@Test public void systemRegistrationUsersCanViewAnyOrganisation() { allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanSeeAllOrganisations(newOrganisationResource().build(), user)); } else { assertFalse(rules.systemRegistrationUserCanSeeAllOrganis...
CollectionFunctions { public static <T> T simpleFindFirstMandatory(Collection<T> list, Predicate<T> filterFn) { if (list == null || list.isEmpty()) { throw new IllegalArgumentException("Cannot find a mandatory matching value in an empty list"); } return simpleFindFirst(list, filterFn).orElseThrow(() -> new IllegalArgum...
@Test public void simpleFindFirstMandatory() { assertEquals(Integer.valueOf(3), CollectionFunctions.simpleFindFirstMandatory(asList(1, 2, 3), i -> i > 2)); } @Test(expected = IllegalArgumentException.class) public void simpleFindFirstMandatory_withNullList() { CollectionFunctions.simpleFindFirstMandatory((List<Integer>...
CollectionFunctions { public static <T> boolean simpleAnyMatch(Collection<T> list, Predicate<T> filterFn) { if (list == null || list.isEmpty()) { return false; } return list.stream().anyMatch(filterFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static ...
@Test public void simpleAnyMatch() { assertTrue(CollectionFunctions.simpleAnyMatch(asList(1, 2, 3), i -> i > 2)); } @Test public void simpleAnyMatch_noMatch() { assertFalse(CollectionFunctions.simpleAnyMatch(asList(1, 2), i -> i > 2)); } @Test public void simpleAnyMatch_nullList() { assertFalse(CollectionFunctions.simp...
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "A member of an Organisation can view their own Organisation") public boolean memberOfOrganisationCanViewOwnOrganisation(OrganisationResource organisation, UserResource user) { return isMemberOfOrganisation(organisation, user); } @PermissionRu...
@Test public void memberOfOrganisationCanViewOwnOrganisation() { UserResource user = newUserResource().build(); UserResource anotherUser = newUserResource().build(); OrganisationResource organisation = newOrganisationResource().build(); when(processRoleRepository.existsByUserIdAndOrganisationId(user.getId(), organisati...
CollectionFunctions { public static <T> boolean simpleAllMatch(Collection<T> list, Predicate<T> filterFn) { if (list == null || list.isEmpty()) { return true; } return list.stream().allMatch(filterFn); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static L...
@Test public void simpleAllMatch() { assertTrue(CollectionFunctions.simpleAllMatch(asList(1, 2, 3), i -> i > 0)); } @Test public void simpleAllMatch_noMatch() { assertFalse(CollectionFunctions.simpleAllMatch(asList(1, 2, 3), i -> i > 1)); } @Test public void simpleAllMatch_nullList() { assertTrue(CollectionFunctions.si...
CollectionFunctions { public static <T> BinaryOperator<T> nullSafe(final BinaryOperator<T> notNullSafe) { return (t1, t2) -> { if (t1 != null && t2 != null) { return notNullSafe.apply(t1, t2); } else if (t1 != null) { return t1; } else return t2; }; } private CollectionFunctions(); static List<T> flattenLists(Collecti...
@Test public void nullSafe() { BinaryOperator<Integer> nullSafeAdder = CollectionFunctions.nullSafe((Integer o1, Integer o2) -> o1 + o2); Integer reduction = Stream.of(null, null, null, 4, null, 6, 7).reduce(nullSafeAdder).get(); assertEquals(17, reduction.intValue()); }
CollectionFunctions { @SuppressWarnings("unchecked") public static <T, R> List<Pair<T, R>> asListOfPairs(Object... entries) { if (entries.length % 2 != 0) { throw new IllegalArgumentException("Should have an even number of names and values in list"); } List<Pair<T, R>> list = new ArrayList<>(); for (int i = 0; i < entr...
@Test public void asListOfPairs() { List<Pair<String, Integer>> expected = asList(Pair.of("a", 1), Pair.of("b", 2), Pair.of("c", 3)); assertEquals(expected, CollectionFunctions.asListOfPairs("a", 1, "b", 2, "c", 3)); } @Test(expected = IllegalArgumentException.class) public void asListOfPairs_unevenEntries() { Collecti...
CollectionFunctions { public static <T> List<T> nOf(int n, T t) { return range(0, n).mapToObj(x -> t).collect(toList()); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Collection<S> toFlatten, Function<S, ? extends Collection<T>>...
@Test public void nOf() { assertEquals(asList("a", "a", "a", "a", "a"), CollectionFunctions.nOf(5, "a")); }
CollectionFunctions { public static <T> List<T> flattenOptional(Collection<Optional<T>> toFlatten){ return simpleMap(simpleFilter(toFlatten, Optional::isPresent), Optional::get); } private CollectionFunctions(); static List<T> flattenLists(Collection<? extends Collection<T>> toFlatten); static List<T> flattenLists(Col...
@Test public void flattenOptional() { List<Optional<Integer>> listOfOptionals = asList( Optional.of(1), Optional.empty(), Optional.of(3), Optional.of(4), Optional.empty()); assertEquals(asList(1, 3, 4), CollectionFunctions.flattenOptional(listOfOptionals)); }
MathFunctions { public static BigDecimal percentage(long numerator, long denominator) { int scale = 2; if (denominator != 0) { return valueOf(numerator).multiply(valueOf(100)).divide(valueOf(denominator), scale, HALF_UP); } else { return ZERO.setScale(scale); } } private MathFunctions(); static BigDecimal percentage(l...
@Test public void testPercentage() { assertEquals(percentage(0, 10), new BigDecimal("0.00")); assertEquals(percentage(10, 10), new BigDecimal("100.00")); assertEquals(percentage(1, 3), new BigDecimal("33.33")); assertEquals(percentage(2, 3), new BigDecimal("66.67")); assertEquals(percentage(2, 1), new BigDecimal("200.0...
MapFunctions { public static <T, R> Map<T, R> asMap(Object... nameValuePairs) { if (nameValuePairs.length % 2 != 0) { throw new IllegalArgumentException("Should have an even number of names and values in list"); } Map<T, R> map = new HashMap<>(); for (int i = 0; i < nameValuePairs.length; i += 2) { T key = (T) nameValu...
@Test public void testAsMap() { Map<Long, String> map = asMap(1L, "String 1", 2L, "String 2"); assertEquals(2, map.size()); assertTrue(map.containsKey(1L)); assertTrue(map.containsKey(2L)); assertEquals("String 1", map.get(1L)); assertEquals("String 2", map.get(2L)); } @Test(expected = IllegalArgumentException.class) p...
MapFunctions { public static <T, R> LinkedHashMap<R, Integer> getSortedGroupingCounts(List<T> list, Function<T, R> groupFn) { if (list == null || list.isEmpty()) { return new LinkedHashMap<>(0); } Map<R, List<T>> grouped = list.stream().collect(groupingBy(groupFn)); Map<R, Integer> numberOfOccurrancesByGrouping = simpl...
@Test public void testGetSortedGroupingCounts() { List<SortGroupTest> groupable = simpleMap(asList("string 1", "string 1", "string 2", "string 2", "string 2", "string 2", "string 3"), SortGroupTest::new); Map<String, Integer> groupedCountedAndSorted = MapFunctions.getSortedGroupingCounts(groupable, SortGroupTest::getVa...
MapFunctions { public static <T, R> Map<T, R> combineMaps(Map<T, R> map1, Map<T, R> map2) { if (map1 == null && map2 == null) { return new HashMap<>(0); } if (map1 == null) { return new HashMap<>(map2); } if (map2 == null) { return new HashMap<>(map1); } Map<T, R> combined = new HashMap<>(map1); map2.forEach((key, valu...
@Test public void testCombineMaps() { Map<Long, String> map1 = asMap(1L, "1", 2L, "2"); Map<Long, String> map2 = asMap(3L, "3"); assertEquals(asMap(1L, "1", 2L, "2", 3L, "3"), combineMaps(map1, map2)); }
OrganisationPermissionRules { @PermissionRule(value = "UPDATE", description = "A member of an Organisation can update their own Organisation") public boolean memberOfOrganisationCanUpdateOwnOrganisation(OrganisationResource organisation, UserResource user) { return isMemberOfOrganisation(organisation, user); } @Permis...
@Test public void memberOfOrganisationCanUpdateOwnOrganisation() { UserResource user = newUserResource().build(); OrganisationResource organisation = newOrganisationResource().build(); when(processRoleRepository.existsByUserIdAndOrganisationId(user.getId(), organisation.getId())).thenReturn(true); assertTrue(rules.memb...
MapFunctions { public static <T, S> Pair<Map<T, S>, Map<T, S>> simplePartition(Map<T, S> map, Predicate<Entry<T, S>> test) { if (map == null || map.isEmpty()) { return Pair.of(emptyMap(), emptyMap()); } Map<Boolean, List<Entry<T, S>>> partitioned = map.entrySet().stream().collect(partitioningBy(test)); Map<T, S> left =...
@Test public void testSimplePartition() { Map<Long, String> map1 = asMap(1L, "1", 2L, "2", 3L, "3"); Pair<Map<Long, String>, Map<Long, String>> result = simplePartition(map1, longStringEntry -> longStringEntry.getKey().equals(2L)); assertEquals(asMap(2L, "2"), result.getLeft()); assertEquals(asMap(1L, "1", 3L, "3"), re...
FieldComparisonValidator implements ConstraintValidator<FieldComparison, Object> { @Override public boolean isValid(Object value, ConstraintValidatorContext context) { boolean valid = isValid(value); if (!valid) { addConstraintViolationMessageToField(context, message, firstFieldName); } return valid; } @Override void ...
@Test public void isValid() throws Exception { mockMvc.perform(post("/") .contentType(APPLICATION_FORM_URLENCODED) .param("hasCats", "true") .param("catQuantity", "10") .param("hasDogs", "true") .param("dogQuantity", "10")) .andExpect(status().isOk()) .andExpect(model().hasNoErrors()) .andExpect(view().name("success"))...
PhoneNumberValidator { public boolean validate(final String phonenumber) { matcher = pattern.matcher(phonenumber); return matcher.matches(); } PhoneNumberValidator(); boolean validate(final String phonenumber); static final String VALID_PHONE_NUMBER; }
@Test public void validPhoneNumberWithEightDigits() { PhoneNumberValidator tester = new PhoneNumberValidator(); assertTrue("Eight digit phonenumber", tester.validate(eightDigitPhoneNumber)); } @Test public void invalidPhoneNumberWithSevenDigits() { PhoneNumberValidator tester = new PhoneNumberValidator(); assertFalse("...
ApplicationAssessorResource { public boolean isAssigned() { return complementOf(of(REJECTED, WITHDRAWN)).contains(mostRecentAssessmentState); } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, String ...
@Test public void isAssigned() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(CREATED, PENDING, ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED), ApplicationAssessorResource::isAssigned); }
ApplicationAssessorResource { public boolean isAccepted() { return of(ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED).contains(mostRecentAssessmentState); } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, ...
@Test public void isAccepted() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED), ApplicationAssessorResource::isAccepted); }
ApplicationAssessorResource { public boolean isNotified() { return complementOf(of(CREATED)).contains(mostRecentAssessmentState); } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, String lastName, ...
@Test public void isNotified() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(PENDING, REJECTED, ACCEPTED, OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED, WITHDRAWN), ApplicationAssessorResource::isNotified); }
ApplicationAssessorResource { public boolean isStarted() { return complementOf(of(CREATED, PENDING, ACCEPTED, REJECTED, WITHDRAWN)).contains(mostRecentAssessmentState); } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, ...
@Test public void isStarted() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(OPEN, DECIDE_IF_READY_TO_SUBMIT, READY_TO_SUBMIT, SUBMITTED), ApplicationAssessorResource::isStarted); }
ApplicationAssessorResource { public boolean isSubmitted() { return SUBMITTED == mostRecentAssessmentState; } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, String lastName, ...
@Test public void isSubmitted() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(SUBMITTED), ApplicationAssessorResource::isSubmitted); }
ApplicationAssessorResource { public boolean isRejected() { return REJECTED == mostRecentAssessmentState; } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, String lastName, ...
@Test public void isRejected() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(AssessmentState.REJECTED), ApplicationAssessorResource::isRejected); }
ApplicationAssessorResource { public boolean isWithdrawn() { return WITHDRAWN == mostRecentAssessmentState; } ApplicationAssessorResource(); ApplicationAssessorResource(Long userId, String firstName, String lastName, ...
@Test public void isWithdrawn() throws Exception { assertTrueOnlyForMostRecentAssessmentStates(of(AssessmentState.WITHDRAWN), ApplicationAssessorResource::isWithdrawn); }
AssessmentTotalScoreResource { @JsonIgnore public Integer getTotalScorePercentage() { if (totalScoreGiven == null || totalScoreGiven == 0) { return 0; } return totalScorePossible == 0 ? 0 : Math.round(totalScoreGiven * 100.0f / totalScorePossible); } AssessmentTotalScoreResource(); AssessmentTotalScoreResource(Integer...
@Test public void getTotalScorePercentage() throws Exception { assertEquals("Expected 50% since a score of 100 was given out of a possible 200", 50, getTotalScorePercentage(100, 200)); } @Test public void getTotalScorePercentage_roundDown() throws Exception { assertEquals("Expected 50.4% to be rounded down to 50%", 50,...
OrganisationPermissionRules { @PermissionRule(value = "CREATE", description = "The System Registration User can create Organisations on behalf of non-logged in Users " + "during the regsitration process") public boolean systemRegistrationUserCanCreateOrganisations(OrganisationResource organisation, UserResource user) {...
@Test public void systemRegistrationUserCanCreateOrganisations() { allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanCreateOrganisations(newOrganisationResource().build(), user)); } else { assertFalse(rules.systemRegistrationUserCanCreateOrganisa...
CompetitionFundedKeyApplicationStatisticsResource { @JsonIgnore public boolean isCanManageFundingNotifications() { return applicationsFunded > 0 || applicationsNotFunded > 0 || applicationsOnHold > 0; } int getApplicationsSubmitted(); void setApplicationsSubmitted(int applicationsSubmitted); int getApplicationsFunded(...
@Test public void isCanManageFundingNotifications() { List<CompetitionFundedKeyApplicationStatisticsResource> resources = newCompetitionFundedKeyApplicationStatisticsResource() .withApplicationsFunded(0, 1, 0, 0, 1, 0, 1, 1) .withApplicationsNotFunded(0, 0, 1, 0, 1, 1, 0, 1) .withApplicationsOnHold(0, 0, 0, 1, 0, 1, 0,...
CompetitionFundedKeyApplicationStatisticsResource { @JsonIgnore public boolean isCanReleaseFeedback() { return applicationsAwaitingDecision == 0 && applicationsSubmitted == applicationsNotifiedOfDecision; } int getApplicationsSubmitted(); void setApplicationsSubmitted(int applicationsSubmitted); int getApplicationsFun...
@Test public void isCanReleaseFeedback() { List<CompetitionFundedKeyApplicationStatisticsResource> resources = newCompetitionFundedKeyApplicationStatisticsResource() .withApplicationsAwaitingDecision(1,1,0,0) .withApplicationsSubmitted(1,1,1,1) .withApplicationsNotifiedOfDecision(0,1,0,1) .build(4); boolean[] expectedC...
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getAssociateSalary() { return associateSalary; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagemen...
@Test public void getAssociateSalary() { assertEquals(associateSalary, additionalCompanyCostCategory.getAssociateSalary()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getManagementSupervision() { return managementSupervision; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void ...
@Test public void getManagementSupervision() { assertEquals(managementSupervision, additionalCompanyCostCategory.getManagementSupervision()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getOtherStaff() { return otherStaff; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervisi...
@Test public void getOtherStaff() { assertEquals(otherStaff, additionalCompanyCostCategory.getOtherStaff()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getCapitalEquipment() { return capitalEquipment; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagem...
@Test public void getCapitalEquipment() { assertEquals(capitalEquipment, additionalCompanyCostCategory.getCapitalEquipment()); }
OrganisationPermissionRules { @PermissionRule(value = "UPDATE", description = "The System Registration User can update Organisations that are not yet linked to Applications on behalf of non-logged in Users " + "during the regsitration process") public boolean systemRegistrationUserCanUpdateOrganisationsNotYetConnectedT...
@Test public void systemRegistrationUserCanUpdateOrganisationsNotYetConnectedToApplicationsOrUsers() { when(processRoleRepository.existsByOrganisationId(anyLong())).thenReturn(false); allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanUpdateOrgani...
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getConsumables() { return consumables; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervi...
@Test public void getConsumables() { assertEquals(consumables, additionalCompanyCostCategory.getConsumables()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { public AdditionalCompanyCost getOtherCosts() { return otherCosts; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervisi...
@Test public void getOtherCosts() { assertEquals(otherCosts, additionalCompanyCostCategory.getOtherCosts()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { @Override @JsonIgnore public List<FinanceRowItem> getCosts() { return newArrayList(associateSalary, managementSupervision, otherStaff, capitalEquipment, consumables, otherCosts); } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(Addi...
@Test public void getCosts() { assertEquals(costs, additionalCompanyCostCategory.getCosts()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { @Override public BigDecimal getTotal() { return total; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervision(Addition...
@Test public void getTotal() { BigDecimal result = associateSalary.getTotal() .add(managementSupervision.getTotal()) .add(otherStaff.getTotal()) .add(capitalEquipment.getTotal()) .add(consumables.getTotal()) .add(otherCosts.getTotal()); additionalCompanyCostCategory.calculateTotal(); assertEquals(result, additionalComp...