]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/Name.java
fix: avoid blanks after displayed names
[gigi.git] / src / club / wpia / gigi / dbObjects / Name.java
1 package club.wpia.gigi.dbObjects;
2
3 import java.io.PrintWriter;
4 import java.util.Map;
5
6 import club.wpia.gigi.GigiApiException;
7 import club.wpia.gigi.database.DBEnum;
8 import club.wpia.gigi.database.GigiPreparedStatement;
9 import club.wpia.gigi.database.GigiResultSet;
10 import club.wpia.gigi.dbObjects.NamePart.NamePartType;
11 import club.wpia.gigi.localisation.Language;
12 import club.wpia.gigi.output.template.Outputable;
13 import club.wpia.gigi.util.HTMLEncoder;
14
15 public class Name implements Outputable, IdCachable {
16
17     public static enum NameSchemaType implements DBEnum {
18         SINGLE, WESTERN;
19
20         @Override
21         public String getDBName() {
22             return toString().toLowerCase();
23         }
24
25     }
26
27     private abstract static class SchemedName {
28
29         /**
30          * @see Name#matches(String)
31          */
32         public abstract boolean matches(String text);
33
34         public abstract String toPreferredString();
35
36         /**
37          * @see Name#toAbbreviatedString()
38          */
39         public abstract String toAbbreviatedString();
40
41         public abstract NameSchemaType getSchemeName();
42
43         /**
44          * @see Name#output(PrintWriter, Language, Map)
45          */
46         public abstract void output(PrintWriter out);
47
48     }
49
50     private static class SingleName extends SchemedName {
51
52         private NamePart singlePart;
53
54         public SingleName(NamePart singlePart) {
55             this.singlePart = singlePart;
56         }
57
58         @Override
59         public boolean matches(String text) {
60             return text.equals(singlePart.getValue());
61         }
62
63         @Override
64         public String toPreferredString() {
65             return singlePart.getValue();
66         }
67
68         @Override
69         public String toAbbreviatedString() {
70             return singlePart.getValue();
71         }
72
73         @Override
74         public NameSchemaType getSchemeName() {
75             return NameSchemaType.SINGLE;
76         }
77
78         @Override
79         public void output(PrintWriter out) {
80             out.print("<span class='sname'>");
81             out.print(HTMLEncoder.encodeHTML(singlePart.getValue()));
82             out.print("</span>");
83         }
84     }
85
86     /**
87      * Naming scheme where any first name and the first last name is required.
88      * Requires first names in arbitrary order. Last names and suffixes in
89      * correct order.
90      */
91     private static class WesternName extends SchemedName {
92
93         private NamePart[] firstNames;
94
95         private NamePart[] lastNames;
96
97         private NamePart[] suffixes;
98
99         public WesternName(NamePart[] firstName, NamePart lastName[], NamePart[] suffixes) {
100             if (lastName.length < 1 || firstName.length < 1) {
101                 throw new Error("Requires at least one first and one last name");
102             }
103             this.lastNames = lastName;
104             this.firstNames = firstName;
105             this.suffixes = suffixes;
106         }
107
108         @Override
109         public boolean matches(String text) {
110             String[] tokens = text.split(" ");
111
112             NamePart mandatoryLN = lastNames[0];
113             for (int i = 0; i < tokens.length; i++) {
114                 if (tokens[i].equals(mandatoryLN.getValue())) {
115                     if (tryMatchFirst(tokens, i) && tryMatchLastSuff(tokens, i)) {
116                         return true;
117                     }
118
119                 }
120             }
121             return false;
122         }
123
124         private boolean tryMatchLastSuff(String[] tokens, int lastName) {
125             int userInputPos = lastName + 1;
126             boolean currentlyMatchingLastNames = true;
127             int referencePos = 1;
128             while ((currentlyMatchingLastNames || referencePos < suffixes.length) && (userInputPos < tokens.length)) {
129                 // we break when we match suffixes and there is no
130                 // reference-suffix left
131                 if (currentlyMatchingLastNames) {
132                     if (referencePos >= lastNames.length) {
133                         referencePos = 0;
134                         currentlyMatchingLastNames = false;
135                     } else if (tokens[userInputPos].equals(lastNames[referencePos].getValue())) {
136                         userInputPos++;
137                         referencePos++;
138                     } else {
139                         referencePos++;
140                     }
141                 } else {
142                     if (tokens[userInputPos].equals(suffixes[referencePos].getValue())) {
143                         userInputPos++;
144                         referencePos++;
145                     } else {
146                         referencePos++;
147                     }
148                 }
149             }
150             if (userInputPos >= tokens.length) {
151                 // all name parts are covered we're done here
152                 return true;
153             }
154             return false;
155         }
156
157         private boolean tryMatchFirst(String[] tokens, int lastName) {
158             if (lastName == 0) {
159                 return false;
160             }
161             boolean[] fnUsed = new boolean[firstNames.length];
162             for (int i = 0; i < lastName; i++) {
163                 boolean found = false;
164                 for (int j = 0; j < fnUsed.length; j++) {
165                     if ( !fnUsed[j] && firstNames[j].getValue().equals(tokens[i])) {
166                         fnUsed[j] = true;
167                         found = true;
168                         break;
169                     }
170                 }
171                 if ( !found) {
172                     return false;
173                 }
174             }
175             return true;
176         }
177
178         @Override
179         public String toPreferredString() {
180             StringBuilder res = new StringBuilder();
181             appendArray(res, firstNames);
182             appendArray(res, lastNames);
183             appendArray(res, suffixes);
184             res.deleteCharAt(res.length() - 1);
185             return res.toString();
186         }
187
188         @Override
189         public void output(PrintWriter out) {
190             outputNameParts(out, "fname", firstNames);
191             outputNameParts(out, "lname", lastNames);
192             outputNameParts(out, "suffix", suffixes);
193         }
194
195         private void outputNameParts(PrintWriter out, String type, NamePart[] input) {
196             StringBuilder res;
197             res = new StringBuilder();
198             appendArray(res, input);
199             if (res.length() > 0) {
200                 res.deleteCharAt(res.length() - 1);
201                 out.print("<span class='" + type + "'>");
202                 out.print(HTMLEncoder.encodeHTML(res.toString()));
203                 out.print("</span>");
204             }
205         }
206
207         private void appendArray(StringBuilder res, NamePart[] ps) {
208             for (int i = 0; i < ps.length; i++) {
209                 res.append(ps[i].getValue());
210                 res.append(" ");
211             }
212         }
213
214         @Override
215         public NameSchemaType getSchemeName() {
216             return NameSchemaType.WESTERN;
217         }
218
219         @Override
220         public String toAbbreviatedString() {
221             return firstNames[0].getValue() + " " + lastNames[0].getValue().charAt(0) + ".";
222         }
223     }
224
225     private int id;
226
227     private int ownerId;
228
229     /**
230      * Only resolved lazily to resolve circular referencing with {@link User} on
231      * {@link User#getPreferredName()}. Resolved based on {@link #ownerId}.
232      */
233     private User owner;
234
235     private NamePart[] parts;
236
237     private SchemedName scheme;
238
239     /**
240      * This name should not get verifed anymore and therefore not be displayed
241      * to the RA-Agent. This state is irrevocable.
242      */
243     private boolean deprecated;
244
245     private Name(GigiResultSet rs) {
246         ownerId = rs.getInt(1);
247         id = rs.getInt(2);
248         deprecated = rs.getString("deprecated") != null;
249         try (GigiPreparedStatement partFetcher = new GigiPreparedStatement("SELECT `type`, `value` FROM `nameParts` WHERE `id`=? ORDER BY `position` ASC", true)) {
250             partFetcher.setInt(1, id);
251             GigiResultSet rs1 = partFetcher.executeQuery();
252             rs1.last();
253             NamePart[] dt = new NamePart[rs1.getRow()];
254             rs1.beforeFirst();
255             for (int i = 0; rs1.next(); i++) {
256                 dt[i] = new NamePart(rs1);
257             }
258             parts = dt;
259             scheme = detectScheme();
260         }
261
262     }
263
264     public Name(User u, NamePart... np) throws GigiApiException {
265         synchronized (Name.class) {
266             parts = np;
267             owner = u;
268             scheme = detectScheme();
269             if (scheme == null) {
270                 throw new GigiApiException("Name particles don't match up for any known name scheme.");
271             }
272             try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO `names` SET `uid`=?, `type`=?::`nameSchemaType`")) {
273                 inserter.setInt(1, u.getId());
274                 inserter.setEnum(2, scheme.getSchemeName());
275                 inserter.execute();
276                 id = inserter.lastInsertId();
277             }
278             try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO `nameParts` SET `id`=?, `position`=?, `type`=?::`namePartType`, `value`=?")) {
279                 inserter.setInt(1, id);
280                 for (int i = 0; i < np.length; i++) {
281                     inserter.setInt(2, i);
282                     inserter.setEnum(3, np[i].getType());
283                     inserter.setString(4, np[i].getValue());
284                     inserter.execute();
285                 }
286             }
287             cache.put(this);
288         }
289     }
290
291     private SchemedName detectScheme() {
292         if (parts.length == 1 && parts[0].getType() == NamePartType.SINGLE_NAME) {
293             return new SingleName(parts[0]);
294         }
295         int suffixCount = 0;
296         int lastCount = 0;
297         int firstCount = 0;
298         int stage = 0;
299         for (NamePart p : parts) {
300             if (p.getType() == NamePartType.LAST_NAME) {
301                 lastCount++;
302                 if (stage < 1) {
303                     stage = 1;
304                 } else if (stage != 1) {
305                     return null;
306                 }
307             } else if (p.getType() == NamePartType.FIRST_NAME) {
308                 firstCount++;
309                 if (stage != 0) {
310                     return null;
311                 }
312             } else if (p.getType() == NamePartType.SUFFIX) {
313                 suffixCount++;
314                 if (stage < 2) {
315                     stage = 2;
316                 } else if (stage != 2) {
317                     return null;
318                 }
319
320             } else {
321                 return null;
322             }
323         }
324         if (firstCount == 0 || lastCount == 0) {
325             return null;
326         }
327         NamePart[] firstNames = new NamePart[firstCount];
328         NamePart[] lastNames = new NamePart[lastCount];
329         NamePart[] suffixes = new NamePart[suffixCount];
330         int fn = 0;
331         int ln = 0;
332         int sn = 0;
333         for (NamePart p : parts) {
334             if (p.getType() == NamePartType.FIRST_NAME) {
335                 firstNames[fn++] = p;
336             } else if (p.getType() == NamePartType.SUFFIX) {
337                 suffixes[sn++] = p;
338             } else if (p.getType() == NamePartType.LAST_NAME) {
339                 lastNames[ln++] = p;
340             }
341         }
342
343         return new WesternName(firstNames, lastNames, suffixes);
344     }
345
346     /**
347      * Outputs an HTML variant suitable for locations where special UI features
348      * should indicate the different Name Parts.
349      */
350     @Override
351     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
352         out.print("<span class=\"names\">");
353         scheme.output(out);
354         out.print("</span>");
355     }
356
357     /**
358      * Tests, if this name fits into the given string.
359      * 
360      * @param text
361      *            the name to test against
362      * @return true, iff this name matches.
363      */
364     public boolean matches(String text) {
365         if ( !text.equals(text.trim())) {
366             return false;
367         }
368         return scheme.matches(text);
369     }
370
371     @Override
372     public String toString() {
373         return scheme.toPreferredString();
374     }
375
376     /**
377      * Transforms this String into a short form. This short form should not be
378      * unique. (For "western" names this would be
379      * "firstName firstCharOfLastName.".)
380      * 
381      * @return the short form of the name
382      */
383     public String toAbbreviatedString() {
384         return scheme.toAbbreviatedString();
385     }
386
387     public int getVerificationPoints() {
388         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(`points`) FROM (SELECT DISTINCT ON (`from`, `method`) `points` FROM `notary` WHERE `to`=? AND `deleted` IS NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP) ORDER BY `from`, `method`, `when` DESC) AS p")) {
389             query.setInt(1, getId());
390
391             GigiResultSet rs = query.executeQuery();
392             int points = 0;
393
394             if (rs.next()) {
395                 points = rs.getInt(1);
396             }
397
398             return points;
399         }
400     }
401
402     @Override
403     public int getId() {
404         return id;
405     }
406
407     private static ObjectCache<Name> cache = new ObjectCache<>();
408
409     public synchronized static Name getById(int id) {
410         Name cacheRes = cache.get(id);
411         if (cacheRes != null) {
412             return cacheRes;
413         }
414
415         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `uid`, `id`, `deprecated` FROM `names` WHERE `deleted` IS NULL AND `id` = ?")) {
416             ps.setInt(1, id);
417             GigiResultSet rs = ps.executeQuery();
418             if ( !rs.next()) {
419                 return null;
420             }
421
422             Name c = new Name(rs);
423             cache.put(c);
424             return c;
425         }
426     }
427
428     public NamePart[] getParts() {
429         return parts;
430     }
431
432     public void remove() {
433         synchronized (Name.class) {
434             cache.remove(this);
435             try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deleted` = now() WHERE `id`=?")) {
436                 ps.setInt(1, id);
437                 ps.executeUpdate();
438             }
439         }
440     }
441
442     public synchronized void deprecate() {
443         deprecated = true;
444         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deprecated`=now() WHERE `id`=?")) {
445             ps.setInt(1, id);
446             ps.executeUpdate();
447         }
448     }
449
450     public boolean isDeprecated() {
451         return deprecated;
452     }
453
454     public synchronized User getOwner() {
455         if (owner == null) {
456             owner = User.getById(ownerId);
457         }
458         return owner;
459     }
460 }