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()));
82 out.println("</span>");
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);
191 outputNameParts(out, "lname", lastNames);
192 outputNameParts(out, "suffix", suffixes);
195 private void outputNameParts(PrintWriter out, String type, NamePart[] input) {
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.println("</span>");
207 private void appendArray(StringBuilder res, NamePart[] ps) {
208 for (int i = 0; i < ps.length; i++) {
209 res.append(ps[i].getValue());
215 public NameSchemaType getSchemeName() {
216 return NameSchemaType.WESTERN;
220 public String toAbbreviatedString() {
221 return firstNames[0].getValue() + " " + lastNames[0].getValue().charAt(0) + ".";
230 * Only resolved lazily to resolve circular referencing with {@link User} on
231 * {@link User#getPreferredName()}. Resolved based on {@link #ownerId}.
235 private NamePart[] parts;
237 private SchemedName scheme;
240 * This name should not get verifed anymore and therefore not be displayed
241 * to the RA-Agent. This state is irrevocable.
243 private boolean deprecated;
245 private Name(GigiResultSet rs) {
246 ownerId = rs.getInt(1);
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();
253 NamePart[] dt = new NamePart[rs1.getRow()];
255 for (int i = 0; rs1.next(); i++) {
256 dt[i] = new NamePart(rs1);
259 scheme = detectScheme();
264 public Name(User u, NamePart... np) throws GigiApiException {
265 synchronized (Name.class) {
268 scheme = detectScheme();
269 if (scheme == null) {
270 throw new GigiApiException("Name particles don't match up for any known name scheme.");
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());
276 id = inserter.lastInsertId();
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());
291 private SchemedName detectScheme() {
292 if (parts.length == 1 && parts[0].getType() == NamePartType.SINGLE_NAME) {
293 return new SingleName(parts[0]);
299 for (NamePart p : parts) {
300 if (p.getType() == NamePartType.LAST_NAME) {
304 } else if (stage != 1) {
307 } else if (p.getType() == NamePartType.FIRST_NAME) {
312 } else if (p.getType() == NamePartType.SUFFIX) {
316 } else if (stage != 2) {
324 if (firstCount == 0 || lastCount == 0) {
327 NamePart[] firstNames = new NamePart[firstCount];
328 NamePart[] lastNames = new NamePart[lastCount];
329 NamePart[] suffixes = new NamePart[suffixCount];
333 for (NamePart p : parts) {
334 if (p.getType() == NamePartType.FIRST_NAME) {
335 firstNames[fn++] = p;
336 } else if (p.getType() == NamePartType.SUFFIX) {
338 } else if (p.getType() == NamePartType.LAST_NAME) {
343 return new WesternName(firstNames, lastNames, suffixes);
347 * Outputs an HTML variant suitable for locations where special UI features
348 * should indicate the different Name Parts.
351 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
352 out.print("<span class=\"names\">");
354 out.print("</span> ");
358 * Tests, if this name fits into the given string.
361 * the name to test against
362 * @return true, iff this name matches.
364 public boolean matches(String text) {
365 if ( !text.equals(text.trim())) {
368 return scheme.matches(text);
372 public String toString() {
373 return scheme.toPreferredString();
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.".)
381 * @return the short form of the name
383 public String toAbbreviatedString() {
384 return scheme.toAbbreviatedString();
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());
391 GigiResultSet rs = query.executeQuery();
395 points = rs.getInt(1);
407 private static ObjectCache<Name> cache = new ObjectCache<>();
409 public synchronized static Name getById(int id) {
410 Name cacheRes = cache.get(id);
411 if (cacheRes != null) {
415 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `uid`, `id`, `deprecated` FROM `names` WHERE `deleted` IS NULL AND `id` = ?")) {
417 GigiResultSet rs = ps.executeQuery();
422 Name c = new Name(rs);
428 public NamePart[] getParts() {
432 public void remove() {
433 synchronized (Name.class) {
435 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deleted` = now() WHERE `id`=?")) {
442 public synchronized void deprecate() {
444 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `names` SET `deprecated`=now() WHERE `id`=?")) {
450 public boolean isDeprecated() {
454 public synchronized User getOwner() {
456 owner = User.getById(ownerId);