1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package eu.ehri.project.models.idgen;
21
22 import com.google.common.base.Joiner;
23 import com.google.common.collect.ArrayListMultimap;
24 import com.google.common.collect.ListMultimap;
25 import com.google.common.collect.Lists;
26 import eu.ehri.project.acl.SystemScope;
27 import eu.ehri.project.models.base.PermissionScope;
28 import eu.ehri.project.persistence.Bundle;
29 import eu.ehri.project.persistence.Messages;
30 import eu.ehri.project.utils.Slugify;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import java.text.MessageFormat;
35 import java.util.Collection;
36 import java.util.List;
37
38
39
40
41 public class IdGeneratorUtils {
42
43
44
45 public static final String HIERARCHY_SEPARATOR = "-";
46 public static final String SLUG_REPLACE = "_";
47
48 private static final Joiner hierarchyJoiner = Joiner.on(HIERARCHY_SEPARATOR);
49
50 protected final static Logger logger = LoggerFactory.getLogger(IdGeneratorUtils.class);
51
52 public static ListMultimap<String, String> handleIdCollision(Collection<String> scopeIds,
53 String dataKey, String ident) {
54
55 logger.error("ID Generation error: {}={} (scope: {})", dataKey, ident, Lists.newArrayList(scopeIds));
56 ListMultimap<String, String> errors = ArrayListMultimap.create();
57 errors.put(dataKey, MessageFormat.format(
58 Messages.getString("BundleManager.uniquenessError"), ident));
59 return errors;
60 }
61
62
63
64
65
66
67
68
69
70
71 public static String generateId(PermissionScope scope, Bundle bundle, String ident) {
72 List<String> scopeIds = Lists.newArrayList();
73 if (scope != null && !scope.equals(SystemScope.getInstance())) {
74 for (PermissionScope s : scope.getPermissionScopes()) {
75 scopeIds.add(0, s.getIdentifier());
76 }
77 scopeIds.add(scope.getIdentifier());
78 }
79 return generateId(scopeIds, bundle, ident);
80 }
81
82
83
84
85
86
87
88
89
90
91 public static String generateId(Collection<String> scopeIds, Bundle bundle, String ident) {
92
93
94 if (ident == null || ident.trim().isEmpty()) {
95 throw new RuntimeException("Invalid null identifier for "
96 + bundle.getType().getName() + ": " + bundle.getData());
97 }
98 List<String> newIds = Lists.newArrayList(scopeIds);
99 newIds.add(ident);
100 return joinPath(newIds);
101 }
102
103
104
105
106
107
108
109
110
111 public static String joinPath(Collection<String> path) {
112
113
114
115 List<String> newPaths = Lists.newArrayList();
116 String last = null;
117 for (String ident : path) {
118 if (last == null) {
119 newPaths.add(ident);
120 } else {
121 if (ident.startsWith(last) && !ident.equals(last)) {
122 newPaths.add(ident.substring(last.length()));
123 } else {
124 newPaths.add(ident);
125 }
126 }
127 last = ident;
128 }
129
130
131 List<String> slugged = Lists.newArrayList();
132 for (String p : newPaths) {
133 slugged.add(Slugify.slugify(p, SLUG_REPLACE));
134 }
135
136 return hierarchyJoiner.join(slugged);
137 }
138 }