Project

General

Profile

Download (54.2 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2009 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

    
10
package eu.etaxonomy.cdm.strategy.parser;
11

    
12
import java.util.HashSet;
13
import java.util.Set;
14
import java.util.regex.Matcher;
15
import java.util.regex.Pattern;
16

    
17
import org.apache.commons.lang.StringUtils;
18
import org.apache.log4j.Logger;
19
import org.joda.time.DateTimeFieldType;
20
import org.joda.time.Partial;
21

    
22
import eu.etaxonomy.cdm.common.CdmUtils;
23
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
24
import eu.etaxonomy.cdm.model.agent.Person;
25
import eu.etaxonomy.cdm.model.agent.Team;
26
import eu.etaxonomy.cdm.model.agent.TeamOrPersonBase;
27
import eu.etaxonomy.cdm.model.common.CdmBase;
28
import eu.etaxonomy.cdm.model.common.IParsable;
29
import eu.etaxonomy.cdm.model.common.TimePeriod;
30
import eu.etaxonomy.cdm.model.name.BacterialName;
31
import eu.etaxonomy.cdm.model.name.BotanicalName;
32
import eu.etaxonomy.cdm.model.name.CultivarPlantName;
33
import eu.etaxonomy.cdm.model.name.HybridRelationship;
34
import eu.etaxonomy.cdm.model.name.HybridRelationshipType;
35
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
36
import eu.etaxonomy.cdm.model.name.NomenclaturalStatus;
37
import eu.etaxonomy.cdm.model.name.NomenclaturalStatusType;
38
import eu.etaxonomy.cdm.model.name.NonViralName;
39
import eu.etaxonomy.cdm.model.name.Rank;
40
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
41
import eu.etaxonomy.cdm.model.name.ZoologicalName;
42
import eu.etaxonomy.cdm.model.reference.IBook;
43
import eu.etaxonomy.cdm.model.reference.IBookSection;
44
import eu.etaxonomy.cdm.model.reference.INomenclaturalReference;
45
import eu.etaxonomy.cdm.model.reference.IVolumeReference;
46
import eu.etaxonomy.cdm.model.reference.Reference;
47
import eu.etaxonomy.cdm.model.reference.ReferenceFactory;
48
import eu.etaxonomy.cdm.model.reference.ReferenceType;
49
import eu.etaxonomy.cdm.strategy.exceptions.StringNotParsableException;
50
import eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException;
51

    
52

    
53
/**
54
 * @author a.mueller
55
 *
56
 */
57
public class NonViralNameParserImpl extends NonViralNameParserImplRegExBase implements INonViralNameParser<NonViralName> {
58
	private static final Logger logger = Logger.getLogger(NonViralNameParserImpl.class);
59

    
60
	// good intro: http://java.sun.com/docs/books/tutorial/essential/regex/index.html
61

    
62
	final static boolean MAKE_EMPTY = true;
63
	final static boolean MAKE_NOT_EMPTY = false;
64

    
65
	private final boolean authorIsAlwaysTeam = false;
66

    
67
	public static NonViralNameParserImpl NewInstance(){
68
		return new NonViralNameParserImpl();
69
	}
70

    
71
	@Override
72
    public NonViralName parseSimpleName(String simpleName){
73
		return parseSimpleName(simpleName, null, null);
74
	}
75

    
76
	@Override
77
    public NonViralName parseSimpleName(String simpleName, NomenclaturalCode code, Rank rank){
78
		//"parseSimpleName() not yet implemented. Uses parseFullName() instead");
79
		return parseFullName(simpleName, code, rank);
80
	}
81

    
82
	public void parseSimpleName(NonViralName nameToBeFilled, String simpleNameString, Rank rank, boolean makeEmpty){
83
		//"parseSimpleName() not yet implemented. Uses parseFullName() instead");
84
		parseFullName(nameToBeFilled, simpleNameString, rank, makeEmpty);
85
	}
86

    
87
	public NonViralName getNonViralNameInstance(String fullString, NomenclaturalCode code){
88
		return getNonViralNameInstance(fullString, code, null);
89
	}
90

    
91
	public NonViralName getNonViralNameInstance(String fullString, NomenclaturalCode code, Rank rank){
92
		NonViralName<?> result = null;
93
		if(code ==null) {
94
			boolean isBotanicalName = anyBotanicFullNamePattern.matcher(fullString).find();
95
			boolean isZoologicalName = anyZooFullNamePattern.matcher(fullString).find();;
96
			boolean isBacteriologicalName = false;
97
			boolean isCultivatedPlantName = false;
98
			if ( (isBotanicalName || isCultivatedPlantName) && ! isZoologicalName && !isBacteriologicalName){
99
				if (isBotanicalName){
100
					result = BotanicalName.NewInstance(rank);
101
				}else{
102
					result = CultivarPlantName.NewInstance(rank);
103
				}
104
			}else if ( isZoologicalName /*&& ! isBotanicalName*/ && !isBacteriologicalName && !isCultivatedPlantName){
105
				result = ZoologicalName.NewInstance(rank);
106
			}else if ( isZoologicalName && ! isBotanicalName && !isBacteriologicalName && !isCultivatedPlantName){
107
				result = BacterialName.NewInstance(rank);
108
			}else {
109
				result =  NonViralName.NewInstance(rank);
110
			}
111
		} else {
112
			switch (code) {
113
			case ICNAFP:
114
				result = BotanicalName.NewInstance(rank);
115
				break;
116
			case ICZN:
117
				result = ZoologicalName.NewInstance(rank);
118
				break;
119
			case ICNCP:
120
				logger.warn("ICNCP parsing not yet implemented");
121
				result = CultivarPlantName.NewInstance(rank);
122
				break;
123
			case ICNB:
124
				logger.warn("ICNB not yet implemented");
125
				result = BacterialName.NewInstance(rank);
126
				break;
127
			case ICVCN:
128
				logger.error("Viral name is not a NonViralName !!");
129
				break;
130
			default:
131
				// FIXME Unreachable code
132
				logger.error("Unknown Nomenclatural Code !!");
133
			}
134
		}
135
		return result;
136
	}
137

    
138
	@Override
139
    public NonViralName parseReferencedName(String fullReferenceString) {
140
		return parseReferencedName(fullReferenceString, null, null);
141
	}
142

    
143
	@Override
144
    public NonViralName parseReferencedName(String fullReferenceString, NomenclaturalCode nomCode, Rank rank) {
145
		if (fullReferenceString == null){
146
			return null;
147
		}else{
148
			NonViralName<?> result = getNonViralNameInstance(fullReferenceString, nomCode, rank);
149
			parseReferencedName(result, fullReferenceString, rank, MAKE_EMPTY);
150
			return result;
151
		}
152
	}
153

    
154
	private String standardize(NonViralName<?> nameToBeFilled, String fullReferenceString, boolean makeEmpty){
155
		//Check null and standardize
156
		if (fullReferenceString == null){
157
			//return null;
158
			return null;
159
		}
160
		if (makeEmpty){
161
			makeEmpty(nameToBeFilled);
162
		}
163
		fullReferenceString = fullReferenceString.replaceAll(oWs , " ");
164
		fullReferenceString = fullReferenceString.trim();
165
		if ("".equals(fullReferenceString)){
166
			fullReferenceString = null;
167
		}
168
		return fullReferenceString;
169
	}
170

    
171
	/**
172
	 * Returns the regEx to be used for the full-name depending on the code
173
	 * @param nameToBeFilled
174
	 * @return
175
	 */
176
	private String getCodeSpecificFullNameRegEx(NonViralName<?> nameToBeFilledOrig){
177
	    NonViralName<?> nameToBeFilled = HibernateProxyHelper.deproxy(nameToBeFilledOrig, NonViralName.class);
178
		if (nameToBeFilled instanceof ZoologicalName){
179
			return anyZooFullName;
180
		}else if (nameToBeFilled instanceof BotanicalName) {
181
			return anyBotanicFullName;
182
		}else if (nameToBeFilled instanceof NonViralName) {
183
			return anyBotanicFullName;  //TODO ?
184
		}else{
185
			logger.warn("nameToBeFilled class not supported ("+nameToBeFilled.getClass()+")");
186
			return null;
187
		}
188
	}
189

    
190
	/**
191
	 * Returns the regEx to be used for the fsimple-name depending on the code
192
	 * @param nameToBeFilled
193
	 * @return
194
	 */
195
	private String getCodeSpecificSimpleNameRegEx(NonViralName<?> nameToBeFilled){
196
		nameToBeFilled = HibernateProxyHelper.deproxy(nameToBeFilled, NonViralName.class);
197

    
198
		if (nameToBeFilled instanceof ZoologicalName){
199
			return anyZooName;
200
		}else if (nameToBeFilled instanceof NonViralName){
201
			return anyZooName;  //TODO ?
202
		}else if (nameToBeFilled instanceof BotanicalName) {
203
			return anyBotanicName;
204
		}else{
205
			logger.warn("nameToBeFilled class not supported ("+nameToBeFilled.getClass()+")");
206
			return null;
207
		}
208
	}
209

    
210
	private Matcher getMatcher(String regEx, String matchString){
211
		Pattern pattern = Pattern.compile(regEx);
212
		Matcher matcher = pattern.matcher(matchString);
213
		return matcher;
214
	}
215

    
216
	@Override
217
    public void parseReferencedName(NonViralName nameToBeFilled, String fullReferenceStringOrig, Rank rank, boolean makeEmpty) {
218
		//standardize
219
		String fullReferenceString = standardize(nameToBeFilled, fullReferenceStringOrig, makeEmpty);
220
		if (fullReferenceString == null){
221
			return;
222
		}
223
		// happens already in standardize(...)
224
//		makeProblemEmpty(nameToBeFilled);
225

    
226
		//make nomenclatural status and replace it by empty string
227
	    fullReferenceString = parseNomStatus(fullReferenceString, nameToBeFilled, makeEmpty);
228
	    nameToBeFilled.setProblemEnds(fullReferenceString.length());
229

    
230
	    //get full name reg
231
		String localFullNameRegEx = getCodeSpecificFullNameRegEx(nameToBeFilled);
232
		//get full name reg
233
		String localSimpleNameRegEx = getCodeSpecificSimpleNameRegEx(nameToBeFilled);
234

    
235
		//separate name and reference part
236
		String nameAndRefSeparatorRegEx = "(^" + localFullNameRegEx + ")("+ referenceSeperator + ")";
237
		Matcher nameAndRefSeparatorMatcher = getMatcher (nameAndRefSeparatorRegEx, fullReferenceString);
238

    
239
		Matcher onlyNameMatcher = getMatcher (localFullNameRegEx, fullReferenceString);
240
		Matcher hybridMatcher = hybridFormulaPattern.matcher(fullReferenceString);
241
		Matcher onlySimpleNameMatcher = getMatcher (localSimpleNameRegEx, fullReferenceString);
242

    
243
		if (onlyNameMatcher.matches()){
244
			makeEmpty = false;
245
			parseFullName(nameToBeFilled, fullReferenceString, rank, makeEmpty);
246
		} else if (nameAndRefSeparatorMatcher.find()){
247
			makeNameWithReference(nameToBeFilled, fullReferenceString, nameAndRefSeparatorMatcher, rank, makeEmpty);
248
		}else if (hybridMatcher.matches() ){
249
		    //I do not remember why we need makeEmpty = false for onlyNameMatcher,
250
		    //but for hybridMatcher we need to remove old Hybrid Relationships if necessary, therefore
251
		    //I removed it from here
252
            parseFullName(nameToBeFilled, fullReferenceString, rank, makeEmpty);
253
        }else if (onlySimpleNameMatcher.matches()){
254
			makeEmpty = false;
255
			parseFullName(nameToBeFilled, fullReferenceString, rank, makeEmpty);	//simpleName not yet implemented
256
		}else{
257
			makeNoFullRefMatch(nameToBeFilled, fullReferenceString, rank);
258
		}
259
		//problem handling. Start and end solved in subroutines
260
		if (! nameToBeFilled.hasProblem()){
261
			makeProblemEmpty(nameToBeFilled);
262
		}
263
	}
264

    
265
	private void makeProblemEmpty(IParsable parsable){
266
		boolean hasCheckRank = parsable.hasProblem(ParserProblem.CheckRank);
267
		parsable.setParsingProblem(0);
268
		if (hasCheckRank){
269
			parsable.addParsingProblem(ParserProblem.CheckRank);
270
		}
271
		parsable.setProblemStarts(-1);
272
		parsable.setProblemEnds(-1);
273
	}
274

    
275
	private void makeNoFullRefMatch(NonViralName<?> nameToBeFilled, String fullReferenceString, Rank rank){
276
	    //try to parse first part as name, but keep in mind full string is not parsable
277
		int start = 0;
278

    
279
		String localFullName = getCodeSpecificFullNameRegEx(nameToBeFilled);
280
		Matcher fullNameMatcher = getMatcher (pStart + localFullName, fullReferenceString);
281
		if (fullNameMatcher.find()){
282
			String fullNameString = fullNameMatcher.group(0);
283
			nameToBeFilled.setProtectedNameCache(false);
284
			parseFullName(nameToBeFilled, fullNameString, rank, false);
285
			String sure = nameToBeFilled.getNameCache();
286
			start = sure.length();
287
		}
288

    
289
//		String localSimpleName = getLocalSimpleName(nameToBeFilled);
290
//		Matcher simpleNameMatcher = getMatcher (start + localSimpleName, fullReferenceString);
291
//		if (simpleNameMatcher.find()){
292
//			String simpleNameString = simpleNameMatcher.group(0);
293
//			parseFullName(nameToBeFilled, simpleNameString, rank, false);
294
//			start = simpleNameString.length();
295
//		}
296

    
297
		//don't parse if name can't be separated
298
		nameToBeFilled.addParsingProblem(ParserProblem.NameReferenceSeparation);
299
		nameToBeFilled.setTitleCache(fullReferenceString,true);
300
		nameToBeFilled.setFullTitleCache(fullReferenceString,true);
301
		// FIXME Quick fix, otherwise search would not deliver results for unparsable names
302
		nameToBeFilled.setNameCache(fullReferenceString,true);
303
		// END
304
		nameToBeFilled.setProblemStarts(start);
305
		nameToBeFilled.setProblemEnds(fullReferenceString.length());
306
		logger.info("no applicable parsing rule could be found for \"" + fullReferenceString + "\"");
307
	}
308

    
309
	private void makeNameWithReference(NonViralName<?> nameToBeFilled,
310
			String fullReferenceString,
311
			Matcher nameAndRefSeparatorMatcher,
312
			Rank rank,
313
			boolean makeEmpty){
314

    
315
		String nameAndSeparator = nameAndRefSeparatorMatcher.group(0);
316
	    String name = nameAndRefSeparatorMatcher.group(1);
317
	    String referenceString = fullReferenceString.substring(nameAndRefSeparatorMatcher.end());
318

    
319
	    // is reference an in ref?
320
	    String separator = nameAndSeparator.substring(name.length());
321
		boolean isInReference = separator.matches(inReferenceSeparator);
322

    
323
	    //parse subparts
324

    
325
		int oldProblemEnds = nameToBeFilled.getProblemEnds();
326
		parseFullName(nameToBeFilled, name, rank, makeEmpty);
327
	    nameToBeFilled.setProblemEnds(oldProblemEnds);
328

    
329
		//zoological new combinations should not have a nom. reference to be parsed
330
	    if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
331
			ZoologicalName zooName = CdmBase.deproxy(nameToBeFilled, ZoologicalName.class);
332
			//is name new combination?
333
			if (zooName.getBasionymAuthorship() != null || zooName.getOriginalPublicationYear() != null){
334
				ParserProblem parserProblem = ParserProblem.NewCombinationHasPublication;
335
				zooName.addParsingProblem(parserProblem);
336
				nameToBeFilled.setProblemStarts((nameToBeFilled.getProblemStarts()> -1) ? nameToBeFilled.getProblemStarts(): name.length());
337
				nameToBeFilled.setProblemEnds(Math.max(fullReferenceString.length(), nameToBeFilled.getProblemEnds()));
338
			}
339
		}
340

    
341
	    parseReference(nameToBeFilled, referenceString, isInReference);
342
	    INomenclaturalReference ref = nameToBeFilled.getNomenclaturalReference();
343

    
344
	    //problem start
345
	    int start = nameToBeFilled.getProblemStarts();
346
	    int nameLength = name.length();
347
	    int nameAndSeparatorLength = nameAndSeparator.length();
348
	    int fullRefLength = nameToBeFilled.getFullTitleCache().length();
349

    
350
	    if (nameToBeFilled.isProtectedTitleCache() || nameToBeFilled.getParsingProblems().contains(ParserProblem.CheckRank)){
351
	    	start = Math.max(0, start);
352
		}else{
353
			if (ref != null && ref.getParsingProblem()!=0){
354
				start = Math.max(nameAndSeparatorLength, start);
355
		    	//TODO search within ref
356
			}
357
		}
358

    
359
	    //end
360
	    int end = nameToBeFilled.getProblemEnds();
361

    
362
	    if (ref != null && ref.getParsingProblem()!=0){
363
	    	end = Math.min(nameAndSeparatorLength + ref.getProblemEnds(), end);
364
	    }else{
365
	    	if (nameToBeFilled.isProtectedTitleCache() ){
366
	    		end = Math.min(end, nameAndSeparatorLength);
367
	    		//TODO search within name
368
			}
369
	    }
370
	    nameToBeFilled.setProblemStarts(start);
371
	    nameToBeFilled.setProblemEnds(end);
372

    
373
	    //delegate has problem to name
374
	    if (ref != null && ref.getParsingProblem()!=0){
375
	    	nameToBeFilled.addParsingProblems(ref.getParsingProblem());
376
	    }
377

    
378
	    Reference<?> nomRef;
379
		if ( (nomRef = (Reference<?>)nameToBeFilled.getNomenclaturalReference()) != null ){
380
			nomRef.setAuthorship(nameToBeFilled.getCombinationAuthorship());
381
		}
382
	}
383

    
384
	//TODO make it an Array of status
385
	/**
386
	 * Extracts a {@link NomenclaturalStatus} from the reference String and adds it to the @link {@link TaxonNameBase}.
387
	 * The nomenclatural status part ist deleted from the reference String.
388
	 * @return  String the new (shortend) reference String
389
	 */
390
	public String parseNomStatus(String fullString, NonViralName<?> nameToBeFilled, boolean makeEmpty) {
391
		Set<NomenclaturalStatusType> existingStatusTypeSet = new HashSet<NomenclaturalStatusType>();
392
		Set<NomenclaturalStatusType> newStatusTypeSet = new HashSet<NomenclaturalStatusType>();
393
		for (NomenclaturalStatus existingStatus : nameToBeFilled.getStatus()){
394
			existingStatusTypeSet.add(existingStatus.getType());
395
		}
396

    
397
		String statusString;
398
		Pattern hasStatusPattern = Pattern.compile("(" + pNomStatusPhrase + ")");
399
		Matcher hasStatusMatcher = hasStatusPattern.matcher(fullString);
400

    
401
		if (hasStatusMatcher.find()) {
402
			String statusPhrase = hasStatusMatcher.group(0);
403

    
404
			Pattern statusPattern = Pattern.compile(pNomStatus);
405
			Matcher statusMatcher = statusPattern.matcher(statusPhrase);
406
			statusMatcher.find();
407
			statusString = statusMatcher.group(0);
408
			try {
409
				NomenclaturalStatusType nomStatusType = NomenclaturalStatusType.getNomenclaturalStatusTypeByAbbreviation(statusString, nameToBeFilled);
410
				if (! existingStatusTypeSet.contains(nomStatusType)){
411
					NomenclaturalStatus nomStatus = NomenclaturalStatus.NewInstance(nomStatusType);
412
					nameToBeFilled.addStatus(nomStatus);
413
				}
414
				newStatusTypeSet.add(nomStatusType);
415
				fullString = fullString.replace(statusPhrase, "");
416
			} catch (UnknownCdmTypeException e) {
417
				//Do nothing
418
			}
419
		}
420
		//remove not existing nom status
421
		if (makeEmpty){
422
			Set<NomenclaturalStatus> tmpStatus = new HashSet<NomenclaturalStatus>();
423
			tmpStatus.addAll(nameToBeFilled.getStatus());
424
			for (NomenclaturalStatus status : tmpStatus){
425
				if (! newStatusTypeSet.contains(status.getType())){
426
					nameToBeFilled.removeStatus(status);
427
				}
428
			}
429
		}
430

    
431
		return fullString;
432
	}
433

    
434

    
435
	private void parseReference(NonViralName<?> nameToBeFilled, String strReference, boolean isInReference){
436

    
437
		INomenclaturalReference ref;
438
		String originalStrReference = strReference;
439

    
440
		//End (just delete end (e.g. '.', may be ambigous for yearPhrase, but no real information gets lost
441
		Matcher endMatcher = getMatcher(referenceEnd + end, strReference);
442
		if (endMatcher.find()){
443
			String endPart = endMatcher.group(0);
444
			strReference = strReference.substring(0, strReference.length() - endPart.length());
445
		}
446

    
447
//		String pDetailYear = ".*" + detailSeparator + detail + fWs + yearSeperator + fWs + yearPhrase + fWs + end;
448
//		Matcher detailYearMatcher = getMatcher(pDetailYear, strReference);
449

    
450
		String strReferenceWithYear = strReference;
451
		//year
452
		String yearPart = null;
453
		String pYearPhrase = yearSeperator + fWs + yearPhrase + fWs + end;
454
		Matcher yearPhraseMatcher = getMatcher(pYearPhrase, strReference);
455
		if (yearPhraseMatcher.find()){
456
			yearPart = yearPhraseMatcher.group(0);
457
			strReference = strReference.substring(0, strReference.length() - yearPart.length());
458
			yearPart = yearPart.replaceFirst(pStart + yearSeperator, "").trim();
459
		}else{
460
			if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
461
				ZoologicalName zooName = CdmBase.deproxy(nameToBeFilled, ZoologicalName.class);
462
				yearPart = String.valueOf(zooName.getPublicationYear());
463
				//continue
464
			}else{
465
				ref = makeDetailYearUnparsable(nameToBeFilled,strReference);
466
				ref.setDatePublished(TimePeriodParser.parseString(yearPart));
467
				return;
468
			}
469
		}
470

    
471

    
472
		//detail
473
		String pDetailPhrase = detailSeparator + fWs + detail + fWs + end;
474
		Matcher detailPhraseMatcher = getMatcher(pDetailPhrase, strReference);
475
		if (detailPhraseMatcher.find()){
476
			String detailPart = detailPhraseMatcher.group(0);
477
			strReference = strReference.substring(0, strReference.length() - detailPart.length());
478
			detailPart = detailPart.replaceFirst(pStart + detailSeparator, "").trim();
479
			nameToBeFilled.setNomenclaturalMicroReference(detailPart);
480
		}else{
481
			makeDetailYearUnparsable(nameToBeFilled, strReferenceWithYear);
482
			return;
483
		}
484
		//parse title and author
485
		ref = parseReferenceTitle(strReference, yearPart, isInReference);
486
		if (ref.hasProblem()){
487
			ref.setTitleCache( (isInReference ? "in ":"") +  originalStrReference, true);
488
			ref.setAbbrevTitleCache( (isInReference ? "in ":"") +  originalStrReference, true);
489
		}
490
		nameToBeFilled.setNomenclaturalReference(ref);
491
		int end = Math.min(strReference.length(), ref.getProblemEnds());
492
		ref.setProblemEnds(end);
493
	}
494

    
495
	/**
496
	 * @param nameToBeFilled
497
	 * @param strReference
498
	 * @return
499
	 */
500
	private INomenclaturalReference makeDetailYearUnparsable(NonViralName<?> nameToBeFilled, String strReference) {
501
		INomenclaturalReference ref;
502
		//ref = Generic.NewInstance();
503

    
504
		ref = ReferenceFactory.newGeneric();
505
		ref.setTitleCache(strReference,true);
506
		ref.setProblemEnds(strReference.length());
507
		ref.addParsingProblem(ParserProblem.CheckDetailOrYear);
508
		nameToBeFilled.addParsingProblem(ParserProblem.CheckDetailOrYear);
509
		nameToBeFilled.setNomenclaturalReference(ref);
510
		return ref;
511
	}
512

    
513
	/**
514
	 * Parses the referenceTitlePart, including the author volume and edition.
515
	 * @param reference
516
	 * @param year
517
	 * @return
518
	 */
519
	private INomenclaturalReference parseReferenceTitle(String strReference, String year, boolean isInReference){
520
		IBook result = null;
521

    
522
		Matcher refSineDetailMatcher = referenceSineDetailPattern.matcher(strReference);
523
		if (! refSineDetailMatcher.matches()){
524
			//TODO ?
525
		}
526

    
527
		Matcher articleMatcher = getMatcher(pArticleReference, strReference);
528
		Matcher bookMatcher = getMatcher(pBookReference, strReference);
529

    
530
		Matcher softArticleMatcher = getMatcher(pSoftArticleReference, strReference);
531
		Matcher bookSectionMatcher = getMatcher(pBookSectionReference, strReference);
532

    
533

    
534
		if(isInReference == false){
535
			if (bookMatcher.matches() ){
536
				result = parseBook(strReference);
537
			}else{
538
				logger.warn("Non-InRef must be book but does not match book");
539
				result = ReferenceFactory.newBook();
540
				makeUnparsableRefTitle(result, strReference);
541
			}
542
		}else{  //inRef
543
			if (articleMatcher.matches()){
544
				//article without separators like ","
545
				result = parseArticle(strReference);
546
			}else if (softArticleMatcher.matches()){
547
				result = parseArticle(strReference);
548
			}else if (bookSectionMatcher.matches()){
549
				result = parseBookSection(strReference);
550
			}else{
551
				result =  ReferenceFactory.newGeneric();
552
				makeUnparsableRefTitle(result, "in " + strReference);
553
			}
554
		}
555
		//make year
556
		if (makeYear(result, year) == false){
557
			//TODO
558
			logger.warn("Year could not be parsed");
559
		}
560
		result.setProblemStarts(0);
561
		result.setProblemEnds(strReference.length());
562
		return result;
563
	}
564

    
565
	private void makeUnparsableRefTitle(INomenclaturalReference result, String reference){
566
		result.setTitleCache(reference,true);
567
		result.setAbbrevTitleCache(reference,true);
568
		result.addParsingProblem(ParserProblem.UnparsableReferenceTitle);
569
	}
570

    
571
	/**
572
	 * Parses a single date string. If the string is not parsable a StringNotParsableException is thrown
573
	 * @param singleDateString
574
	 * @return
575
	 * @throws StringNotParsableException
576
	 */
577
	private static Partial parseSingleDate(String singleDateString)
578
			throws StringNotParsableException{
579
		Partial dt = new Partial();
580
		if (CdmUtils.isNumeric(singleDateString)){
581
			try {
582
				Integer year = Integer.valueOf(singleDateString.trim());
583
				if (year > 1750 && year < 2050){
584
					dt = dt.with(DateTimeFieldType.year(), year);
585
				}else{
586
					dt = null;
587
				}
588
			} catch (NumberFormatException e) {
589
				logger.debug("Not a Integer format in getCalendar()");
590
				throw new StringNotParsableException(singleDateString + "is not parsable as a single Date");
591
			}
592
		}
593
		return dt;
594
	}
595

    
596

    
597
	/**
598
	 * Parses the publication date part.
599
	 * @param nomRef
600
	 * @param year
601
	 * @return If the string is not parsable <code>false</code>
602
	 * is returned. <code>True</code> otherwise
603
	 */
604
	private boolean makeYear(INomenclaturalReference nomRef, String year){
605
		boolean result = true;
606
		if (year == null){
607
			return false;
608
		}
609
		if ("".equals(year.trim())){
610
			return true;
611
		}
612
		TimePeriod datePublished = TimePeriodParser.parseString(year);
613

    
614
		if (nomRef.getType().equals(ReferenceType.BookSection)){
615
			handleBookSectionYear((IBookSection)nomRef, datePublished);
616
		}else if (nomRef instanceof Reference){
617
			((Reference)nomRef).setDatePublished(datePublished);
618
		}else{
619
			throw new ClassCastException("nom Ref is not of type Reference but " + (nomRef == null? "(null)" : nomRef.getClass()));
620
		}
621
		return result;
622
	}
623

    
624
	private String makeVolume(IVolumeReference nomRef, String strReference){
625
		//volume
626
		String volPart = null;
627
		String pVolPhrase = volumeSeparator +  volume + end;
628
		Matcher volPhraseMatcher = getMatcher(pVolPhrase, strReference);
629
		if (volPhraseMatcher.find()){
630
			volPart = volPhraseMatcher.group(0);
631
			strReference = strReference.substring(0, strReference.length() - volPart.length());
632
			volPart = volPart.replaceFirst(pStart + volumeSeparator, "").trim();
633
			nomRef.setVolume(volPart);
634
		}
635
		return strReference;
636
	}
637

    
638
	private String makeEdition(IBook book, String strReference){
639
		//volume
640
		String editionPart = null;
641
		Matcher editionPhraseMatcher = getMatcher(pEditionPart, strReference);
642

    
643
		Matcher editionVolumeMatcher = getMatcher(pEditionVolPart, strReference);
644
		boolean isEditionAndVol = editionVolumeMatcher.find();
645

    
646
		if (editionPhraseMatcher.find()){
647
			editionPart = editionPhraseMatcher.group(0);
648
			int pos = strReference.indexOf(editionPart);
649
			int posEnd = pos + editionPart.length();
650
			if (isEditionAndVol){
651
				posEnd++;  //delete also comma
652
			}
653
			strReference = strReference.substring(0, pos) + strReference.substring(posEnd);
654
			editionPart = editionPart.replaceFirst(pStart + editionSeparator, "").trim();
655
			book.setEdition(editionPart);
656
		}
657
		return strReference;
658
	}
659

    
660
	private IBook parseBook(String reference){
661
		IBook result = ReferenceFactory.newBook();
662
		reference = makeEdition(result, reference);
663
		reference = makeVolume(result, reference);
664
		result.setTitle(reference);
665
		return result;
666
	}
667

    
668

    
669
	private Reference<?> parseArticle(String reference){
670
		//if (articlePatter)
671
		//(type, author, title, volume, editor, series;
672
		Reference<?> result = ReferenceFactory.newArticle();
673
		reference = makeVolume(result, reference);
674
		Reference<?> inJournal = ReferenceFactory.newJournal();
675
		inJournal.setTitle(reference);
676
		result.setInReference(inJournal);
677
		return result;
678
	}
679

    
680
	private Reference<?> parseBookSection(String reference){
681
		Reference<?> result = ReferenceFactory.newBookSection();
682

    
683
		Pattern authorPattern = Pattern.compile("^" + authorTeam + referenceAuthorSeparator);
684
		Matcher authorMatcher = authorPattern.matcher(reference);
685
		boolean find = authorMatcher.find();
686
		if (find){
687
			String authorString = authorMatcher.group(0).trim();
688
			String bookString = reference.substring(authorString.length()).trim();
689
			authorString = authorString.substring(0, authorString.length() -1);
690

    
691
			TeamOrPersonBase<?> authorTeam = author(authorString);
692
			IBook inBook = parseBook(bookString);
693
			inBook.setAuthorship(authorTeam);
694
			result.setInBook(inBook);
695
		}else{
696
			logger.warn("Unexpected non matching book section author part");
697
			//TODO do we want to record a 'problem' here?
698
			result.setTitleCache(reference,true);
699
		}
700

    
701
		return result;
702
	}
703

    
704
	/**
705
	 * If the publication date of a book section and it's inBook do differ this is usually
706
	 * caused by the fact that a book has been published during a period, because originally
707
	 * it consisted of several parts that only later where put together to one book.
708
	 * If so, the book section's publication date may be a point in time (year or month of year)
709
	 * whereas the books publication date may be a period of several years.
710
	 * Therefore a valid nomenclatural reference string should use the book sections
711
	 * publication date rather then the book's publication date.<BR>
712
	 * This method in general adds the publication date to the book section.
713
	 * An exception exists if the publication date is a period. Then the parser
714
	 * assumes that the nomenclatural reference string does not follow the above rule but
715
	 * the books publication date is set.
716
	 * @param bookSection
717
	 * @param datePublished
718
	 */
719
	private void handleBookSectionYear(IBookSection bookSection, TimePeriod datePublished){
720
		if (datePublished == null || datePublished.getStart() == null || bookSection == null){
721
			return;
722
		}
723
		if (datePublished.isPeriod() && bookSection.getInBook() != null){
724
			bookSection.getInBook().setDatePublished(datePublished);
725
		}else{
726
			bookSection.setDatePublished(datePublished);
727
		}
728
	}
729

    
730
	@Override
731
    public NonViralName parseFullName(String fullNameString){
732
		return parseFullName(fullNameString, null, null);
733
	}
734

    
735
	@Override
736
    public NonViralName parseFullName(String fullNameString, NomenclaturalCode nomCode, Rank rank) {
737

    
738
		if (fullNameString == null){
739
			return null;
740
		}else{
741
			NonViralName<?> result = getNonViralNameInstance(fullNameString, nomCode, rank);
742
			parseFullName(result, fullNameString, rank, false);
743
			return result;
744
		}
745
	}
746

    
747
	@Override
748
	public void parseFullName(NonViralName nameToBeFilledOrig, String fullNameStringOrig, Rank rank, boolean makeEmpty) {
749
	    NonViralName<?> nameToBeFilled = nameToBeFilledOrig;
750

    
751
	    //TODO prol. etc.
752
		boolean hasCheckRankProblem = false; //was rank guessed in a previous parsing process?
753
		if (nameToBeFilled == null){
754
			throw new IllegalArgumentException("NameToBeFilled must not be null in name parser");
755
		}else{
756
			hasCheckRankProblem = nameToBeFilled.hasProblem(ParserProblem.CheckRank);
757
			nameToBeFilled.removeParsingProblem(ParserProblem.CheckRank);
758
		}
759
		String authorString = null;
760
		if (fullNameStringOrig == null){
761
			return;
762
		}
763
		if (makeEmpty){
764
			makeEmpty(nameToBeFilled);
765
		}
766

    
767
		String fullNameString = fullNameStringOrig.replaceAll(oWs , " ").trim();
768

    
769
		fullNameString = removeHybridBlanks(fullNameString);
770
		String[] epi = pattern.split(fullNameString);
771
		try {
772
	    	//cultivars //TODO 2 implement cultivars
773
//		    if ( cultivarMarkerRE.match(fullName) ){ funktioniert noch nicht, da es z.B. auch Namen gibt, wie 't Hart
774
//		    	result = parseCultivar(fullName);
775
//		    }
776

    
777
		    if (genusOrSupraGenusPattern.matcher(fullNameString).matches()){
778
		    	//supraGeneric
779
				if (rank != null && ! hasCheckRankProblem  && (rank.isSupraGeneric()|| rank.isGenus())){
780
					nameToBeFilled.setRank(rank);
781
					nameToBeFilled.setGenusOrUninomial(epi[0]);
782
				}
783
				//genus or guess rank
784
				else {
785
					rank = guessUninomialRank(nameToBeFilled, epi[0]);
786
					nameToBeFilled.setRank(rank);
787
					nameToBeFilled.setGenusOrUninomial(epi[0]);
788
					nameToBeFilled.addParsingProblem(ParserProblem.CheckRank);
789
					nameToBeFilled.setProblemStarts(0);
790
					nameToBeFilled.setProblemEnds(epi[0].length());
791
				}
792
				authorString = fullNameString.substring(epi[0].length());
793
			}
794
			 //infra genus
795
			 else if (infraGenusPattern.matcher(fullNameString).matches()){
796
				Rank infraGenericRank;
797
				if ("[unranked]".equals(epi[1])){
798
					infraGenericRank = Rank.INFRAGENERICTAXON();
799
				}else{
800
				    String infraGenericRankMarker = epi[1];
801
				    if (infraGenericRankMarker.startsWith(notho)){  //#3868
802
                        nameToBeFilled.setBinomHybrid(true);
803
                        infraGenericRankMarker = infraGenericRankMarker.substring(notho.length());
804
                    }else if(infraGenericRankMarker.startsWith("n")){
805
                        nameToBeFilled.setBinomHybrid(true);
806
                        infraGenericRankMarker = infraGenericRankMarker.substring(1);
807
                    }
808
                    infraGenericRank = Rank.getRankByIdInVoc(infraGenericRankMarker, nameToBeFilledOrig.getNomenclaturalCode());
809
				}
810
				nameToBeFilled.setRank(infraGenericRank);
811
				nameToBeFilled.setGenusOrUninomial(epi[0]);
812
				nameToBeFilled.setInfraGenericEpithet(epi[2]);
813
				authorString = fullNameString.substring(epi[0].length() + 1 + epi[1].length()+ 1 + epi[2].length());
814
			}
815
			 //aggr. or group
816
			 else if (aggrOrGroupPattern.matcher(fullNameString).matches()){
817
				nameToBeFilled.setRank(Rank.getRankByIdInVoc(epi[2]));
818
				nameToBeFilled.setGenusOrUninomial(epi[0]);
819
				nameToBeFilled.setSpecificEpithet(epi[1]);
820
			}
821
			 //species
822
			 else if (speciesPattern.matcher(fullNameString).matches()){
823
				nameToBeFilled.setRank(Rank.SPECIES());
824
				nameToBeFilled.setGenusOrUninomial(epi[0]);
825
				nameToBeFilled.setSpecificEpithet(epi[1]);
826
				authorString = fullNameString.substring(epi[0].length() + 1 + epi[1].length());
827
			}
828
			 //autonym
829
			 else if (autonymPattern.matcher(fullNameString).matches()){
830
				nameToBeFilled.setRank(Rank.getRankByIdInVoc(epi[epi.length - 2]));
831
				nameToBeFilled.setGenusOrUninomial(epi[0]);
832
				nameToBeFilled.setSpecificEpithet(epi[1]);
833
				nameToBeFilled.setInfraSpecificEpithet(epi[epi.length - 1]);
834
				int lenSpecies = 2 + epi[0].length()+epi[1].length();
835
				int lenInfraSpecies =  2 + epi[epi.length - 2].length() + epi[epi.length - 1].length();
836
				authorString = fullNameString.substring(lenSpecies, fullNameString.length() - lenInfraSpecies);
837
			}
838
			 //infraSpecies
839
			 else if (infraSpeciesPattern.matcher(fullNameString).matches()){
840
				String infraSpecRankMarker = epi[2];
841
				String infraSpecEpi = epi[3];
842
				if ("tax.".equals(infraSpecRankMarker)){
843
					infraSpecRankMarker += " " +  epi[3];
844
					infraSpecEpi = epi[4];
845
				}
846
				Rank infraSpecificRank;
847
				if ("[unranked]".equals(infraSpecRankMarker)){
848
					infraSpecificRank = Rank.INFRASPECIFICTAXON();
849
				}else{
850
					String localInfraSpecRankMarker;
851
					if (infraSpecRankMarker.startsWith(notho)){  //#3868
852
	                    nameToBeFilled.setTrinomHybrid(true);
853
	                    localInfraSpecRankMarker = infraSpecRankMarker.substring(notho.length());
854
					}else if(infraSpecRankMarker.startsWith("n")){
855
	                    nameToBeFilled.setTrinomHybrid(true);
856
	                    localInfraSpecRankMarker = infraSpecRankMarker.substring(1);
857
                    }else{
858
                        localInfraSpecRankMarker = infraSpecRankMarker;
859
                    }
860
				    infraSpecificRank = Rank.getRankByIdInVoc(localInfraSpecRankMarker);
861
				}
862
				nameToBeFilled.setRank(infraSpecificRank);
863
				nameToBeFilled.setGenusOrUninomial(epi[0]);
864
				nameToBeFilled.setSpecificEpithet(epi[1]);
865
				nameToBeFilled.setInfraSpecificEpithet(infraSpecEpi);
866
				authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + infraSpecRankMarker.length() + 1 + infraSpecEpi.length());
867

    
868
			 }
869
		      //infraSpecies without marker
870
			 else if (zooInfraSpeciesPattern.matcher(fullNameString).matches()){
871
					String infraSpecEpi = epi[2];
872
					Rank infraSpecificRank = Rank.SUBSPECIES();
873
					nameToBeFilled.setRank(infraSpecificRank);
874
					nameToBeFilled.setGenusOrUninomial(epi[0]);
875
					nameToBeFilled.setSpecificEpithet(epi[1]);
876
					nameToBeFilled.setInfraSpecificEpithet(infraSpecEpi);
877
					authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + infraSpecEpi.length());
878

    
879
			 }//old infraSpecies
880
			 else if (oldInfraSpeciesPattern.matcher(fullNameString).matches()){
881
				boolean implemented = false;
882
				if (implemented){
883
					nameToBeFilled.setRank(Rank.getRankByNameOrIdInVoc(epi[2]));
884
					nameToBeFilled.setGenusOrUninomial(epi[0]);
885
					nameToBeFilled.setSpecificEpithet(epi[1]);
886
					//TODO result.setUnnamedNamePhrase(epi[2] + " " + epi[3]);
887
					authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + epi[2].length() + 1 + epi[3].length());
888
				}else{
889
					nameToBeFilled.addParsingProblem(ParserProblem.OldInfraSpeciesNotSupported);
890
					nameToBeFilled.setTitleCache(fullNameString,true);
891
					// FIXME Quick fix, otherwise search would not deilver results for unparsable names
892
					nameToBeFilled.setNameCache(fullNameString,true);
893
					// END
894
					logger.info("Name string " + fullNameString + " could not be parsed because UnnnamedNamePhrase is not yet implemented!");
895
				}
896
			}
897
		     //hybrid formula
898
			 else if (hybridFormulaPattern.matcher(fullNameString).matches()){
899
				 Set<HybridRelationship> existingRelations = new HashSet<HybridRelationship>();
900
				 Set<HybridRelationship> notToBeDeleted = new HashSet<HybridRelationship>();
901

    
902
				 for ( HybridRelationship rel : nameToBeFilled.getHybridChildRelations()){
903
				     existingRelations.add(rel);
904
				 }
905

    
906
			     String firstNameString = "";
907
				 String secondNameString = "";
908
				 boolean isFirstName = true;
909
				 for (String str : epi){
910
					 if (str.matches(hybridSign)){
911
						 isFirstName = false;
912
					 }else if(isFirstName){
913
						 firstNameString += " " + str;
914
					 }else {
915
						 secondNameString += " " + str;
916
					 }
917
				 }
918
				 nameToBeFilled.setHybridFormula(true);
919
				 NomenclaturalCode code = nameToBeFilled.getNomenclaturalCode();
920
				 NonViralName<?> firstName = this.parseFullName(firstNameString.trim(), code, rank);
921
				 NonViralName<?> secondName = this.parseFullName(secondNameString.trim(), code, rank);
922
				 HybridRelationship firstRel = nameToBeFilled.addHybridParent(firstName, HybridRelationshipType.FIRST_PARENT(), null);
923
				 HybridRelationship second = nameToBeFilled.addHybridParent(secondName, HybridRelationshipType.SECOND_PARENT(), null);
924
				 checkRelationExist(firstRel, existingRelations, notToBeDeleted);
925
				 checkRelationExist(second, existingRelations, notToBeDeleted);
926

    
927
				 Rank newRank;
928
				 Rank firstRank = firstName.getRank();
929
				 Rank secondRank = secondName.getRank();
930

    
931
				 if (firstRank == null || firstRank.isHigher(secondRank)){
932
					 newRank = secondRank;
933
				 }else{
934
					 newRank = firstRank;
935
				 }
936
				 nameToBeFilled.setRank(newRank);
937
				 //remove not existing hybrid relation
938
				 if (makeEmpty){
939
		            Set<HybridRelationship> tmpChildRels = new HashSet<HybridRelationship>();
940
		            tmpChildRels.addAll(nameToBeFilled.getHybridChildRelations());
941
		            for (HybridRelationship rel : tmpChildRels){
942
		                if (! notToBeDeleted.contains(rel)){
943
		                    nameToBeFilled.removeHybridRelationship(rel);
944
		                }
945
		            }
946
				 }
947
			 }
948
		    //none
949
			else{
950
				nameToBeFilled.addParsingProblem(ParserProblem.UnparsableNamePart);
951
				nameToBeFilled.setTitleCache(fullNameString,true);
952
				// FIXME Quick fix, otherwise search would not deilver results for unparsable names
953
				nameToBeFilled.setNameCache(fullNameString, true);
954
				// END
955
				logger.info("no applicable parsing rule could be found for \"" + fullNameString + "\"");
956
		    }
957
		    //hybrid bits
958
		    handleHybridBits(nameToBeFilled);
959
		    if (!nameToBeFilled.isHybridFormula()){
960
		        Set<HybridRelationship> hybridChildRelations = new HashSet<HybridRelationship>();
961
		        hybridChildRelations.addAll(nameToBeFilled.getHybridChildRelations());
962

    
963
		        for (HybridRelationship hybridRelationship: hybridChildRelations){
964
		        	nameToBeFilled.removeHybridRelationship(hybridRelationship);
965
		        }
966
		    }
967

    
968
			//authors
969
		    if (StringUtils.isNotBlank(authorString) ){
970
				handleAuthors(nameToBeFilled, fullNameString, authorString);
971
			}
972
		    return;
973
		} catch (UnknownCdmTypeException e) {
974
			nameToBeFilled.addParsingProblem(ParserProblem.RankNotSupported);
975
			nameToBeFilled.setTitleCache(fullNameString,true);
976
			// FIXME Quick fix, otherwise search would not deilver results for unparsable names
977
			nameToBeFilled.setNameCache(fullNameString,true);
978
			// END
979
			logger.info("unknown rank (" + (rank == null? "null":rank) + ") or abbreviation in string " +  fullNameString);
980
			//return result;
981
			return;
982
		}
983
	}
984

    
985
	/**
986
     * Checks if a hybrid relation exists in the Set of existing relations
987
     * and <BR>
988
     *  if it does not adds it to relations not to be deleted <BR>
989
     *  if it does adds the existing relations to the relations not to be deleted
990
     *
991
     * @param firstRel
992
     * @param existingRelations
993
     * @param notToBeDeleted
994
     */
995
    private void checkRelationExist(
996
            HybridRelationship newRelation,
997
            Set<HybridRelationship> existingRelations,
998
            Set<HybridRelationship> notToBeDeleted) {
999
        HybridRelationship relToKeep = newRelation;
1000
        for (HybridRelationship existingRelation : existingRelations){
1001
            if (existingRelation.equals(newRelation)){
1002
                relToKeep = existingRelation;
1003
                break;
1004
            }
1005
        }
1006
        notToBeDeleted.add(relToKeep);
1007
    }
1008

    
1009
    private void handleHybridBits(NonViralName<?> nameToBeFilled) {
1010
		//uninomial
1011
		String uninomial = CdmUtils.Nz(nameToBeFilled.getGenusOrUninomial());
1012
		boolean isUninomialHybrid = uninomial.startsWith(hybridSign);
1013
		if (isUninomialHybrid){
1014
			nameToBeFilled.setMonomHybrid(true);
1015
			nameToBeFilled.setGenusOrUninomial(uninomial.replace(hybridSign, ""));
1016
		}
1017
		//infrageneric
1018
		String infrageneric = CdmUtils.Nz(nameToBeFilled.getInfraGenericEpithet());
1019
		boolean isInfraGenericHybrid = infrageneric.startsWith(hybridSign);
1020
		if (isInfraGenericHybrid){
1021
			nameToBeFilled.setBinomHybrid(true);
1022
			nameToBeFilled.setInfraGenericEpithet(infrageneric.replace(hybridSign, ""));
1023
		}
1024
		//species Epi
1025
		String speciesEpi = CdmUtils.Nz(nameToBeFilled.getSpecificEpithet());
1026
		boolean isSpeciesHybrid = speciesEpi.startsWith(hybridSign);
1027
		if (isSpeciesHybrid){
1028
			if (StringUtils.isBlank(infrageneric)){
1029
				nameToBeFilled.setBinomHybrid(true);
1030
			}else{
1031
				nameToBeFilled.setTrinomHybrid(true);
1032
			}
1033
			nameToBeFilled.setSpecificEpithet(speciesEpi.replace(hybridSign, ""));
1034
		}
1035
		//infra species
1036
		String infraSpeciesEpi = CdmUtils.Nz(nameToBeFilled.getInfraSpecificEpithet());
1037
		boolean isInfraSpeciesHybrid = infraSpeciesEpi.startsWith(hybridSign);
1038
		if (isInfraSpeciesHybrid){
1039
			nameToBeFilled.setTrinomHybrid(true);
1040
			nameToBeFilled.setInfraSpecificEpithet(infraSpeciesEpi.replace(hybridSign, ""));
1041
		}
1042

    
1043
	}
1044

    
1045
	private String removeHybridBlanks(String fullNameString) {
1046
		String result = fullNameString
1047
		        .replaceAll(oWs + "[xX]" + oWs + "(?=[A-Z])", " " + hybridSign + " ")
1048
		        .replaceAll(hybridFull, " "+hybridSign).trim();
1049
		return result;
1050
	}
1051

    
1052
	/**
1053
	 * Author parser for external use
1054
	 * @param nonViralName
1055
	 * @param authorString
1056
	 * @throws StringNotParsableException
1057
	 */
1058
	@Override
1059
	public void parseAuthors(NonViralName nonViralNameOrig, String authorString) throws StringNotParsableException{
1060
	    NonViralName<?> nonViralName = nonViralNameOrig;
1061
	    TeamOrPersonBase<?>[] authors = new TeamOrPersonBase[4];
1062
		Integer[] years = new Integer[4];
1063
		Class<? extends NonViralName> clazz = nonViralName.getClass();
1064
		fullAuthors(authorString, authors, years, clazz);
1065
		nonViralName.setCombinationAuthorship(authors[0]);
1066
		nonViralName.setExCombinationAuthorship(authors[1]);
1067
		nonViralName.setBasionymAuthorship(authors[2]);
1068
		nonViralName.setExBasionymAuthorship(authors[3]);
1069
		if (nonViralName instanceof ZoologicalName){
1070
			ZoologicalName zooName = CdmBase.deproxy(nonViralName, ZoologicalName.class);
1071
			zooName.setPublicationYear(years[0]);
1072
			zooName.setOriginalPublicationYear(years[2]);
1073
		}
1074
	}
1075

    
1076
	/**
1077
	 * @param nameToBeFilled
1078
	 * @param fullNameString
1079
	 * @param authorString
1080
	 */
1081
	public void handleAuthors(NonViralName nameToBeFilledOrig, String fullNameString, String authorString) {
1082
	    NonViralName<?> nameToBeFilled = nameToBeFilledOrig;
1083
        TeamOrPersonBase<?>[] authors = new TeamOrPersonBase[4];
1084
		Integer[] years = new Integer[4];
1085
		try {
1086
			Class<? extends NonViralName> clazz = nameToBeFilled.getClass();
1087
			fullAuthors(authorString, authors, years, clazz);
1088
		} catch (StringNotParsableException e) {
1089
			nameToBeFilled.addParsingProblem(ParserProblem.UnparsableAuthorPart);
1090
			nameToBeFilled.setTitleCache(fullNameString, true);
1091
			// FIXME Quick fix, otherwise search would not deliver results for unparsable names
1092
			nameToBeFilled.setNameCache(fullNameString, true);
1093
			// END
1094
			logger.info("no applicable parsing rule could be found for \"" + fullNameString + "\"");;
1095
		}
1096
		nameToBeFilled.setCombinationAuthorship(authors[0]);
1097
		nameToBeFilled.setExCombinationAuthorship(authors[1]);
1098
		nameToBeFilled.setBasionymAuthorship(authors[2]);
1099
		nameToBeFilled.setExBasionymAuthorship(authors[3]);
1100
		if (nameToBeFilled instanceof ZoologicalName){
1101
			ZoologicalName zooName = (ZoologicalName)nameToBeFilled;
1102
			zooName.setPublicationYear(years[0]);
1103
			zooName.setOriginalPublicationYear(years[2]);
1104
		}
1105
	}
1106

    
1107
	/**
1108
	 * Guesses the rank of uninomial depending on the typical endings for ranks
1109
	 * @param nameToBeFilled
1110
	 * @param string
1111
	 */
1112
	private Rank guessUninomialRank(NonViralName nameToBeFilled, String uninomial) {
1113
		Rank result = Rank.GENUS();
1114
		if (nameToBeFilled.isInstanceOf(BotanicalName.class)){
1115
			if (false){
1116
				//
1117
			}else if (uninomial.endsWith("phyta") || uninomial.endsWith("mycota") ){  //plants, fungi
1118
				result = Rank.SECTION_BOTANY();
1119
			}else if (uninomial.endsWith("bionta")){
1120
				result = Rank.SUBKINGDOM();  //TODO
1121
			}else if (uninomial.endsWith("phytina")|| uninomial.endsWith("mycotina")  ){  //plants, fungi
1122
				result = Rank.SUBSECTION_BOTANY();
1123
			}else if (uninomial.endsWith("opsida") || uninomial.endsWith("phyceae") || uninomial.endsWith("mycetes")){  //plants, algae, fungi
1124
				result = Rank.CLASS();
1125
			}else if (uninomial.endsWith("idae") || uninomial.endsWith("phycidae") || uninomial.endsWith("mycetidae")){ //plants, algae, fungi
1126
				result = Rank.SUBCLASS();
1127
			}else if (uninomial.endsWith("ales")){
1128
				result = Rank.ORDER();
1129
			}else if (uninomial.endsWith("ineae")){
1130
				result = Rank.SUBORDER();
1131
			}else if (uninomial.endsWith("aceae")){
1132
					result = Rank.FAMILY();
1133
			}else if (uninomial.endsWith("oideae")){
1134
				result = Rank.SUBFAMILY();
1135
			}else if (uninomial.endsWith("eae")){
1136
				result = Rank.TRIBE();
1137
			}else if (uninomial.endsWith("inae")){
1138
				result = Rank.SUBTRIBE();
1139
			}else if (uninomial.endsWith("ota")){
1140
				result = Rank.KINGDOM();  //TODO
1141
			}
1142
		}else if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
1143
			if (false){
1144
				//
1145
			}else if (uninomial.endsWith("oideae")){
1146
				result = Rank.SUPERFAMILY();
1147
			}else if (uninomial.endsWith("idae")){
1148
					result = Rank.FAMILY();
1149
			}else if (uninomial.endsWith("inae")){
1150
				result = Rank.SUBFAMILY();
1151
			}else if (uninomial.endsWith("inae")){
1152
				result = Rank.SUBFAMILY();
1153
			}else if (uninomial.endsWith("ini")){
1154
				result = Rank.TRIBE();
1155
			}else if (uninomial.endsWith("ina")){
1156
				result = Rank.SUBTRIBE();
1157
			}
1158
		}else{
1159
			//
1160
		}
1161
		return result;
1162
	}
1163

    
1164
	/**
1165
	 * Parses the fullAuthorString
1166
	 * @param fullAuthorString
1167
	 * @return array of Teams containing the Team[0],
1168
	 * ExTeam[1], BasionymTeam[2], ExBasionymTeam[3]
1169
	 */
1170
	protected void fullAuthors (String fullAuthorStringOrig, TeamOrPersonBase<?>[] authors, Integer[] years, Class<? extends NonViralName> clazz)
1171
			throws StringNotParsableException{
1172
		if (fullAuthorStringOrig == null || clazz == null){
1173
			return;
1174
		}
1175
		String fullAuthorString = fullAuthorStringOrig.trim();
1176

    
1177
		//Botanic
1178
		if ( BotanicalName.class.isAssignableFrom(clazz) ){
1179
			if (! fullBotanicAuthorStringPattern.matcher(fullAuthorString).matches() ){
1180
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1181
			}
1182
		}
1183
		//Zoo
1184
		else if ( ZoologicalName.class.isAssignableFrom(clazz) ){
1185
			if (! fullZooAuthorStringPattern.matcher(fullAuthorString).matches() ){
1186
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1187
			}
1188
		}else {
1189
			//TODO
1190
			logger.warn ("Full author String parsable only for defined BotanicalNames or ZoologicalNames but this is " + clazz.getSimpleName());
1191
			throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1192
		}
1193
		fullAuthorsChecked(fullAuthorString, authors, years);
1194
	}
1195

    
1196
	/*
1197
	 * like fullTeams but without trim and match check
1198
	 */
1199
	protected void fullAuthorsChecked (String fullAuthorString, TeamOrPersonBase<?>[] authors, Integer[] years){
1200
		int authorShipStart = 0;
1201
		Matcher basionymMatcher = basionymPattern.matcher(fullAuthorString);
1202

    
1203
		if (basionymMatcher.find(0)){
1204

    
1205
			String basString = basionymMatcher.group();
1206
			basString = basString.replaceFirst(basStart, "");
1207
			basString = basString.replaceAll(basEnd, "").trim();
1208
			authorShipStart = basionymMatcher.end(1);
1209

    
1210
			TeamOrPersonBase<?>[] basAuthors = new TeamOrPersonBase[2];
1211
			Integer[] basYears = new Integer[2];
1212
			authorsAndEx(basString, basAuthors, basYears);
1213
			authors[2]= basAuthors[0];
1214
			years[2] = basYears[0];
1215
			authors[3]= basAuthors[1];
1216
			years[3] = basYears[1];
1217
		}
1218
		if (fullAuthorString.length() >= authorShipStart){
1219
			TeamOrPersonBase<?>[] combinationAuthors = new TeamOrPersonBase[2];
1220
			Integer[] combinationYears = new Integer[2];
1221
			authorsAndEx(fullAuthorString.substring(authorShipStart), combinationAuthors, combinationYears);
1222
			authors[0]= combinationAuthors[0] ;
1223
			years[0] = combinationYears[0];
1224
			authors[1]= combinationAuthors[1];
1225
			years[1] = combinationYears[1];
1226
		}
1227
	}
1228

    
1229

    
1230
	/**
1231
	 * Parses the author and ex-author String
1232
	 * @param authorShipStringOrig String representing the author and the ex-author team
1233
	 * @return array of Teams containing the Team[0] and the ExTeam[1]
1234
	 */
1235
	protected void authorsAndEx (String authorShipStringOrig, TeamOrPersonBase<?>[] authors, Integer[] years){
1236
		//TODO noch allgemeiner am anfang durch Replace etc.
1237
		String authorShipString = authorShipStringOrig.trim();
1238
		authorShipString = authorShipString.replaceFirst(oWs + "ex" + oWs, " ex. " );
1239

    
1240
		//int authorEnd = authorTeamString.length();
1241
		int authorBegin = 0;
1242

    
1243
		Matcher exAuthorMatcher = exAuthorPattern.matcher(authorShipString);
1244
		if (exAuthorMatcher.find(0)){
1245
			authorBegin = exAuthorMatcher.end(0);
1246
			int exAuthorEnd = exAuthorMatcher.start(0);
1247
			String exString = authorShipString.substring(0, exAuthorEnd).trim();
1248
			authors [1] = author(exString);
1249
		}
1250
		zooOrBotanicAuthor(authorShipString.substring(authorBegin), authors, years );
1251
	}
1252

    
1253
	/**
1254
	 * Parses the authorString and if it matches an botanical or zoological authorTeam it fills
1255
	 * the computes the AuthorTeam and fills it into the first field of the team array. Same applies
1256
	 * to the year in case of an zoological name.
1257
	 * @param authorString
1258
	 * @param team
1259
	 * @param year
1260
	 */
1261
	protected void zooOrBotanicAuthor(String authorString, TeamOrPersonBase<?>[] team, Integer[] year){
1262
		if (authorString == null){
1263
			return;
1264
		}else if ((authorString = authorString.trim()).length() == 0){
1265
			return;
1266
		}
1267
		Matcher zooAuthorAddidtionMatcher = zooAuthorAddidtionPattern.matcher(authorString);
1268
		if (zooAuthorAddidtionMatcher.find()){
1269
			int index = zooAuthorAddidtionMatcher.start(0);
1270
			String strYear = authorString.substring(index);
1271
			strYear = strYear.replaceAll(zooAuthorYearSeperator, "").trim();
1272
			year[0] = Integer.valueOf(strYear);
1273
			authorString = authorString.substring(0, index).trim();
1274
		}
1275
		team[0] = author(authorString);
1276
	}
1277

    
1278

    
1279
	/**
1280
	 * Parses an authorTeam String and returns the Team
1281
	 * !!! TODO (atomization not yet implemented)
1282
	 * @param authorTeamString String representing the author team
1283
	 * @return an Team
1284
	 */
1285
	protected TeamOrPersonBase<?> author (String authorString){
1286
		if (authorString == null){
1287
			return null;
1288
		}else if ((authorString = authorString.trim()).length() == 0){
1289
			return null;
1290
		}else if (! finalTeamSplitterPattern.matcher(authorString).find() && ! authorIsAlwaysTeam){
1291
			//1 Person
1292
			Person result = Person.NewInstance();
1293
			result.setNomenclaturalTitle(authorString);
1294
			return result;
1295
		}else{
1296
			return parsedTeam(authorString);
1297
		}
1298

    
1299
	}
1300

    
1301
	/**
1302
	 * Parses an authorString (reprsenting a team into the single authors and add
1303
	 * them to the return Team.
1304
	 * @param authorString
1305
	 * @return Team
1306
	 */
1307
	protected Team parsedTeam(String authorString){
1308
		Team result = Team.NewInstance();
1309
		String[] authors = authorString.split(notFinalTeamSplitter);
1310
		for (int i = 0; i < authors.length; i++){
1311
		    String author = authors[i];
1312
		    if ("al.".equals(author.trim()) && i == authors.length - 1){  //final al. is handled as hasMoreMembers
1313
			    result.setHasMoreMembers(true);
1314
			}else{
1315
			    Person person = Person.NewInstance();
1316
			    person.setNomenclaturalTitle(author);
1317
			    result.addTeamMember(person);
1318
			}
1319
		}
1320
		return result;
1321
	}
1322

    
1323

    
1324
//	// Parsing of the given full name that has been identified as a cultivar already somwhere else.
1325
//	// The ... cv. ... syntax is not covered here as it is not according the rules for naming cultivars.
1326
	public BotanicalName parseCultivar(String fullName)	throws StringNotParsableException{
1327
		CultivarPlantName result = null;
1328
		    String[] words = oWsPattern.split(fullName);
1329

    
1330
		    /* ---------------------------------------------------------------------------------
1331
		     * cultivar
1332
		     * ---------------------------------------------------------------------------------*/
1333
			if (fullName.indexOf(" '") != 0){
1334
				//TODO location of 'xx' is probably not arbitrary
1335
				Matcher cultivarMatcher = cultivarPattern.matcher(fullName);
1336
				if (cultivarMatcher.find()){
1337
					String namePart = fullName.replaceFirst(cultivar, "");
1338

    
1339
					String cultivarPart = cultivarMatcher.group(0).replace("'","").trim();
1340
					//OLD: String cultivarPart = cultivarRE.getParen(0).replace("'","").trim();
1341

    
1342
					result = (CultivarPlantName)parseFullName(namePart);
1343
					result.setCultivarName(cultivarPart);
1344
				}
1345
			}else if (fullName.indexOf(" cv.") != 0){
1346
				// cv. is old form (not official)
1347
				throw new StringNotParsableException("Cultivars with only cv. not yet implemented in name parser!");
1348
			}
1349

    
1350
		    /* ---------------------------------------------------------------------------------
1351
		     * cultivar group
1352
		     * ---------------------------------------------------------------------------------
1353
		     */
1354
			// TODO in work
1355
			//Ann. this is not the official way of noting cultivar groups
1356
		    String group = oWs + "Group" + oWs + capitalEpiWord + end;
1357
			Pattern groupRE = Pattern.compile(group);
1358
			Matcher groupMatcher = groupRE.matcher(fullName);
1359
			if (groupMatcher.find()){
1360
		    	if (! words[words.length - 2].equals("group")){
1361
		            throw new StringNotParsableException ("fct ParseHybrid --> term before cultivar group name in " + fullName + " should be 'group'");
1362
		        }else{
1363

    
1364
		        	String namePart = fullName.substring(0, groupMatcher.start(0) - 0);
1365
		        	//OLD: String namePart = fullName.substring(0, groupRE.getParenStart(0) - 0);
1366

    
1367
		        	String cultivarPart = words[words.length -1];
1368
		        	result = (CultivarPlantName)parseFullName(namePart);
1369
		        	if (result != null){
1370
		        		result.setCultivarName(cultivarPart);
1371

    
1372
		        		//OLD: result.setCultivarGroupName(cultivarPart);
1373
		        	}
1374
		        }
1375

    
1376
		    }
1377
//		    // ---------------------------------------------------------------------------------
1378
//		    if ( result = "" ){
1379
//		        return "I: fct ParseCultivar: --> could not parse cultivar " + fullName;
1380
//		    }else{
1381
//		        return result;
1382
	//	    }
1383
			return result; //TODO
1384
	}
1385

    
1386

    
1387
	private void makeEmpty(NonViralName<?> nameToBeFilled){
1388
		nameToBeFilled.setRank(null);
1389
		nameToBeFilled.setTitleCache(null, false);
1390
		nameToBeFilled.setFullTitleCache(null, false);
1391
		nameToBeFilled.setNameCache(null, false);
1392

    
1393
		nameToBeFilled.setAppendedPhrase(null);
1394
		nameToBeFilled.setBasionymAuthorship(null);
1395
		nameToBeFilled.setCombinationAuthorship(null);
1396
		nameToBeFilled.setExBasionymAuthorship(null);
1397
		nameToBeFilled.setExCombinationAuthorship(null);
1398
		nameToBeFilled.setAuthorshipCache(null, false);
1399

    
1400

    
1401
		//delete problems except check rank
1402
		makeProblemEmpty(nameToBeFilled);
1403

    
1404
		// TODO ?
1405
		//nameToBeFilled.setHomotypicalGroup(newHomotypicalGroup);
1406

    
1407

    
1408
		nameToBeFilled.setGenusOrUninomial(null);
1409
		nameToBeFilled.setInfraGenericEpithet(null);
1410
		nameToBeFilled.setSpecificEpithet(null);
1411
		nameToBeFilled.setInfraSpecificEpithet(null);
1412

    
1413
		nameToBeFilled.setNomenclaturalMicroReference(null);
1414
		nameToBeFilled.setNomenclaturalReference(null);
1415

    
1416
		nameToBeFilled.setHybridFormula(false);
1417
		nameToBeFilled.setMonomHybrid(false);
1418
		nameToBeFilled.setBinomHybrid(false);
1419
		nameToBeFilled.setTrinomHybrid(false);
1420

    
1421
		if (nameToBeFilled.isInstanceOf(BotanicalName.class)){
1422
			BotanicalName botanicalName = (BotanicalName)nameToBeFilled;
1423
			botanicalName.setAnamorphic(false);
1424
		}
1425

    
1426
		if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
1427
			ZoologicalName zoologicalName = (ZoologicalName)nameToBeFilled;
1428
			zoologicalName.setBreed(null);
1429
			zoologicalName.setOriginalPublicationYear(null);
1430
		}
1431

    
1432
		//nom status handled in nom status parser, otherwise we loose additional information like reference etc.
1433
		//hybrid relationships handled in hybrid formula and at end of fullNameParser
1434
	}
1435

    
1436

    
1437

    
1438
}
(3-3/8)