1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.oscal.lib.profile.resolver;
7   
8   import java.util.Collections;
9   import java.util.LinkedHashMap;
10  import java.util.List;
11  import java.util.Map;
12  import java.util.Objects;
13  import java.util.function.Function;
14  import java.util.stream.Collectors;
15  import java.util.stream.Stream;
16  
17  import dev.metaschema.core.util.CollectionUtil;
18  import edu.umd.cs.findbugs.annotations.NonNull;
19  import edu.umd.cs.findbugs.annotations.Nullable;
20  
21  public final class ModifyPhaseUtils {
22    private ModifyPhaseUtils() {
23      // disable construction
24    }
25  
26    public static <T> Function<? super T, String> identityKey() {
27      return item -> Integer.toString(Objects.hashCode(item));
28    }
29  
30    public static <T, R> Function<? super T, String> identifierKey(@NonNull Function<T, R> identifierFunction) {
31      return item -> {
32        R identifier = identifierFunction.apply(item);
33        String retval;
34        if (identifier == null) {
35          retval = Integer.toString(Objects.hashCode(item));
36        } else {
37          retval = identifier.toString();
38        }
39        return retval;
40      };
41    }
42  
43    @SuppressWarnings("PMD.OnlyOneReturn") // readability
44    public static <T> T mergeItem(@Nullable T original, @Nullable T additional) {
45      if (additional == null) {
46        return original;
47      }
48  
49      return additional;
50    }
51  
52    @SuppressWarnings("PMD.OnlyOneReturn") // readability
53    public static <T> List<T> merge(@Nullable List<T> original, @Nullable List<T> additional,
54        Function<? super T, String> keyFunction) {
55      if (additional == null || additional.isEmpty()) {
56        return original;
57      }
58  
59      if (original == null || original.isEmpty()) {
60        return additional;
61      }
62  
63      // reverse the stream
64      List<T> reversed = Stream.concat(
65          CollectionUtil.listOrEmpty(original).stream(),
66          CollectionUtil.listOrEmpty(additional).stream())
67          .collect(Collectors.collectingAndThen(
68              Collectors.toList(),
69              l -> {
70                Collections.reverse(l);
71                return l;
72              }));
73  
74      // build a map of each unique identity
75      Map<String, List<T>> identityMap = reversed.stream()
76          .collect(Collectors.groupingBy(keyFunction, LinkedHashMap::new, Collectors.toList()));
77  
78      // build a reversed list of items, using the first item
79      return identityMap.values().stream()
80          .map(list -> list.stream().findFirst().get())
81          .collect(Collectors.collectingAndThen(
82              Collectors.toList(),
83              l -> {
84                Collections.reverse(l);
85                return l;
86              }));
87    }
88  }