Project

General

Profile

Download (54.7 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: "+ strReference);
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.setAbbrevTitle(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.setAbbrevTitle(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
		    //species with infra generic epithet
829
			 else if (speciesWithInfraGenPattern.matcher(fullNameString).matches()){
830
			     nameToBeFilled.setRank(Rank.SPECIES());
831
	             nameToBeFilled.setGenusOrUninomial(epi[0]);
832
                 nameToBeFilled.setInfraGenericEpithet(epi[2]);
833
	             nameToBeFilled.setSpecificEpithet(epi[4]);
834
	             authorString = fullNameString.substring(epi[0].length() + 2 + epi[2].length() + 2 + epi[4].length());
835
			 }
836
			 //autonym
837
			 else if (autonymPattern.matcher(fullNameString).matches()){
838
				nameToBeFilled.setRank(Rank.getRankByIdInVoc(epi[epi.length - 2]));
839
				nameToBeFilled.setGenusOrUninomial(epi[0]);
840
				nameToBeFilled.setSpecificEpithet(epi[1]);
841
				nameToBeFilled.setInfraSpecificEpithet(epi[epi.length - 1]);
842
				int lenSpecies = 2 + epi[0].length()+epi[1].length();
843
				int lenInfraSpecies =  2 + epi[epi.length - 2].length() + epi[epi.length - 1].length();
844
				authorString = fullNameString.substring(lenSpecies, fullNameString.length() - lenInfraSpecies);
845
			}
846
			 //infraSpecies
847
			 else if (infraSpeciesPattern.matcher(fullNameString).matches()){
848
				String infraSpecRankMarker = epi[2];
849
				String infraSpecEpi = epi[3];
850
				if ("tax.".equals(infraSpecRankMarker)){
851
					infraSpecRankMarker += " " +  epi[3];
852
					infraSpecEpi = epi[4];
853
				}
854
				Rank infraSpecificRank;
855
				if ("[unranked]".equals(infraSpecRankMarker)){
856
					infraSpecificRank = Rank.INFRASPECIFICTAXON();
857
				}else{
858
					String localInfraSpecRankMarker;
859
					if (infraSpecRankMarker.startsWith(notho)){  //#3868
860
	                    nameToBeFilled.setTrinomHybrid(true);
861
	                    localInfraSpecRankMarker = infraSpecRankMarker.substring(notho.length());
862
					}else if(infraSpecRankMarker.startsWith("n")){
863
	                    nameToBeFilled.setTrinomHybrid(true);
864
	                    localInfraSpecRankMarker = infraSpecRankMarker.substring(1);
865
                    }else{
866
                        localInfraSpecRankMarker = infraSpecRankMarker;
867
                    }
868
				    infraSpecificRank = Rank.getRankByIdInVoc(localInfraSpecRankMarker);
869
				}
870
				nameToBeFilled.setRank(infraSpecificRank);
871
				nameToBeFilled.setGenusOrUninomial(epi[0]);
872
				nameToBeFilled.setSpecificEpithet(epi[1]);
873
				nameToBeFilled.setInfraSpecificEpithet(infraSpecEpi);
874
				authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + infraSpecRankMarker.length() + 1 + infraSpecEpi.length());
875

    
876
			 }
877
		      //infraSpecies without marker
878
			 else if (zooInfraSpeciesPattern.matcher(fullNameString).matches()){
879
					String infraSpecEpi = epi[2];
880
					Rank infraSpecificRank = Rank.SUBSPECIES();
881
					nameToBeFilled.setRank(infraSpecificRank);
882
					nameToBeFilled.setGenusOrUninomial(epi[0]);
883
					nameToBeFilled.setSpecificEpithet(epi[1]);
884
					nameToBeFilled.setInfraSpecificEpithet(infraSpecEpi);
885
					authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + infraSpecEpi.length());
886

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

    
910
				 for ( HybridRelationship rel : nameToBeFilled.getHybridChildRelations()){
911
				     existingRelations.add(rel);
912
				 }
913

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

    
935
				 Rank newRank;
936
				 Rank firstRank = firstName.getRank();
937
				 Rank secondRank = secondName.getRank();
938

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

    
971
		        for (HybridRelationship hybridRelationship: hybridChildRelations){
972
		        	nameToBeFilled.removeHybridRelationship(hybridRelationship);
973
		        }
974
		    }
975

    
976
			//authors
977
		    if (StringUtils.isNotBlank(authorString) ){
978
				handleAuthors(nameToBeFilled, fullNameString, authorString);
979
			}
980
		    return;
981
		} catch (UnknownCdmTypeException e) {
982
			nameToBeFilled.addParsingProblem(ParserProblem.RankNotSupported);
983
			nameToBeFilled.setTitleCache(fullNameString,true);
984
			// FIXME Quick fix, otherwise search would not deilver results for unparsable names
985
			nameToBeFilled.setNameCache(fullNameString,true);
986
			// END
987
			logger.info("unknown rank (" + (rank == null? "null":rank) + ") or abbreviation in string " +  fullNameString);
988
			//return result;
989
			return;
990
		}
991
	}
992

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

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

    
1051
	}
1052

    
1053
	private String removeHybridBlanks(String fullNameString) {
1054
		String result = fullNameString
1055
		        .replaceAll(oWs + "[xX]" + oWs + "(?=[A-Z])", " " + hybridSign + " ")
1056
		        .replaceAll(hybridFull, " "+hybridSign).trim();
1057
		return result;
1058
	}
1059

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

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

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

    
1172
	/**
1173
	 * Parses the fullAuthorString
1174
	 * @param fullAuthorString
1175
	 * @return array of Teams containing the Team[0],
1176
	 * ExTeam[1], BasionymTeam[2], ExBasionymTeam[3]
1177
	 */
1178
	protected void fullAuthors (String fullAuthorStringOrig, TeamOrPersonBase<?>[] authors, Integer[] years, Class<? extends NonViralName> clazz)
1179
			throws StringNotParsableException{
1180
		if (fullAuthorStringOrig == null || clazz == null){
1181
			return;
1182
		}
1183
		String fullAuthorString = fullAuthorStringOrig.trim();
1184

    
1185
		//Botanic
1186
		if ( BotanicalName.class.isAssignableFrom(clazz) ){
1187
			if (! fullBotanicAuthorStringPattern.matcher(fullAuthorString).matches() ){
1188
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1189
			}
1190
		}
1191
		//Zoo
1192
		else if ( ZoologicalName.class.isAssignableFrom(clazz) ){
1193
			if (! fullZooAuthorStringPattern.matcher(fullAuthorString).matches() ){
1194
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1195
			}
1196
		}else {
1197
			//TODO
1198
			logger.warn ("Full author String parsable only for defined BotanicalNames or ZoologicalNames but this is " + clazz.getSimpleName());
1199
			throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
1200
		}
1201
		fullAuthorsChecked(fullAuthorString, authors, years);
1202
	}
1203

    
1204
	/*
1205
	 * like fullTeams but without trim and match check
1206
	 */
1207
	protected void fullAuthorsChecked (String fullAuthorString, TeamOrPersonBase<?>[] authors, Integer[] years){
1208
		int authorShipStart = 0;
1209
		Matcher basionymMatcher = basionymPattern.matcher(fullAuthorString);
1210

    
1211
		if (basionymMatcher.find(0)){
1212

    
1213
			String basString = basionymMatcher.group();
1214
			basString = basString.replaceFirst(basStart, "");
1215
			basString = basString.replaceAll(basEnd, "").trim();
1216
			authorShipStart = basionymMatcher.end(1);
1217

    
1218
			TeamOrPersonBase<?>[] basAuthors = new TeamOrPersonBase[2];
1219
			Integer[] basYears = new Integer[2];
1220
			authorsAndEx(basString, basAuthors, basYears);
1221
			authors[2]= basAuthors[0];
1222
			years[2] = basYears[0];
1223
			authors[3]= basAuthors[1];
1224
			years[3] = basYears[1];
1225
		}
1226
		if (fullAuthorString.length() >= authorShipStart){
1227
			TeamOrPersonBase<?>[] combinationAuthors = new TeamOrPersonBase[2];
1228
			Integer[] combinationYears = new Integer[2];
1229
			authorsAndEx(fullAuthorString.substring(authorShipStart), combinationAuthors, combinationYears);
1230
			authors[0]= combinationAuthors[0] ;
1231
			years[0] = combinationYears[0];
1232
			authors[1]= combinationAuthors[1];
1233
			years[1] = combinationYears[1];
1234
		}
1235
	}
1236

    
1237

    
1238
	/**
1239
	 * Parses the author and ex-author String
1240
	 * @param authorShipStringOrig String representing the author and the ex-author team
1241
	 * @return array of Teams containing the Team[0] and the ExTeam[1]
1242
	 */
1243
	protected void authorsAndEx (String authorShipStringOrig, TeamOrPersonBase<?>[] authors, Integer[] years){
1244
		//TODO noch allgemeiner am anfang durch Replace etc.
1245
		String authorShipString = authorShipStringOrig.trim();
1246
		authorShipString = authorShipString.replaceFirst(oWs + "ex" + oWs, " ex. " );
1247

    
1248
		//int authorEnd = authorTeamString.length();
1249
		int authorBegin = 0;
1250

    
1251
		Matcher exAuthorMatcher = exAuthorPattern.matcher(authorShipString);
1252
		if (exAuthorMatcher.find(0)){
1253
			authorBegin = exAuthorMatcher.end(0);
1254
			int exAuthorEnd = exAuthorMatcher.start(0);
1255
			String exString = authorShipString.substring(0, exAuthorEnd).trim();
1256
			authors [1] = author(exString);
1257
		}
1258
		zooOrBotanicAuthor(authorShipString.substring(authorBegin), authors, years );
1259
	}
1260

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

    
1286

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

    
1307
	}
1308

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

    
1331

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

    
1338
		    /* ---------------------------------------------------------------------------------
1339
		     * cultivar
1340
		     * ---------------------------------------------------------------------------------*/
1341
			if (fullName.indexOf(" '") != 0){
1342
				//TODO location of 'xx' is probably not arbitrary
1343
				Matcher cultivarMatcher = cultivarPattern.matcher(fullName);
1344
				if (cultivarMatcher.find()){
1345
					String namePart = fullName.replaceFirst(cultivar, "");
1346

    
1347
					String cultivarPart = cultivarMatcher.group(0).replace("'","").trim();
1348
					//OLD: String cultivarPart = cultivarRE.getParen(0).replace("'","").trim();
1349

    
1350
					result = (CultivarPlantName)parseFullName(namePart);
1351
					result.setCultivarName(cultivarPart);
1352
				}
1353
			}else if (fullName.indexOf(" cv.") != 0){
1354
				// cv. is old form (not official)
1355
				throw new StringNotParsableException("Cultivars with only cv. not yet implemented in name parser!");
1356
			}
1357

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

    
1372
		        	String namePart = fullName.substring(0, groupMatcher.start(0) - 0);
1373
		        	//OLD: String namePart = fullName.substring(0, groupRE.getParenStart(0) - 0);
1374

    
1375
		        	String cultivarPart = words[words.length -1];
1376
		        	result = (CultivarPlantName)parseFullName(namePart);
1377
		        	if (result != null){
1378
		        		result.setCultivarName(cultivarPart);
1379

    
1380
		        		//OLD: result.setCultivarGroupName(cultivarPart);
1381
		        	}
1382
		        }
1383

    
1384
		    }
1385
//		    // ---------------------------------------------------------------------------------
1386
//		    if ( result = "" ){
1387
//		        return "I: fct ParseCultivar: --> could not parse cultivar " + fullName;
1388
//		    }else{
1389
//		        return result;
1390
	//	    }
1391
			return result; //TODO
1392
	}
1393

    
1394

    
1395
	private void makeEmpty(NonViralName<?> nameToBeFilled){
1396
		nameToBeFilled.setRank(null);
1397
		nameToBeFilled.setTitleCache(null, false);
1398
		nameToBeFilled.setFullTitleCache(null, false);
1399
		nameToBeFilled.setNameCache(null, false);
1400

    
1401
		nameToBeFilled.setAppendedPhrase(null);
1402
		nameToBeFilled.setBasionymAuthorship(null);
1403
		nameToBeFilled.setCombinationAuthorship(null);
1404
		nameToBeFilled.setExBasionymAuthorship(null);
1405
		nameToBeFilled.setExCombinationAuthorship(null);
1406
		nameToBeFilled.setAuthorshipCache(null, false);
1407

    
1408

    
1409
		//delete problems except check rank
1410
		makeProblemEmpty(nameToBeFilled);
1411

    
1412
		// TODO ?
1413
		//nameToBeFilled.setHomotypicalGroup(newHomotypicalGroup);
1414

    
1415

    
1416
		nameToBeFilled.setGenusOrUninomial(null);
1417
		nameToBeFilled.setInfraGenericEpithet(null);
1418
		nameToBeFilled.setSpecificEpithet(null);
1419
		nameToBeFilled.setInfraSpecificEpithet(null);
1420

    
1421
		nameToBeFilled.setNomenclaturalMicroReference(null);
1422
		nameToBeFilled.setNomenclaturalReference(null);
1423

    
1424
		nameToBeFilled.setHybridFormula(false);
1425
		nameToBeFilled.setMonomHybrid(false);
1426
		nameToBeFilled.setBinomHybrid(false);
1427
		nameToBeFilled.setTrinomHybrid(false);
1428

    
1429
		if (nameToBeFilled.isInstanceOf(BotanicalName.class)){
1430
			BotanicalName botanicalName = (BotanicalName)nameToBeFilled;
1431
			botanicalName.setAnamorphic(false);
1432
		}
1433

    
1434
		if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
1435
			ZoologicalName zoologicalName = (ZoologicalName)nameToBeFilled;
1436
			zoologicalName.setBreed(null);
1437
			zoologicalName.setOriginalPublicationYear(null);
1438
		}
1439

    
1440
		//nom status handled in nom status parser, otherwise we loose additional information like reference etc.
1441
		//hybrid relationships handled in hybrid formula and at end of fullNameParser
1442
	}
1443

    
1444

    
1445

    
1446
}
(3-3/8)