Project

General

Profile

Download (46.3 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.regex.Matcher;
13
import java.util.regex.Pattern;
14

    
15
import org.apache.log4j.Logger;
16
import org.joda.time.DateTimeFieldType;
17
import org.joda.time.Partial;
18

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

    
46

    
47
/**
48
 * @author a.mueller
49
 *
50
 */
51
public class NonViralNameParserImpl extends NonViralNameParserImplRegExBase implements INonViralNameParser<NonViralName> {
52
	private static final Logger logger = Logger.getLogger(NonViralNameParserImpl.class);
53
	
54
	// good intro: http://java.sun.com/docs/books/tutorial/essential/regex/index.html
55
	
56
	final static boolean MAKE_EMPTY = true;
57
	final static boolean MAKE_NOT_EMPTY = false;
58
	
59
	private boolean authorIsAlwaysTeam = true;
60
	private ReferenceFactory refFactory = ReferenceFactory.newInstance();
61
	
62
	
63
	public static NonViralNameParserImpl NewInstance(){
64
		return new NonViralNameParserImpl();
65
	}
66

    
67
	/* (non-Javadoc)
68
	 * @see eu.etaxonomy.cdm.strategy.ITaxonNameParser#parseSubGenericSimpleName(java.lang.String)
69
	 */
70
	public NonViralName parseSimpleName(String simpleName){
71
		return parseSimpleName(simpleName, null, null);
72
	}
73
	
74
	
75
	/* (non-Javadoc)
76
	 * @see eu.etaxonomy.cdm.strategy.parser.INonViralNameParser#parseSimpleName(java.lang.String, eu.etaxonomy.cdm.model.name.NomenclaturalCode, eu.etaxonomy.cdm.model.name.Rank)
77
	 */
78
	public NonViralName parseSimpleName(String simpleName, NomenclaturalCode code, Rank rank){
79
		//"parseSimpleName() not yet implemented. Uses parseFullName() instead");
80
		return parseFullName(simpleName, code, rank);
81
	}
82

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

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

    
141
	/* (non-Javadoc)
142
	 * @see eu.etaxonomy.cdm.strategy.parser.INonViralNameParser#parseFullReference(java.lang.String)
143
	 */
144
	public NonViralName parseReferencedName(String fullReferenceString) {
145
		return parseReferencedName(fullReferenceString, null, null);
146
	}
147
	
148
	/* (non-Javadoc)
149
	 * @see eu.etaxonomy.cdm.strategy.ITaxonNameParser#parseFullReference(java.lang.String, eu.etaxonomy.cdm.model.name.Rank)
150
	 */
151
	public NonViralName parseReferencedName(String fullReferenceString, NomenclaturalCode nomCode, Rank rank) {
152
		if (fullReferenceString == null){
153
			return null;
154
		}else{
155
			NonViralName result = getNonViralNameInstance(fullReferenceString, nomCode, rank);
156
			parseReferencedName(result, fullReferenceString, rank, MAKE_EMPTY);
157
			return result;
158
		}
159
	}
160
	
161
	private String standardize(NonViralName nameToBeFilled, String fullReferenceString, boolean makeEmpty){
162
		//Check null and standardize
163
		if (fullReferenceString == null){
164
			//return null;
165
			return null;
166
		}
167
		if (makeEmpty){
168
			makeEmpty(nameToBeFilled);
169
		}
170
		fullReferenceString = fullReferenceString.replaceAll(oWs , " ");
171
		fullReferenceString = fullReferenceString.trim();
172
		if ("".equals(fullReferenceString)){
173
			fullReferenceString = null;
174
		}
175
		return fullReferenceString;
176
	}
177

    
178
	/**
179
	 * Returns the regEx to be used for the full-name depending on the code
180
	 * @param nameToBeFilled
181
	 * @return
182
	 */
183
	private String getLocalFullName(NonViralName nameToBeFilled){
184
		if (nameToBeFilled instanceof ZoologicalName){
185
			return anyZooFullName;
186
		}else if (nameToBeFilled instanceof BotanicalName) {
187
			return anyBotanicFullName;
188
		}else if (nameToBeFilled instanceof NonViralName) {
189
			return anyBotanicFullName;  //TODO ?
190
		}else{
191
			logger.warn("nameToBeFilled class not supported ("+nameToBeFilled.getClass()+")");
192
			return null;
193
		}
194
	}
195
	
196
	/**
197
	 * Returns the regEx to be used for the fsimple-name depending on the code
198
	 * @param nameToBeFilled
199
	 * @return
200
	 */
201
	private String getLocalSimpleName(NonViralName nameToBeFilled){
202
		if (nameToBeFilled instanceof ZoologicalName){
203
			return anyZooName;
204
		}else if (nameToBeFilled instanceof NonViralName){
205
			return anyZooName;  //TODO ?
206
		}else if (nameToBeFilled instanceof BotanicalName) {
207
			return anyBotanicName;
208
		}else{
209
			logger.warn("nameToBeFilled class not supported ("+nameToBeFilled.getClass()+")");
210
			return null;
211
		}
212
	}
213
	
214
	private Matcher getMatcher(String regEx, String matchString){
215
		Pattern pattern = Pattern.compile(regEx);
216
		Matcher matcher = pattern.matcher(matchString);
217
		return matcher;
218
	}
219
	
220
	/* (non-Javadoc)
221
	 * @see eu.etaxonomy.cdm.strategy.ITaxonNameParser#parseFullReference(eu.etaxonomy.cdm.model.name.BotanicalName, java.lang.String, eu.etaxonomy.cdm.model.name.Rank, boolean)
222
	 */
223
	public void parseReferencedName(NonViralName nameToBeFilled, String fullReferenceString, Rank rank, boolean makeEmpty) {
224
		//standardize
225
		fullReferenceString = standardize(nameToBeFilled, fullReferenceString, makeEmpty);
226
		if (fullReferenceString == null){
227
			return;
228
		}
229
		// happens already in standardize(...)
230
//		makeProblemEmpty(nameToBeFilled);
231
		
232
		//make nomenclatural status and replace it by empty string 
233
	    fullReferenceString = parseNomStatus(fullReferenceString, nameToBeFilled);
234
	    nameToBeFilled.setProblemEnds(fullReferenceString.length());
235
		
236
	    //get full name reg
237
		String localFullName = getLocalFullName(nameToBeFilled);
238
		//get full name reg
239
		String localSimpleName = getLocalSimpleName(nameToBeFilled);
240
		
241
		//separate name and reference part
242
		String nameAndRefSeparator = "(^" + localFullName + ")("+ referenceSeperator + ")";
243
		Matcher nameAndRefSeparatorMatcher = getMatcher (nameAndRefSeparator, fullReferenceString);
244
		
245
		Matcher onlyNameMatcher = getMatcher (localFullName, fullReferenceString);
246
		Matcher onlySimpleNameMatcher = getMatcher (localSimpleName, fullReferenceString);
247
		
248
		if (nameAndRefSeparatorMatcher.find()){
249
			makeNameWithReference(nameToBeFilled, fullReferenceString, nameAndRefSeparatorMatcher, rank, makeEmpty);
250
		}else if (onlyNameMatcher.matches()){
251
			makeEmpty = false;
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 = getLocalFullName(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.getBasionymAuthorTeam() != 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 = (INomenclaturalReference)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
	    ReferenceBase nomRef;
379
		if ( (nomRef = (ReferenceBase)nameToBeFilled.getNomenclaturalReference()) != null ){
380
			nomRef.setAuthorTeam((TeamOrPersonBase)nameToBeFilled.getCombinationAuthorTeam());
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
	private String parseNomStatus(String fullString, NonViralName nameToBeFilled) {
391
		String statusString;
392
		Pattern hasStatusPattern = Pattern.compile("(" + pNomStatusPhrase + ")"); 
393
		Matcher hasStatusMatcher = hasStatusPattern.matcher(fullString);
394
		
395
		if (hasStatusMatcher.find()) {
396
			String statusPhrase = hasStatusMatcher.group(0);
397
			
398
			Pattern statusPattern = Pattern.compile(pNomStatus);
399
			Matcher statusMatcher = statusPattern.matcher(statusPhrase);
400
			statusMatcher.find();
401
			statusString = statusMatcher.group(0);
402
			try {
403
				NomenclaturalStatusType nomStatusType = NomenclaturalStatusType.getNomenclaturalStatusTypeByAbbreviation(statusString);
404
				NomenclaturalStatus nomStatus = NomenclaturalStatus.NewInstance(nomStatusType);
405
				nameToBeFilled.addStatus(nomStatus);
406
			    
407
				fullString = fullString.replace(statusPhrase, "");
408
			} catch (UnknownCdmTypeException e) {
409
				//Do nothing
410
			}
411
		}
412
		return fullString;
413
	}
414
	
415
	
416
	private void parseReference(NonViralName nameToBeFilled, String strReference, boolean isInReference){
417
		
418
		INomenclaturalReference ref;
419
		String originalStrReference = strReference;
420
		
421
		//End (just delete end (e.g. '.', may be ambigous for yearPhrase, but no real information gets lost
422
		Matcher endMatcher = getMatcher(referenceEnd + end, strReference);
423
		if (endMatcher.find()){
424
			String endPart = endMatcher.group(0);
425
			strReference = strReference.substring(0, strReference.length() - endPart.length());
426
		}
427
		
428
//		String pDetailYear = ".*" + detailSeparator + detail + fWs + yearSeperator + fWs + yearPhrase + fWs + end;
429
//		Matcher detailYearMatcher = getMatcher(pDetailYear, strReference);
430
		
431
		String strReferenceWithYear = strReference;
432
		//year
433
		String yearPart = null;
434
		String pYearPhrase = yearSeperator + fWs + yearPhrase + fWs + end;
435
		Matcher yearPhraseMatcher = getMatcher(pYearPhrase, strReference);
436
		if (yearPhraseMatcher.find()){
437
			yearPart = yearPhraseMatcher.group(0);
438
			strReference = strReference.substring(0, strReference.length() - yearPart.length());
439
			yearPart = yearPart.replaceFirst(pStart + yearSeperator, "").trim();
440
		}else{
441
			if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
442
				ZoologicalName zooName = CdmBase.deproxy(nameToBeFilled, ZoologicalName.class);
443
				yearPart = String.valueOf(zooName.getPublicationYear());
444
				//continue
445
			}else{
446
				ref = makeDetailYearUnparsable(nameToBeFilled,strReference);
447
				ref.setDatePublished(TimePeriod.parseString(yearPart));
448
				return;
449
			}
450
		}
451
		
452
			
453
		//detail
454
		String pDetailPhrase = detailSeparator + fWs + detail + fWs + end;
455
		Matcher detailPhraseMatcher = getMatcher(pDetailPhrase, strReference);
456
		if (detailPhraseMatcher.find()){
457
			String detailPart = detailPhraseMatcher.group(0);
458
			strReference = strReference.substring(0, strReference.length() - detailPart.length());
459
			detailPart = detailPart.replaceFirst(pStart + detailSeparator, "").trim();
460
			nameToBeFilled.setNomenclaturalMicroReference(detailPart);
461
		}else{
462
			makeDetailYearUnparsable(nameToBeFilled, strReferenceWithYear);
463
			return;
464
		}
465
		//parse title and author
466
		ref = parseReferenceTitle(strReference, yearPart, isInReference);
467
		if (ref.hasProblem()){
468
			ref.setTitleCache( (isInReference?"in ":"") +  originalStrReference,true);
469
		}
470
		nameToBeFilled.setNomenclaturalReference((ReferenceBase)ref);
471
		int end = Math.min(strReference.length(), ref.getProblemEnds());
472
		ref.setProblemEnds(end);
473
	}
474

    
475
	/**
476
	 * @param nameToBeFilled
477
	 * @param strReference
478
	 * @return 
479
	 */
480
	private INomenclaturalReference makeDetailYearUnparsable(NonViralName nameToBeFilled, String strReference) {
481
		INomenclaturalReference ref;
482
		//ref = Generic.NewInstance();
483
		
484
		ref = refFactory.newGeneric();
485
		ref.setTitleCache(strReference,true);
486
		ref.setProblemEnds(strReference.length());
487
		ref.addParsingProblem(ParserProblem.CheckDetailOrYear);
488
		nameToBeFilled.addParsingProblem(ParserProblem.CheckDetailOrYear);
489
		nameToBeFilled.setNomenclaturalReference((ReferenceBase)ref);
490
		return ref;
491
	}
492
		
493
	/**
494
	 * Parses the referenceTitlePart, including the author volume and edition.
495
	 * @param reference
496
	 * @param year
497
	 * @return
498
	 */
499
	private INomenclaturalReference parseReferenceTitle(String strReference, String year, boolean isInReference){
500
		IBook result = null;
501
		
502
		Matcher refSineDetailMatcher = referenceSineDetailPattern.matcher(strReference);
503
		if (! refSineDetailMatcher.matches()){
504
			//TODO ?
505
		}
506
		
507
		Matcher articleMatcher = getMatcher(pArticleReference, strReference);
508
		
509
		Matcher softArticleMatcher = getMatcher(pSoftArticleReference, strReference);
510
		Matcher bookMatcher = getMatcher(pBookReference, strReference);
511
		Matcher bookSectionMatcher = getMatcher(pBookSectionReference, strReference);
512
		
513
		
514
		if(isInReference == false){
515
			if (bookMatcher.matches() ){
516
				result = parseBook(strReference);
517
			}else{
518
				logger.warn("Non-InRef must be book but does not match book");
519
				result = refFactory.newBook();
520
				makeUnparsableRefTitle(result, strReference);
521
			}
522
		}else{  //inRef
523
			if (articleMatcher.matches()){
524
				//article without separators like ","
525
				result = parseArticle(strReference);
526
			}else if (softArticleMatcher.matches()){
527
				result = parseArticle(strReference);
528
			}else if (bookSectionMatcher.matches()){
529
				result = parseBookSection(strReference);
530
			}else{
531
				result =  refFactory.newGeneric();
532
				makeUnparsableRefTitle(result, "in " + strReference);
533
			}
534
		}
535
		//make year
536
		if (makeYear(result, year) == false){
537
			//TODO
538
			logger.warn("Year could not be parsed");
539
		}
540
		result.setProblemStarts(0);
541
		result.setProblemEnds(strReference.length());
542
		return result;
543
	}
544
	
545
	private void makeUnparsableRefTitle(INomenclaturalReference result, String reference){
546
		result.setTitleCache(reference,true);
547
		result.addParsingProblem(ParserProblem.UnparsableReferenceTitle);
548
	}
549
	
550
	/**
551
	 * Parses a single date string. If the string is not parsable a StringNotParsableException is thrown
552
	 * @param singleDateString
553
	 * @return
554
	 * @throws StringNotParsableException
555
	 */
556
	private static Partial parseSingleDate(String singleDateString) 
557
			throws StringNotParsableException{
558
		Partial dt = new Partial();
559
		if (CdmUtils.isNumeric(singleDateString)){
560
			try {
561
				Integer year = Integer.valueOf(singleDateString.trim());
562
				if (year > 1750 && year < 2050){
563
					dt = dt.with(DateTimeFieldType.year(), year);
564
				}else{
565
					dt = null;
566
				}
567
			} catch (NumberFormatException e) {
568
				logger.debug("Not a Integer format in getCalendar()");
569
				throw new StringNotParsableException(singleDateString + "is not parsable as a single Date");
570
			}
571
		}
572
		return dt;
573
	}
574

    
575
	
576
	/**
577
	 * Parses the publication date part. 
578
	 * @param nomRef
579
	 * @param year
580
	 * @return If the string is not parsable <code>false</code>
581
	 * is returned. <code>True</code> otherwise
582
	 */
583
	private boolean makeYear(INomenclaturalReference nomRef, String year){
584
		boolean result = true;
585
		if (year == null){
586
			return false;
587
		}
588
		if ("".equals(year.trim())){
589
			return true;
590
		}
591
		TimePeriod datePublished = TimePeriod.parseString(year);
592
		
593
		if (nomRef.getType().equals(ReferenceType.BookSection)){
594
			handleBookSectionYear((IBookSection)nomRef, datePublished);
595
		}else if (nomRef instanceof ReferenceBase){
596
			((ReferenceBase)nomRef).setDatePublished(datePublished);	
597
		}else{
598
			throw new ClassCastException("nom Ref is not of type ReferenceBase but " + (nomRef == null? "(null)" : nomRef.getClass()));
599
		}
600
		return result;	
601
	}
602
	
603
	private String makeVolume(IVolumeReference nomRef, String strReference){
604
		//volume
605
		String volPart = null;
606
		String pVolPhrase = volumeSeparator +  volume + end;
607
		Matcher volPhraseMatcher = getMatcher(pVolPhrase, strReference);
608
		if (volPhraseMatcher.find()){
609
			volPart = volPhraseMatcher.group(0);
610
			strReference = strReference.substring(0, strReference.length() - volPart.length());
611
			volPart = volPart.replaceFirst(pStart + volumeSeparator, "").trim();
612
			nomRef.setVolume(volPart);
613
		}
614
		return strReference;
615
	}
616
	
617
	private String makeEdition(IBook book, String strReference){
618
		//volume
619
		String editionPart = null;
620
		Matcher editionPhraseMatcher = getMatcher(pEditionPart, strReference);
621
		
622
		Matcher editionVolumeMatcher = getMatcher(pEditionVolPart, strReference);
623
		boolean isEditionAndVol = editionVolumeMatcher.find();
624
		
625
		if (editionPhraseMatcher.find()){
626
			editionPart = editionPhraseMatcher.group(0);
627
			int pos = strReference.indexOf(editionPart);
628
			int posEnd = pos + editionPart.length();
629
			if (isEditionAndVol){
630
				posEnd++;  //delete also comma
631
			}
632
			strReference = strReference.substring(0, pos) + strReference.substring(posEnd);
633
			editionPart = editionPart.replaceFirst(pStart + editionSeparator, "").trim();
634
			book.setEdition(editionPart);
635
		}
636
		return strReference;
637
	}
638
	
639
	private IBook parseBook(String reference){
640
		IBook result = refFactory.newBook();
641
		reference = makeEdition(result, reference);
642
		reference = makeVolume(result, reference);
643
		result.setTitle(reference);
644
		return result;
645
	}
646
	
647
	
648
	private ReferenceBase parseArticle(String reference){
649
		//if (articlePatter)
650
		//(type, author, title, volume, editor, series;
651
		ReferenceBase result = refFactory.newArticle();
652
		reference = makeVolume(result, reference);
653
		ReferenceBase inJournal = refFactory.newJournal();
654
		inJournal.setTitle(reference);
655
		result.setInReference(inJournal);
656
		return result;
657
	}
658
	
659
	private ReferenceBase parseBookSection(String reference){
660
		ReferenceBase result = refFactory.newBookSection();
661
		String[] parts = reference.split(referenceAuthorSeparator, 2);
662
		if (parts.length != 2){
663
			logger.warn("Unexpected number of parts");
664
			result.setTitleCache(reference,true);
665
		}else{
666
			String authorString = parts[0];
667
			String bookString = parts[1];
668
			
669
			TeamOrPersonBase<?> authorTeam = author(authorString);
670
			IBook inBook = parseBook(bookString);
671
			inBook.setAuthorTeam(authorTeam);
672
			result.setInBook(inBook);
673
		}
674
		return result;
675
	}
676
	
677
	/**
678
	 * If the publication date of a book section and it's inBook do differ this is usually 
679
	 * caused by the fact that a book has been published during a period, because originally 
680
	 * it consisted of several parts that only later where put together to one book.
681
	 * If so, the book section's publication date may be a point in time (year or month of year)
682
	 * whereas the books publication date may be a period of several years.
683
	 * Therefore a valid nomenclatural reference string should use the book sections 
684
	 * publication date rather then the book's publication date.<BR>
685
	 * This method in general adds the publication date to the book section.
686
	 * An exception exists if the publication date is a period. Then the parser
687
	 * assumes that the nomenclatural reference string does not follow the above rule but
688
	 * the books publication date is set.
689
	 * @param bookSection
690
	 * @param datePublished
691
	 */
692
	private void handleBookSectionYear(IBookSection bookSection, TimePeriod datePublished){
693
		if (datePublished == null || datePublished.getStart() == null || bookSection == null){
694
			return;
695
		}
696
		if (datePublished.isPeriod() && bookSection.getInBook() != null){
697
			bookSection.getInBook().setDatePublished(datePublished);
698
		}else{
699
			bookSection.setDatePublished(datePublished);	
700
		}
701
	}
702
	
703
	
704
	/* (non-Javadoc)
705
	 * @see eu.etaxonomy.cdm.strategy.parser.INonViralNameParser#parseFullName(java.lang.String)
706
	 */
707
	public NonViralName parseFullName(String fullNameString){
708
		return parseFullName(fullNameString, null, null);
709
	}
710
	
711
	
712
	/* (non-Javadoc)
713
	 * @see eu.etaxonomy.cdm.strategy.ITaxonNameParser#parseFullName(java.lang.String, eu.etaxonomy.cdm.model.name.Rank)
714
	 */
715
	public NonViralName parseFullName(String fullNameString, NomenclaturalCode nomCode, Rank rank) {
716
		
717
		if (fullNameString == null){
718
			return null;
719
		}else{
720
			NonViralName result = getNonViralNameInstance(fullNameString, nomCode, rank);
721
			parseFullName(result, fullNameString, rank, false);
722
			return result;
723
		}
724
	}
725
		
726
	
727
	public void parseFullName(NonViralName nameToBeFilled, String fullNameString, Rank rank, boolean makeEmpty) {
728
		//TODO prol. etc.
729
		boolean hasCheckRankProblem = false; //was rank guessed in a previous parsing process?
730
		if (nameToBeFilled == null){
731
			logger.warn("name is null!");
732
		}else{
733
			hasCheckRankProblem = nameToBeFilled.hasProblem(ParserProblem.CheckRank);
734
			nameToBeFilled.removeParsingProblem(ParserProblem.CheckRank);
735
		}
736
		String authorString = null;
737
		
738
		if (fullNameString == null){
739
			return;
740
		}
741
		
742
		if (makeEmpty){
743
			makeEmpty(nameToBeFilled);
744
		}
745
		fullNameString.replaceAll(oWs , " ");
746
		//TODO 
747
		// OLD: fullName = oWsRE.subst(fullName, " "); //substitute multiple whitespaces		   
748
		fullNameString = fullNameString.trim();
749
		
750
		String[] epi = pattern.split(fullNameString);
751
		try {
752
	    	//cultivars //TODO 2 implement cultivars
753
//		    if ( cultivarMarkerRE.match(fullName) ){ funktioniert noch nicht, da es z.B. auch Namen gibt, wie 't Hart
754
//		    	result = parseCultivar(fullName);
755
//		    }
756
		    //hybrids //TODO 2 implement hybrids
757
		    //else 
758
		    if (hybridPattern.matcher(fullNameString).matches() ){
759
		    	nameToBeFilled = parseHybrid(fullNameString);
760
		    }
761
		    else if (genusOrSupraGenusPattern.matcher(fullNameString).matches()){
762
		    	//supraGeneric
763
				if (rank != null && ! hasCheckRankProblem  && (rank.isSupraGeneric()|| rank.isGenus())){
764
					nameToBeFilled.setRank(rank);
765
					nameToBeFilled.setGenusOrUninomial(epi[0]);
766
				} 
767
				//genus or guess rank
768
				else {
769
					rank = guessUninomialRank(nameToBeFilled, epi[0]); 
770
					nameToBeFilled.setRank(rank);
771
					nameToBeFilled.setGenusOrUninomial(epi[0]);
772
					nameToBeFilled.addParsingProblem(ParserProblem.CheckRank);
773
					nameToBeFilled.setProblemStarts(0);
774
					nameToBeFilled.setProblemEnds(epi[0].length());
775
				}
776
				authorString = fullNameString.substring(epi[0].length());
777
			}
778
			//infra genus
779
			else if (infraGenusPattern.matcher(fullNameString).matches()){
780
				nameToBeFilled.setRank(Rank.getRankByAbbreviation(epi[1]));
781
				nameToBeFilled.setGenusOrUninomial(epi[0]);
782
				nameToBeFilled.setInfraGenericEpithet(epi[2]);
783
				authorString = fullNameString.substring(epi[0].length() + 1 + epi[1].length()+ 1 + epi[2].length());
784
			}
785
			//aggr. or group
786
			else if (aggrOrGroupPattern.matcher(fullNameString).matches()){
787
				nameToBeFilled.setRank(Rank.getRankByAbbreviation(epi[2]));
788
				nameToBeFilled.setGenusOrUninomial(epi[0]);
789
				nameToBeFilled.setSpecificEpithet(epi[1]);
790
			}
791
			//species
792
			else if (speciesPattern.matcher(fullNameString).matches()){
793
				nameToBeFilled.setRank(Rank.SPECIES());
794
				nameToBeFilled.setGenusOrUninomial(epi[0]);
795
				nameToBeFilled.setSpecificEpithet(epi[1]);
796
				authorString = fullNameString.substring(epi[0].length() + 1 + epi[1].length());
797
			}
798
			//autonym
799
			else if (autonymPattern.matcher(fullNameString).matches()){
800
				nameToBeFilled.setRank(Rank.getRankByAbbreviation(epi[epi.length - 2]));
801
				nameToBeFilled.setGenusOrUninomial(epi[0]);
802
				nameToBeFilled.setSpecificEpithet(epi[1]);
803
				nameToBeFilled.setInfraSpecificEpithet(epi[epi.length - 1]);
804
				int lenSpecies = 2 + epi[0].length()+epi[1].length();
805
				int lenInfraSpecies =  2 + epi[epi.length - 2].length() + epi[epi.length - 1].length();
806
				authorString = fullNameString.substring(lenSpecies, fullNameString.length() - lenInfraSpecies);
807
			}
808
			//infraSpecies
809
			else if (infraSpeciesPattern.matcher(fullNameString).matches()){
810
				String infraSpecRankEpi = epi[2];
811
				String infraSpecEpi = epi[3];
812
				if ("tax.".equals(infraSpecRankEpi)){
813
					infraSpecRankEpi += " " +  epi[3];
814
					infraSpecEpi = epi[4];
815
				}
816
				nameToBeFilled.setRank(Rank.getRankByAbbreviation(infraSpecRankEpi));
817
				nameToBeFilled.setGenusOrUninomial(epi[0]);
818
				nameToBeFilled.setSpecificEpithet(epi[1]);
819
				nameToBeFilled.setInfraSpecificEpithet(infraSpecEpi);
820
				authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + infraSpecRankEpi.length() + 1 + infraSpecEpi.length());
821
			}//old infraSpecies
822
			else if (oldInfraSpeciesPattern.matcher(fullNameString).matches()){
823
				boolean implemented = false;
824
				if (implemented){
825
					nameToBeFilled.setRank(Rank.getRankByNameOrAbbreviation(epi[2]));
826
					nameToBeFilled.setGenusOrUninomial(epi[0]);
827
					nameToBeFilled.setSpecificEpithet(epi[1]);
828
					//TODO result.setUnnamedNamePhrase(epi[2] + " " + epi[3]);
829
					authorString = fullNameString.substring(epi[0].length()+ 1 + epi[1].length() +1 + epi[2].length() + 1 + epi[3].length());
830
				}else{
831
					nameToBeFilled.addParsingProblem(ParserProblem.OldInfraSpeciesNotSupported);
832
					nameToBeFilled.setTitleCache(fullNameString,true);
833
					// FIXME Quick fix, otherwise search would not deilver results for unparsable names
834
					nameToBeFilled.setNameCache(fullNameString,true);
835
					// END
836
					logger.info("Name string " + fullNameString + " could not be parsed because UnnnamedNamePhrase is not yet implemented!");
837
				}
838
			}
839
			//none
840
			else{ 
841
				nameToBeFilled.addParsingProblem(ParserProblem.UnparsableNamePart);
842
				nameToBeFilled.setTitleCache(fullNameString,true);
843
				// FIXME Quick fix, otherwise search would not deilver results for unparsable names
844
				nameToBeFilled.setNameCache(fullNameString,true);
845
				// END
846
				logger.info("no applicable parsing rule could be found for \"" + fullNameString + "\"");
847
		    }
848
			//authors
849
		    if (nameToBeFilled != null && authorString != null && authorString.trim().length() > 0 ){ 
850
				TeamOrPersonBase<?>[] authors = new TeamOrPersonBase[4];
851
				Integer[] years = new Integer[4];
852
				try {
853
					Class<? extends NonViralName> clazz = nameToBeFilled.getClass();
854
					fullAuthors(authorString, authors, years, clazz);
855
				} catch (StringNotParsableException e) {
856
					nameToBeFilled.addParsingProblem(ParserProblem.UnparsableAuthorPart);
857
					nameToBeFilled.setTitleCache(fullNameString,true);
858
					// FIXME Quick fix, otherwise search would not deilver results for unparsable names
859
					nameToBeFilled.setNameCache(fullNameString,true);
860
					// END
861
					logger.info("no applicable parsing rule could be found for \"" + fullNameString + "\"");;
862
				}
863
				nameToBeFilled.setCombinationAuthorTeam(authors[0]);
864
				nameToBeFilled.setExCombinationAuthorTeam(authors[1]);
865
				nameToBeFilled.setBasionymAuthorTeam(authors[2]);
866
				nameToBeFilled.setExBasionymAuthorTeam(authors[3]);
867
				if (nameToBeFilled instanceof ZoologicalName){
868
					ZoologicalName zooName = (ZoologicalName)nameToBeFilled;
869
					zooName.setPublicationYear(years[0]);
870
					zooName.setOriginalPublicationYear(years[2]);
871
				}
872
			}	
873
			//return
874
			if (nameToBeFilled != null){
875
		    	//return(BotanicalName)result;
876
				return;
877
			}
878
		} catch (UnknownCdmTypeException e) {
879
			nameToBeFilled.addParsingProblem(ParserProblem.RankNotSupported);
880
			nameToBeFilled.setTitleCache(fullNameString,true);
881
			// FIXME Quick fix, otherwise search would not deilver results for unparsable names
882
			nameToBeFilled.setNameCache(fullNameString,true);
883
			// END
884
			logger.info("unknown rank (" + (rank == null? "null":rank) + ") or abbreviation in string " +  fullNameString);
885
			//return result;
886
			return;
887
		}
888
	}
889

    
890
	
891
	
892
	/**
893
	 * Guesses the rank of uninomial depending on the typical endings for ranks
894
	 * @param nameToBeFilled
895
	 * @param string
896
	 */
897
	private Rank guessUninomialRank(NonViralName nameToBeFilled, String uninomial) {
898
		Rank result = Rank.GENUS();
899
		if (nameToBeFilled.isInstanceOf(BotanicalName.class)){
900
			if (false){
901
				//
902
			}else if (uninomial.endsWith("phyta") || uninomial.endsWith("mycota") ){  //plants, fungi
903
				result = Rank.SECTION_BOTANY();
904
			}else if (uninomial.endsWith("bionta")){
905
				result = Rank.SUBKINGDOM();  //TODO
906
			}else if (uninomial.endsWith("phytina")|| uninomial.endsWith("mycotina")  ){  //plants, fungi
907
				result = Rank.SUBSECTION_BOTANY();
908
			}else if (uninomial.endsWith("opsida") || uninomial.endsWith("phyceae") || uninomial.endsWith("mycetes")){  //plants, algae, fungi
909
				result = Rank.CLASS();
910
			}else if (uninomial.endsWith("idae") || uninomial.endsWith("phycidae") || uninomial.endsWith("mycetidae")){ //plants, algae, fungi
911
				result = Rank.SUBCLASS();
912
			}else if (uninomial.endsWith("ales")){
913
				result = Rank.ORDER();
914
			}else if (uninomial.endsWith("ineae")){
915
				result = Rank.SUBORDER();
916
			}else if (uninomial.endsWith("aceae")){
917
					result = Rank.FAMILY();
918
			}else if (uninomial.endsWith("oideae")){
919
				result = Rank.SUBFAMILY();
920
			}else if (uninomial.endsWith("eae")){
921
				result = Rank.TRIBE();
922
			}else if (uninomial.endsWith("inae")){
923
				result = Rank.SUBTRIBE();
924
			}else if (uninomial.endsWith("ota")){
925
				result = Rank.KINGDOM();  //TODO
926
			}
927
		}else if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
928
			if (false){
929
				//
930
			}else if (uninomial.endsWith("oideae")){
931
				result = Rank.SUPERFAMILY();
932
			}else if (uninomial.endsWith("idae")){
933
					result = Rank.FAMILY();
934
			}else if (uninomial.endsWith("inae")){
935
				result = Rank.SUBFAMILY();
936
			}else if (uninomial.endsWith("inae")){
937
				result = Rank.SUBFAMILY();
938
			}else if (uninomial.endsWith("ini")){
939
				result = Rank.TRIBE();
940
			}else if (uninomial.endsWith("ina")){
941
				result = Rank.SUBTRIBE();
942
			}
943
		}else{
944
			//
945
		}
946
		return result;
947
	}
948

    
949
	/**
950
	 * Parses the fullAuthorString
951
	 * @param fullAuthorString
952
	 * @return array of Teams containing the Team[0], 
953
	 * ExTeam[1], BasionymTeam[2], ExBasionymTeam[3]
954
	 */
955
	protected void fullAuthors (String fullAuthorString, TeamOrPersonBase<?>[] authors, Integer[] years, Class<? extends NonViralName> clazz)
956
			throws StringNotParsableException{
957
		fullAuthorString = fullAuthorString.trim();
958
		if (fullAuthorString == null || clazz == null){
959
			return;
960
		}
961
		//Botanic
962
		if ( BotanicalName.class.isAssignableFrom(clazz) ){
963
			if (! fullBotanicAuthorStringPattern.matcher(fullAuthorString).matches() ){
964
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
965
			}
966
		}
967
		//Zoo
968
		else if ( ZoologicalName.class.isAssignableFrom(clazz) ){
969
			if (! fullZooAuthorStringPattern.matcher(fullAuthorString).matches() ){
970
				throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
971
			}
972
		}else {
973
			//TODO
974
			logger.warn ("not yet implemented");
975
			throw new StringNotParsableException("fullAuthorString (" +fullAuthorString+") not parsable: ");
976
		}
977
		fullAuthorsChecked(fullAuthorString, authors, years);
978
	}
979
	
980
	/*
981
	 * like fullTeams but without trim and match check
982
	 */
983
	protected void fullAuthorsChecked (String fullAuthorString, TeamOrPersonBase<?>[] authors, Integer[] years){
984
		int authorTeamStart = 0;
985
		Matcher basionymMatcher = basionymPattern.matcher(fullAuthorString);
986
		
987
		if (basionymMatcher.find(0)){
988
			
989
			String basString = basionymMatcher.group();
990
			basString = basString.replaceFirst(basStart, "");
991
			basString = basString.replaceAll(basEnd, "").trim();
992
			authorTeamStart = basionymMatcher.end(1) + 1;
993
			
994
			TeamOrPersonBase<?>[] basAuthors = new TeamOrPersonBase[2];
995
			Integer[] basYears = new Integer[2];
996
			authorsAndEx(basString, basAuthors, basYears);
997
			authors[2]= basAuthors[0];
998
			years[2] = basYears[0];
999
			authors[3]= basAuthors[1];
1000
			years[3] = basYears[1];
1001
		}
1002
		if (fullAuthorString.length() >= authorTeamStart){
1003
			TeamOrPersonBase<?>[] combinationAuthors = new TeamOrPersonBase[2];;
1004
			Integer[] combinationYears = new Integer[2];
1005
			authorsAndEx(fullAuthorString.substring(authorTeamStart), combinationAuthors, combinationYears);
1006
			authors[0]= combinationAuthors[0] ;
1007
			years[0] = combinationYears[0];
1008
			authors[1]= combinationAuthors[1];
1009
			years[1] = combinationYears[1];
1010
		}
1011
	}
1012
	
1013
	
1014
	/**
1015
	 * Parses the author and ex-author String
1016
	 * @param authorTeamString String representing the author and the ex-author team
1017
	 * @return array of Teams containing the Team[0] and the ExTeam[1]
1018
	 */
1019
	protected void authorsAndEx (String authorTeamString, TeamOrPersonBase<?>[] authors, Integer[] years){
1020
		//TODO noch allgemeiner am anfang durch Replace etc. 
1021
		authorTeamString = authorTeamString.trim();
1022
		authorTeamString = authorTeamString.replaceFirst(oWs + "ex" + oWs, " ex. " ); 
1023
		int authorEnd = authorTeamString.length();
1024
		
1025
		Matcher exAuthorMatcher = exAuthorPattern.matcher(authorTeamString);
1026
		if (exAuthorMatcher.find(0)){
1027
			int exAuthorBegin = exAuthorMatcher.end(0);
1028
			String exString = authorTeamString.substring(exAuthorBegin).trim();
1029
			authorEnd = exAuthorMatcher.start(0);
1030
			authors [1] = author(exString);
1031
		}
1032
		zooOrBotanicAuthor(authorTeamString.substring(0, authorEnd), authors, years );
1033
	}
1034
	
1035
	/**
1036
	 * Parses the authorString and if it matches an botanical or zoological authorTeam it fills
1037
	 * the computes the AuthorTeam and fills it into the first field of the team array. Same applies 
1038
	 * to the year in case of an zoological name. 
1039
	 * @param authorString
1040
	 * @param team
1041
	 * @param year
1042
	 */
1043
	protected void zooOrBotanicAuthor(String authorString, TeamOrPersonBase<?>[] team, Integer[] year){
1044
		if (authorString == null){ 
1045
			return;
1046
		}else if ((authorString = authorString.trim()).length() == 0){
1047
			return;
1048
		}
1049
		Matcher zooAuthorAddidtionMatcher = zooAuthorAddidtionPattern.matcher(authorString);
1050
		if (zooAuthorAddidtionMatcher.find()){
1051
			int index = zooAuthorAddidtionMatcher.start(0); 
1052
			String strYear = authorString.substring(index);
1053
			strYear = strYear.replaceAll(zooAuthorYearSeperator, "").trim();
1054
			year[0] = Integer.valueOf(strYear);
1055
			authorString = authorString.substring(0, index).trim();
1056
		}
1057
		team[0] = author(authorString);
1058
	}
1059
	
1060
	
1061
	/**
1062
	 * Parses an authorTeam String and returns the Team 
1063
	 * !!! TODO (atomization not yet implemented)
1064
	 * @param authorTeamString String representing the author team
1065
	 * @return an Team 
1066
	 */
1067
	protected TeamOrPersonBase<?> author (String authorString){
1068
		if (authorString == null){ 
1069
			return null;
1070
		}else if ((authorString = authorString.trim()).length() == 0){
1071
			return null;
1072
		}else if (! teamSplitterPattern.matcher(authorString).find() && ! authorIsAlwaysTeam){
1073
			//1 Person
1074
			Person result = Person.NewInstance();
1075
			result.setNomenclaturalTitle(authorString);
1076
			return result;
1077
		}else{
1078
			return parsedTeam(authorString);
1079
		} 
1080
		
1081
	}
1082
	
1083
	/**
1084
	 * Parses an authorString (reprsenting a team into the single authors and add
1085
	 * them to the return Team.
1086
	 * @param authorString
1087
	 * @return Team
1088
	 */
1089
	protected Team parsedTeam(String authorString){
1090
		Team result = Team.NewInstance();
1091
		String[] authors = authorString.split(teamSplitter);
1092
		for (String author : authors){
1093
			Person person = Person.NewInstance();
1094
			person.setNomenclaturalTitle(author);
1095
			result.addTeamMember(person); 
1096
		}
1097
		return result;
1098
	}
1099
	
1100

    
1101
	//Parsing of the given full name that has been identified as hybrid already somewhere else.
1102
	private BotanicalName parseHybrid(String fullName){
1103
	    logger.warn("parseHybrid --> function not yet implemented");
1104
	    BotanicalName result = BotanicalName.NewInstance(null);
1105
	    result.setTitleCache(fullName,true);
1106
	    return result;
1107
    }
1108
	
1109
//	// Parsing of the given full name that has been identified as a cultivar already somwhere else.
1110
//	// The ... cv. ... syntax is not covered here as it is not according the rules for naming cultivars.
1111
	public BotanicalName parseCultivar(String fullName)	throws StringNotParsableException{
1112
		CultivarPlantName result = null;
1113
		    String[] words = oWsPattern.split(fullName);
1114
			
1115
		    /* ---------------------------------------------------------------------------------
1116
		     * cultivar
1117
		     * ---------------------------------------------------------------------------------*/
1118
			if (fullName.indexOf(" '") != 0){
1119
				//TODO location of 'xx' is probably not arbitrary
1120
				Matcher cultivarMatcher = cultivarPattern.matcher(fullName);
1121
				if (cultivarMatcher.find()){
1122
					String namePart = fullName.replaceFirst(cultivar, "");
1123
					
1124
					String cultivarPart = cultivarMatcher.group(0).replace("'","").trim();
1125
					//OLD: String cultivarPart = cultivarRE.getParen(0).replace("'","").trim();
1126
					
1127
					result = (CultivarPlantName)parseFullName(namePart);
1128
					result.setCultivarName(cultivarPart);
1129
				}	
1130
			}else if (fullName.indexOf(" cv.") != 0){
1131
				// cv. is old form (not official) 
1132
				throw new StringNotParsableException("Cultivars with only cv. not yet implemented in name parser!");
1133
			}
1134
				
1135
		    /* ---------------------------------------------------------------------------------
1136
		     * cultivar group
1137
		     * ---------------------------------------------------------------------------------
1138
		     */ 
1139
			// TODO in work 
1140
			//Ann. this is not the official way of noting cultivar groups
1141
		    String group = oWs + "Group" + oWs + capitalEpiWord + end;
1142
			Pattern groupRE = Pattern.compile(group);
1143
			Matcher groupMatcher = groupRE.matcher(fullName);
1144
			if (groupMatcher.find()){
1145
		    	if (! words[words.length - 2].equals("group")){
1146
		            throw new StringNotParsableException ("fct ParseHybrid --> term before cultivar group name in " + fullName + " should be 'group'");
1147
		        }else{
1148
		        	
1149
		        	String namePart = fullName.substring(0, groupMatcher.start(0) - 0);
1150
		        	//OLD: String namePart = fullName.substring(0, groupRE.getParenStart(0) - 0);
1151
		        	
1152
		        	String cultivarPart = words[words.length -1];
1153
		        	result = (CultivarPlantName)parseFullName(namePart);
1154
		        	if (result != null){
1155
		        		result.setCultivarName(cultivarPart);
1156
			        	
1157
		        		//OLD: result.setCultivarGroupName(cultivarPart);
1158
		        	}
1159
		        }
1160

    
1161
		    }
1162
//		    // ---------------------------------------------------------------------------------
1163
//		    if ( result = "" ){
1164
//		        return "I: fct ParseCultivar: --> could not parse cultivar " + fullName;
1165
//		    }else{
1166
//		        return result;
1167
	//	    }
1168
			return result; //TODO
1169
	}
1170

    
1171
	
1172
	private void makeEmpty(NonViralName nameToBeFilled){
1173
		nameToBeFilled.setRank(null);
1174
		nameToBeFilled.setTitleCache(null, false);
1175
		nameToBeFilled.setFullTitleCache(null, false);
1176
		nameToBeFilled.setNameCache(null, false);
1177
				
1178
		nameToBeFilled.setAppendedPhrase(null);
1179
		nameToBeFilled.setBasionymAuthorTeam(null);
1180
		nameToBeFilled.setCombinationAuthorTeam(null);
1181
		nameToBeFilled.setExBasionymAuthorTeam(null);
1182
		nameToBeFilled.setExCombinationAuthorTeam(null);
1183
		nameToBeFilled.setAuthorshipCache(null, false);
1184
		
1185
		
1186
		//delete problems except check rank
1187
		makeProblemEmpty(nameToBeFilled);
1188
				
1189
		// TODO ?
1190
		//nameToBeFilled.setHomotypicalGroup(newHomotypicalGroup);
1191

    
1192
		
1193
		nameToBeFilled.setGenusOrUninomial(null);
1194
		nameToBeFilled.setInfraGenericEpithet(null);
1195
		nameToBeFilled.setSpecificEpithet(null);
1196
		nameToBeFilled.setInfraSpecificEpithet(null);
1197
		
1198
		nameToBeFilled.setNomenclaturalMicroReference(null);
1199
		nameToBeFilled.setNomenclaturalReference(null);
1200
		
1201
		nameToBeFilled.setHybridFormula(false);
1202
		nameToBeFilled.setMonomHybrid(false);
1203
		nameToBeFilled.setBinomHybrid(false);
1204
		nameToBeFilled.setTrinomHybrid(false);
1205
		
1206
		if (nameToBeFilled.isInstanceOf(BotanicalName.class)){
1207
			BotanicalName botanicalName = (BotanicalName)nameToBeFilled;
1208
			botanicalName.setAnamorphic(false);
1209
		}
1210
		
1211
		if (nameToBeFilled.isInstanceOf(ZoologicalName.class)){
1212
			ZoologicalName zoologicalName = (ZoologicalName)nameToBeFilled;
1213
			zoologicalName.setBreed(null);
1214
			zoologicalName.setOriginalPublicationYear(null);
1215
			
1216
		}
1217
	}
1218
	
1219
	
1220
    
1221
}
(2-2/5)