-
Notifications
You must be signed in to change notification settings - Fork 4
/
NameParserGbifV1.java
355 lines (304 loc) · 11.4 KB
/
NameParserGbifV1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.nameparser;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.gbif.api.exception.UnparsableException;
import org.gbif.api.model.checklistbank.ParsedName;
import org.gbif.api.service.checklistbank.NameParser;
import org.gbif.api.vocabulary.NameType;
import org.gbif.api.vocabulary.Rank;
import org.gbif.nameparser.api.NamePart;
import org.gbif.nameparser.api.NomCode;
import org.gbif.nameparser.api.UnparsableNameException;
import org.gbif.nameparser.api.Warnings;
import org.gbif.nameparser.util.NameFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Map;
import static org.gbif.nameparser.api.ParsedName.State;
/**
* A name parser wrapped to return classic ParsedName objects from the GBIF API v1.
*/
public class NameParserGbifV1 implements NameParser {
private static Logger LOG = LoggerFactory.getLogger(NameParserGbifV1.class);
private static final Map<org.gbif.nameparser.api.NameType, NameType> NAME_TYPE_MAP = ImmutableMap.<org.gbif.nameparser.api.NameType, NameType>builder()
.put(org.gbif.nameparser.api.NameType.SCIENTIFIC, NameType.SCIENTIFIC)
.put(org.gbif.nameparser.api.NameType.VIRUS, NameType.VIRUS)
.put(org.gbif.nameparser.api.NameType.HYBRID_FORMULA, NameType.HYBRID)
.put(org.gbif.nameparser.api.NameType.INFORMAL, NameType.INFORMAL)
.put(org.gbif.nameparser.api.NameType.OTU, NameType.OTU)
.put(org.gbif.nameparser.api.NameType.PLACEHOLDER, NameType.PLACEHOLDER)
.put(org.gbif.nameparser.api.NameType.NO_NAME, NameType.NO_NAME)
.build();
private final NameParserGBIF parser;
/**
* Using the default GBIF RegEx Name Parser.
*/
public NameParserGbifV1() {
this.parser = new NameParserGBIF();
}
/**
* Using the default GBIF RegEx Name Parser with a given timeout for parsing a single name.
* @param timeout in milliseconds before returning an Unparsable name
*/
public NameParserGbifV1(long timeout) {
this.parser = new NameParserGBIF(timeout);
}
public NameParserGbifV1(NameParserGBIF parser) {
this.parser = parser;
}
public long getTimeout() {
return parser.getTimeout();
}
public void setTimeout(long timeout) {
parser.setTimeout(timeout);
}
@Override
public ParsedName parse(String s, @Nullable Rank rank) throws UnparsableException {
try {
return convert(s, rank, parser.parse(s, fromGbif(rank)));
} catch (InterruptedException e) {
// got interrupted but we cant handle it or rethrow it. next best option is to reset the threads flag
Thread.currentThread().interrupt();
throw new IllegalStateException("Thread got interrupted");
} catch (UnparsableNameException e) {
throw new UnparsableException(NAME_TYPE_MAP.getOrDefault(e.getType(), NameType.DOUBTFUL), e.getName());
}
}
@Override
public ParsedName parse(String scientificName) throws UnparsableException {
return parse(scientificName, null);
}
@Override
public ParsedName parseQuietly(String scientificName, @Nullable Rank rank) {
ParsedName p;
try {
p = parse(scientificName, rank);
} catch (UnparsableException e) {
p = new ParsedName();
p.setScientificName(scientificName);
p.setRank(rank);
p.setType(e.type);
p.setParsed(false);
p.setParsedPartially(false);
}
return p;
}
@Override
public ParsedName parseQuietly(String scientificName) {
return parseQuietly(scientificName, null);
}
@Override
// parses the name without authorship and returns the ParsedName.canonicalName() string
public String parseToCanonical(String scientificName, @Nullable Rank rank) {
if (StringUtils.isBlank(scientificName)) {
return null;
}
try {
ParsedName pn = parse(scientificName, rank);
if (pn != null) {
return pn.canonicalName();
}
} catch (UnparsableException e) {
logUnparsable(e);
}
return null;
}
private static void logUnparsable(UnparsableException e) {
if (e.type.isParsable()) {
LOG.debug("Unparsable {} {} >>> {}", e.type, e.name, e.getMessage());
} else {
LOG.warn("Unparsable {} {} >>> {}", e.type, e.name, e.getMessage());
}
}
@Override
public String parseToCanonical(String scientificName) {
return parseToCanonical(scientificName, null);
}
public String parseToCanonicalOrScientificName(String scientificName) {
return parseToCanonicalOrScientificName(scientificName, null);
}
/**
* Tries to parses the name without authorship and returns the ParsedName.canonicalName() string
* For unparsable types and other UnparsableExceptions the original scientific name is returned.
* @param rank the rank of the name if it is known externally. Helps identifying infrageneric names vs bracket authors
*/
public String parseToCanonicalOrScientificName(String scientificName, @Nullable Rank rank) {
if (StringUtils.isBlank(scientificName)) {
return null;
}
try {
ParsedName pn = parse(scientificName, rank);
if (pn != null) {
return pn.canonicalName();
}
} catch (UnparsableException e) {
logUnparsable(e);
}
return StringUtils.normalizeSpace(scientificName.trim());
}
private ParsedName convert(String scientificName, Rank rank, org.gbif.nameparser.api.ParsedName pn) throws UnparsableException {
// throw unparsable for all unparsable types but placeholder and for all names that have a not parsed state
if ((!pn.getType().isParsable() && pn.getType() != org.gbif.nameparser.api.NameType.PLACEHOLDER)
|| pn.getState() == org.gbif.nameparser.api.ParsedName.State.NONE) {
throw new UnparsableException(gbifNameType(pn), scientificName);
}
ParsedName gbif = new ParsedName();
gbif.setType(gbifNameType(pn));
gbif.setScientificName(scientificName);
gbif.setGenusOrAbove(pn.getGenus() != null ? pn.getGenus(): pn.getUninomial());
gbif.setInfraGeneric(pn.getInfragenericEpithet());
gbif.setSpecificEpithet(pn.getSpecificEpithet());
gbif.setInfraSpecificEpithet(pn.getInfraspecificEpithet());
gbif.setCultivarEpithet(pn.getCultivarEpithet());
gbif.setNotho(toGbif(pn.getNotho()));
gbif.setRank(toGbif(pn.getRank()));
// in the old API we used null instead of unranked
if (gbif.getRank() == Rank.UNRANKED && Rank.UNRANKED != rank) {
gbif.setRank(null);
}
gbif.setStrain(pn.getPhrase());
gbif.setSensu(pn.getTaxonomicNote());
gbif.setAuthorship(NameFormatter.authorString(pn.getCombinationAuthorship(), false, pn.getCode()));
gbif.setYear(pn.getCombinationAuthorship().getYear());
gbif.setBracketAuthorship(NameFormatter.authorString(pn.getBasionymAuthorship(), false, pn.getCode()));
gbif.setBracketYear(pn.getBasionymAuthorship().getYear());
gbif.setNomStatus(pn.getNomenclaturalNote());
if (pn.getEpithetQualifier() != null && !pn.getEpithetQualifier().isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<NamePart, String> pq : pn.getEpithetQualifier().entrySet()) {
if (sb.length() < 1) {
sb.append(" ");
}
sb.append(pq.getValue())
.append(" ")
.append(pn.getEpithet(pq.getKey()));
}
gbif.setRemarks(sb.toString());
}
// we throw UnparsableException above already for State.NONE
gbif.setParsed(true);
gbif.setParsedPartially(pn.getState() == State.PARTIAL);
return gbif;
}
public static NameType gbifNameType(org.gbif.nameparser.api.ParsedName pn) {
NameType t;
// detect name types that only exist in the GBIF API v1
if (pn.isDoubtful() && pn.getWarnings().contains(Warnings.BLACKLISTED_EPITHET)) {
t = NameType.BLACKLISTED;
} else if (pn.isCandidatus()) {
t = NameType.CANDIDATUS;
} else if (pn.getCode() == NomCode.CULTIVARS || pn.getCultivarEpithet() != null) {
t = NameType.CULTIVAR;
} else {
// convert all others
t = NAME_TYPE_MAP.get(pn.getType());
}
// use doubtful in too good cases
if (pn.isDoubtful() && (t == NameType.SCIENTIFIC || t == NameType.CULTIVAR)) {
return NameType.DOUBTFUL;
}
return t;
}
public static org.gbif.api.vocabulary.NamePart toGbif(NamePart notho) {
return convertEnum(org.gbif.api.vocabulary.NamePart.class, notho);
}
public static Rank toGbif(org.gbif.nameparser.api.Rank rank) {
if (rank == null) {
return null;
}
switch (rank) {
case SUPERDIVISION: return Rank.SUPERPHYLUM;
case DIVISION: return Rank.PHYLUM;
case SUBDIVISION: return Rank.SUBPHYLUM;
case INFRADIVISION: return Rank.INFRAPHYLUM;
case PROLES: return Rank.RACE;
case SECTION_BOTANY: return Rank.SECTION;
case SUBSECTION_BOTANY: return Rank.SUBSECTION;
case SUPERSECTION_BOTANY:
case SUPERSERIES:
return Rank.INFRAGENERIC_NAME;
case KLEPTON:
case SUPERVARIETY:
case SUPERFORM:
case LUSUS:
case MUTATIO:
return Rank.INFRASPECIFIC_NAME;
case SUPERGENUS:
case FALANX:
case GIGAFAMILY:
case MEGAFAMILY:
case GRANDFAMILY:
case EPIFAMILY:
case SUPERSECTION_ZOOLOGY:
case SECTION_ZOOLOGY:
case SUBSECTION_ZOOLOGY:
case GIGAORDER:
case MIRORDER:
case NANORDER:
case HYPOORDER:
case MINORDER:
case MEGACOHORT:
case GIGACLASS:
case MEGACLASS:
case SUBTERCLASS:
case CLAUDIUS:
case PARVPHYLUM:
case MICROPHYLUM:
case NANOPHYLUM:
case SUPERDOMAIN:
case SUBDOMAIN:
case INFRADOMAIN:
case EMPIRE:
case REALM:
case SUBREALM:
return Rank.SUPRAGENERIC_NAME;
default: return convertEnum(Rank.class, rank);
}
}
public static org.gbif.nameparser.api.Rank fromGbif(Rank rank) {
if (rank == null) {
return null;
}
switch (rank) {
case RACE:
case PROLES:
return org.gbif.nameparser.api.Rank.PROLES;
case SECTION:
return org.gbif.nameparser.api.Rank.SECTION_BOTANY;
case SUBSECTION:
return org.gbif.nameparser.api.Rank.SUBSECTION_BOTANY;
default:
return convertEnum(org.gbif.nameparser.api.Rank.class, rank);
}
}
/**
* Converts an enumeration value into a constant with the exact same name from a different enumeration class.
* In case the enumeration constant name does not exist an error is thrown.
*
* @param targetClass class of the target enumeration
* @param value
* @throws IllegalArgumentException in case the enumeration name does not exist in the target class
*/
private static <G extends Enum<G>> G convertEnum(Class<G> targetClass, Enum<?> value) {
try {
return value == null ? null : Enum.valueOf(targetClass, value.name());
} catch (IllegalArgumentException e) {
LOG.warn("Unable to convert {} into {}", value, targetClass);
return null;
}
}
}