1 package fr.ifremer.tutti.persistence.entities;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import com.google.common.base.Function;
26 import com.google.common.base.Predicate;
27 import com.google.common.collect.Iterables;
28 import com.google.common.collect.Lists;
29 import com.google.common.collect.Maps;
30
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.Map;
35
36
37
38
39
40
41
42 public class TuttiEntities {
43
44 protected TuttiEntities() {
45
46 }
47
48
49
50
51
52
53
54 public static <B extends TuttiEntity> List<Integer> toIntegerIds(Collection<B> list) {
55 return list == null ?
56 Collections.<Integer>emptyList() :
57 Lists.transform(Lists.newArrayList(list), GET_ID_AS_INT);
58 }
59
60 public static <B extends TuttiEntity> Map<String, B> splitById(Iterable<B> list) {
61 return Maps.uniqueIndex(list, GET_ID);
62 }
63
64 public static <B extends TuttiEntity> Map<Integer, B> splitByIdAsInt(Iterable<B> list) {
65 return Maps.uniqueIndex(list, GET_ID_AS_INT);
66 }
67
68 public static <B extends TuttiEntity> boolean isNew(B bean) {
69 return bean.getId() == null;
70 }
71
72 public static final Function<TuttiEntity, String> GET_ID = TuttiEntity::getId;
73
74 public static <E extends TuttiEntity> Function<E, String> newIdFunction() {
75 return (Function<E, String>) GET_ID;
76 }
77
78 public static <E extends TuttiEntity> Function<E, Integer> newIdAstIntFunction() {
79 return (Function<E, Integer>) GET_ID_AS_INT;
80 }
81
82 public static final Function<TuttiEntity, Integer> GET_ID_AS_INT = TuttiEntity::getIdAsInt;
83
84 public static <B extends TuttiEntity> Predicate<B> newIdPredicate(String id) {
85 return new IdPredicate<>(id);
86 }
87
88 public static <B extends TuttiEntity> B findById(Iterable<B> beans, String id) {
89 return Iterables.tryFind(beans, newIdPredicate(id)).orNull();
90 }
91
92 public static <B extends TuttiEntity> List<String> collecIds(List<B> list) {
93 return Lists.transform(list, GET_ID);
94 }
95
96 protected static class IdPredicate<B extends TuttiEntity> implements Predicate<B> {
97
98 private final String id;
99
100 public IdPredicate(String id) {
101 this.id = id;
102 }
103
104 @Override
105 public boolean apply(B input) {
106 return id.equals(input.getId());
107 }
108 }
109
110 }
111
112