1 package club.wpia.gigi.dbObjects;
3 import java.io.PrintWriter;
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;
15 public class Name implements Outputable, IdCachable {
17 public static enum NameSchemaType implements DBEnum {
21 public String getDBName() {
22 return toString().toLowerCase();
27 private abstract static class SchemedName {
30 * @see Name#matches(String)
32 public abstract boolean matches(String text);
34 public abstract String toPreferredString();
37 * @see Name#toAbbreviatedString()
39 public abstract String toAbbreviatedString();
41 public abstract NameSchemaType getSchemeName();
44 * @see Name#output(PrintWriter, Language, Map)
46 public abstract void output(PrintWriter out);
50 private static class SingleName extends SchemedName {
52 private NamePart singlePart;
54 public SingleName(NamePart singlePart) {
55 this.singlePart = singlePart;
59 public boolean matches(String text) {
60 return text.equals(singlePart.getValue());
64 public String toPreferredString() {
65 return singlePart.getValue();
69 public String toAbbreviatedString() {
70 return singlePart.getValue();
74 public NameSchemaType getSchemeName() {
75 return NameSchemaType.SINGLE;
79 public void output(PrintWriter out) {
80 out.print("<span class='sname'>");
81 out.print(HTMLEncoder.encodeHTML(singlePart.getValue()));
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
91 private static class WesternName extends SchemedName {
93 private NamePart[] firstNames;
95 private NamePart[] lastNames;
97 private NamePart[] suffixes;
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");
103 this.lastNames = lastName;
104 this.firstNames = firstName;
105 this.suffixes = suffixes;
109 public boolean matches(String text) {
110 String[] tokens = text.split(" ");
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)) {
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) {
134 currentlyMatchingLastNames = false;
135 } else if (tokens[userInputPos].equals(lastNames[referencePos].getValue())) {
142 if (tokens[userInputPos].equals(suffixes[referencePos].getValue())) {
150 if (userInputPos >= tokens.length) {
151 // all name parts are covered we're done here
157 private boolean tryMatchFirst(String[] tokens, int lastName) {
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])) {
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();
189 public void output(PrintWriter out) {
190 outputNameParts(out, "fname", firstNames, false);
191 outputNameParts(out, "lname", lastNames, true);
192 outputNameParts(out, "suffix", suffixes, true);
195 private void outputNameParts(PrintWriter out, String type, NamePart[] input, boolean leadingSpace) {
197 res = new StringBuilder();
198 appendArray(res, input);
199 if (res.length() > 0) {
200 res.deleteCharAt(res.length() - 1);
204 out.print("<span class='" + type + "'>");
205 out.print(HTMLEncoder.encodeHTML(res.toString()));
206 out.print("</span>");
210 private void appendArray(StringBuilder res, NamePart[] ps) {
211 for (int i = 0; i < ps.length; i++) {
212 res.append(ps[i].getValue());
218 public NameSchemaType getSchemeName() {
219 return NameSchemaType.WESTERN;
223 public String toAbbreviatedString() {
224 return firstNames[0].getValue() + " " + lastNames[0].getValue().charAt(0) + ".";
233 * Only resolved lazily to resolve circular referencing with {@link User} on
234 * {@link User#getPreferredName()}. Resolved based on {@link #ownerId}.
238 private NamePart[] parts;
240 private SchemedName scheme;
243 * This name should not get verifed anymore and therefore not be displayed
244 * to the RA-Agent. This state is irrevocable.
246 private boolean deprecated;
248 private Name(GigiResultSet rs) {
249 ownerId = rs.getInt(1);
251 deprecated = rs.getString("deprecated") != null;
252 try (GigiPreparedStatement partFetcher = new GigiPreparedStatement("SELECT `type`, `value` FROM `nameParts` WHERE `id`=? ORDER BY `position` ASC", true)) {
253 partFetcher.setInt(1, id);
254 GigiResultSet rs1 = partFetcher.executeQuery();
256 NamePart[] dt = new NamePart[rs1.getRow()];
258 for (int i = 0; rs1.next(); i++) {
259 dt[i] = new NamePart(rs1);
262 scheme = detectScheme();
267 public Name(User u, NamePart... np) throws GigiApiException {
268 synchronized (Name.class) {
271 scheme = detectScheme();
272 if (scheme == null) {
273 throw new GigiApiException("Name particles don't match up for any known name scheme.");
275 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO `names` SET `uid`=?, `type`=?::`nameSchemaType`")) {
276 inserter.setInt(1, u.getId());
277 inserter.setEnum(2, scheme.getSchemeName());
279 id = inserter.lastInsertId();
281 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO `nameParts` SET `id`=?, `position`=?, `type`=?::`namePartType`, `value`=?")) {
282 inserter.setInt(1, id);
283 for (int i = 0; i < np.length; i++) {
284 inserter.setInt(2, i);
285 inserter.setEnum(3, np[i].getType());
286 inserter.setString(4, np[i].getValue());
294 private SchemedName detectScheme() {
295 if (parts.length == 1 && parts[0].getType() == NamePartType.SINGLE_NAME) {
296 return new SingleName(parts[0]);
302 for (NamePart p : parts) {
303 if (p.getType() == NamePartType.LAST_NAME) {
307 } else if (stage != 1) {
310 } else if (p.getType() == NamePartType.FIRST_NAME) {
315 } else if (p.getType() == NamePartType.SUFFIX) {
319 } else if (stage != 2) {
327 if (firstCount == 0 || lastCount == 0) {
330 NamePart[] firstNames = new NamePart[firstCount];
331 NamePart[] lastNames = new NamePart[lastCount];
332 NamePart[] suffixes = new NamePart[suffixCount];
336 for (NamePart p : parts) {
337 if (p.getType() == NamePartType.FIRST_NAME) {
338 firstNames[fn++] = p;
339 } else if (p.getType() == NamePartType.SUFFIX) {
341 } else if (p.getType() == NamePartType.LAST_NAME) {
346 return new WesternName(firstNames, lastNames, suffixes);
350 * Outputs an HTML variant suitable for locations where special UI features
351 * should indicate the different Name Parts.
354 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
355 out.print("<span class=\"names\">");
357 out.print("</span>");
361 * Tests, if this name fits into the given string.
364 * the name to test against
365 * @return true, iff this name matches.
367 public boolean matches(String text) {
368 if ( !text.equals(text.trim())) {
371 return scheme.matches(text);
375 public String toString() {
376 return scheme.toPreferredString();
380 * Transforms this String into a short form. This short form should not be
381 * unique. (For "western" names this would be
382 * "firstName firstCharOfLastName.".)
384 * @return the short form of the name
386 public String toAbbreviatedString() {
387 return scheme.toAbbreviatedString();
390 public int getVerificationPoints() {
391 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")) {
392 query.setInt(1, getId());
394 GigiResultSet rs = query.executeQuery();
398 points = rs.getInt(1);
410 private static ObjectCache<Name> cache = new ObjectCache<>();
412 public synchronized static Name getById(int id) {
413 Name cacheRes = cache.get(id);
414 if (cacheRes != null) {
418 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `uid`, `id`, `deprecated` FROM `names` WHERE `deleted` IS NULL AND `id` = ?")) {
420 GigiResultSet rs = ps.executeQuery();
425 Name c = new Name(rs);
431 public NamePart[] getParts() {
435 public void remove() {
436 synchronized (Name.class) {
438 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deleted` = now() WHERE `id`=?")) {
445 public synchronized void deprecate() {
447 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deprecated`=now() WHERE `id`=?")) {
453 public boolean isDeprecated() {
457 public synchronized User getOwner() {
459 owner = User.getById(ownerId);