2 * Copyright (C) 2007 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
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.
10 package eu
.etaxonomy
.cdm
.io
.specimen
;
13 import java
.util
.ArrayList
;
14 import java
.util
.HashMap
;
15 import java
.util
.HashSet
;
16 import java
.util
.List
;
19 import java
.util
.UUID
;
21 import org
.apache
.log4j
.Logger
;
23 import eu
.etaxonomy
.cdm
.api
.application
.ICdmRepository
;
24 import eu
.etaxonomy
.cdm
.api
.facade
.DerivedUnitFacade
;
25 import eu
.etaxonomy
.cdm
.api
.service
.config
.FindOccurrencesConfigurator
;
26 import eu
.etaxonomy
.cdm
.api
.service
.pager
.Pager
;
27 import eu
.etaxonomy
.cdm
.hibernate
.HibernateProxyHelper
;
28 import eu
.etaxonomy
.cdm
.io
.common
.CdmImportBase
;
29 import eu
.etaxonomy
.cdm
.io
.common
.IImportConfigurator
;
30 import eu
.etaxonomy
.cdm
.io
.specimen
.abcd206
.in
.Identification
;
31 import eu
.etaxonomy
.cdm
.io
.specimen
.abcd206
.in
.SpecimenImportReport
;
32 import eu
.etaxonomy
.cdm
.model
.agent
.AgentBase
;
33 import eu
.etaxonomy
.cdm
.model
.agent
.Institution
;
34 import eu
.etaxonomy
.cdm
.model
.agent
.Person
;
35 import eu
.etaxonomy
.cdm
.model
.agent
.Team
;
36 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
37 import eu
.etaxonomy
.cdm
.model
.common
.IdentifiableSource
;
38 import eu
.etaxonomy
.cdm
.model
.common
.LanguageString
;
39 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionBase
;
40 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionElementSource
;
41 import eu
.etaxonomy
.cdm
.model
.description
.Feature
;
42 import eu
.etaxonomy
.cdm
.model
.description
.IndividualsAssociation
;
43 import eu
.etaxonomy
.cdm
.model
.description
.TaxonDescription
;
44 import eu
.etaxonomy
.cdm
.model
.name
.INonViralName
;
45 import eu
.etaxonomy
.cdm
.model
.name
.NomenclaturalCode
;
46 import eu
.etaxonomy
.cdm
.model
.name
.Rank
;
47 import eu
.etaxonomy
.cdm
.model
.name
.SpecimenTypeDesignation
;
48 import eu
.etaxonomy
.cdm
.model
.name
.SpecimenTypeDesignationStatus
;
49 import eu
.etaxonomy
.cdm
.model
.name
.TaxonName
;
50 import eu
.etaxonomy
.cdm
.model
.name
.TaxonNameFactory
;
51 import eu
.etaxonomy
.cdm
.model
.occurrence
.Collection
;
52 import eu
.etaxonomy
.cdm
.model
.occurrence
.DerivedUnit
;
53 import eu
.etaxonomy
.cdm
.model
.occurrence
.DeterminationEvent
;
54 import eu
.etaxonomy
.cdm
.model
.occurrence
.SpecimenOrObservationBase
;
55 import eu
.etaxonomy
.cdm
.model
.occurrence
.SpecimenOrObservationType
;
56 import eu
.etaxonomy
.cdm
.model
.reference
.ISourceable
;
57 import eu
.etaxonomy
.cdm
.model
.reference
.OriginalSourceBase
;
58 import eu
.etaxonomy
.cdm
.model
.reference
.OriginalSourceType
;
59 import eu
.etaxonomy
.cdm
.model
.reference
.Reference
;
60 import eu
.etaxonomy
.cdm
.model
.reference
.ReferenceFactory
;
61 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
62 import eu
.etaxonomy
.cdm
.model
.taxon
.Synonym
;
63 import eu
.etaxonomy
.cdm
.model
.taxon
.Taxon
;
64 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonBase
;
65 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
66 import eu
.etaxonomy
.cdm
.model
.term
.DefinedTerm
;
67 import eu
.etaxonomy
.cdm
.persistence
.query
.MatchMode
;
68 import eu
.etaxonomy
.cdm
.strategy
.parser
.NonViralNameParserImpl
;
69 import eu
.etaxonomy
.cdm
.strategy
.parser
.ParserProblem
;
70 import eu
.etaxonomy
.cdm
.strategy
.parser
.TimePeriodParser
;
77 public abstract class SpecimenImportBase
<CONFIG
extends IImportConfigurator
, STATE
extends SpecimenImportStateBase
>
78 extends CdmImportBase
<CONFIG
, STATE
> {
80 private static final long serialVersionUID
= 4423065367998125678L;
81 private static final Logger logger
= Logger
.getLogger(SpecimenImportBase
.class);
83 protected static final UUID SPECIMEN_SCAN_TERM
= UUID
.fromString("acda15be-c0e2-4ea8-8783-b9b0c4ad7f03");
85 private static final String COLON
= ":";
87 protected Map
<String
, DefinedTerm
> kindOfUnitsMap
;
92 protected abstract void doInvoke(STATE state
);
95 * Handle a single unit
99 protected abstract void handleSingleUnit(STATE state
, Object item
) ;
103 protected TaxonName
getOrCreateTaxonName(String scientificName
, Rank rank
, boolean preferredFlag
, STATE state
, int unitIndexInAbcdFile
){
104 TaxonName taxonName
= null;
105 SpecimenImportConfiguratorBase
<?
,?
,?
> config
= state
.getConfig();
107 //check atomised name data for rank
108 //new name will be created
109 TaxonName atomisedTaxonName
= null;
110 if (rank
==null && unitIndexInAbcdFile
>=0 && ((state
.getDataHolder().getAtomisedIdentificationList() != null && !state
.getDataHolder().getAtomisedIdentificationList().isEmpty())|| state
.getDataHolder().getAtomisedIdentificationList().size() > 0)) {
111 atomisedTaxonName
= setTaxonNameByType(state
.getDataHolder().getAtomisedIdentificationList().get(unitIndexInAbcdFile
), scientificName
, state
);
112 if(atomisedTaxonName
!=null){
113 rank
= atomisedTaxonName
.getRank();
116 if(config
.isReuseExistingTaxaWhenPossible()){
117 TaxonName parsedName
= atomisedTaxonName
;
118 if(parsedName
==null){
120 parsedName
= parseScientificName(scientificName
, state
, state
.getReport(), rank
);
123 atomisedTaxonName
= parsedName
;
124 if(config
.isIgnoreAuthorship() && parsedName
!=null){// && preferredFlag){
125 // do not ignore authorship for non-preferred names because they need
126 // to be created for the determination history
127 String nameCache
= TaxonName
.castAndDeproxy(parsedName
).getNameCache();
128 List
<TaxonName
> names
= getNameService().findNamesByNameCache(nameCache
, MatchMode
.EXACT
, null);
129 if (!names
.isEmpty()){
130 taxonName
= getBestMatchingName(scientificName
, new ArrayList
<>(names
), state
);
132 if (taxonName
== null && !names
.isEmpty()){
133 taxonName
= names
.get(0);
137 //search for existing names
138 List
<TaxonName
> names
= getNameService().listByTitleWithRestrictions(TaxonName
.class, scientificName
, MatchMode
.EXACT
, null, null, null, null, null);
139 taxonName
= getBestMatchingName(scientificName
, names
, state
);
140 //still nothing found -> try with the atomised name full title cache
141 if(taxonName
==null && atomisedTaxonName
!=null){
142 names
= getNameService().listByTitleWithRestrictions(TaxonName
.class, atomisedTaxonName
.getFullTitleCache(), MatchMode
.EXACT
, null, null, null, null, null);
143 taxonName
= getBestMatchingName(atomisedTaxonName
.getTitleCache(), names
, state
);
144 //still nothing found -> try with the atomised name title cache
146 names
= getNameService().listByTitleWithRestrictions(TaxonName
.class, atomisedTaxonName
.getTitleCache(), MatchMode
.EXACT
, null, null, null, null, null);
147 taxonName
= getBestMatchingName(atomisedTaxonName
.getTitleCache(), names
, state
);
155 if(taxonName
==null && atomisedTaxonName
!=null){
156 taxonName
= atomisedTaxonName
;
157 state
.getReport().addName(taxonName
);
158 logger
.info("Created new taxon name "+taxonName
);
159 if(taxonName
.hasProblem()){
160 state
.getReport().addInfoMessage(String
.format("Created %s with parsing problems", taxonName
));
162 if(!atomisedTaxonName
.getTitleCache().equals(scientificName
)){
163 state
.getReport().addInfoMessage(String
.format("Taxon %s was parsed as %s", scientificName
, atomisedTaxonName
.getTitleCache()));
166 else if(taxonName
==null){
167 //create new taxon name
169 if (state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNAFP
)){
170 taxonName
= TaxonNameFactory
.NewBotanicalInstance(rank
);
171 }else if (state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICZN
)){
172 taxonName
= TaxonNameFactory
.NewZoologicalInstance(rank
);
174 taxonName
= TaxonNameFactory
.NewNonViralInstance(rank
);
176 taxonName
.setFullTitleCache(scientificName
,true);
177 taxonName
.setTitleCache(scientificName
, true);
178 state
.getReport().addName(taxonName
);
179 logger
.info("Created new taxon name "+taxonName
);
181 if (taxonName
!= null){
182 state
.names
.put(taxonName
.getNameCache(), taxonName
);
184 if(!taxonName
.isPersited()) {
185 save(taxonName
, state
);
190 protected TaxonName
getBestMatchingName(String scientificName
, java
.util
.Collection
<TaxonName
> names
, STATE state
){
191 Set
<TaxonName
> namesWithAcceptedTaxa
= new HashSet
<>();
192 List
<TaxonName
> namesWithAcceptedTaxaInClassification
= new ArrayList
<>();
193 for (TaxonName name
: names
) {
194 if(!name
.getTaxa().isEmpty()){
195 Set
<Taxon
> taxa
= name
.getTaxa();
196 for (Taxon taxon
:taxa
){
197 if (!taxon
.getTaxonNodes().isEmpty()){
198 //use only taxa included in a classification
199 for (TaxonNode node
:taxon
.getTaxonNodes()){
200 if (state
.getClassification() != null && node
.getClassification().equals(state
.getClassification())){
201 namesWithAcceptedTaxaInClassification
.add(name
);
203 namesWithAcceptedTaxa
.add(name
);
212 String message
= String
.format("More than one taxon name was found for %s, maybe in other classifications!", scientificName
);
213 //check for names with accepted taxa in classification
214 if(namesWithAcceptedTaxaInClassification
.size()>0){
215 if(namesWithAcceptedTaxaInClassification
.size()>1){
217 state
.getReport().addInfoMessage(message
);
218 logger
.warn(message
);
221 return namesWithAcceptedTaxaInClassification
.iterator().next();
223 //check for any names with accepted taxa
224 if(namesWithAcceptedTaxa
.size()>0){
225 if(namesWithAcceptedTaxa
.size()>1){
227 state
.getReport().addInfoMessage(message
);
228 logger
.warn(message
);
231 return namesWithAcceptedTaxa
.iterator().next();
233 //no names with accepted taxa found -> check accepted taxa of synonyms
234 List
<Taxon
> taxaFromSynonyms
= new ArrayList
<>();
235 for (TaxonName name
: names
) {
236 Set
<TaxonBase
> taxonBases
= name
.getTaxonBases();
237 for (TaxonBase taxonBase
: taxonBases
) {
238 if(taxonBase
.isInstanceOf(Synonym
.class)){
239 Synonym synonym
= HibernateProxyHelper
.deproxy(taxonBase
, Synonym
.class);
240 taxaFromSynonyms
.add(synonym
.getAcceptedTaxon());
244 if(taxaFromSynonyms
.size()>0){
245 if(taxaFromSynonyms
.size()>1){
246 state
.getReport().addInfoMessage(message
);
247 logger
.warn(message
);
250 return taxaFromSynonyms
.iterator().next().getName();
252 //no accepted and no synonyms -> return one of the names and create a new taxon
253 if (names
.isEmpty()){
256 return names
.iterator().next();
260 * Parse automatically the scientific name
261 * @param scientificName the scientific name to parse
262 * @param state the current import state
263 * @param report the import report
264 * @return a parsed name
267 protected TaxonName
parseScientificName(String scientificName
, STATE state
, SpecimenImportReport report
, Rank rank
) {
269 NonViralNameParserImpl nvnpi
= NonViralNameParserImpl
.NewInstance();
270 TaxonName taxonName
= null;
271 boolean problem
= false;
273 if (logger
.isDebugEnabled()){
274 logger
.debug("parseScientificName " + state
.getDataHolder().getNomenclatureCode().toString());
277 if (state
.getDataHolder().getNomenclatureCode() != null && (state
.getDataHolder().getNomenclatureCode().toString().equals("Zoological") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICZN"))) {
278 taxonName
= (TaxonName
)nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICZN
, rank
);
279 if (taxonName
.hasProblem()) {
283 else if (state
.getDataHolder().getNomenclatureCode() != null && (state
.getDataHolder().getNomenclatureCode().toString().equals("Botanical") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICBN") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICNAFP"))) {
284 taxonName
= (TaxonName
)nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNAFP
, rank
);
285 if (taxonName
.hasProblem()) {
289 else if (state
.getDataHolder().getNomenclatureCode() != null && (state
.getDataHolder().getNomenclatureCode().toString().equals("Bacterial") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICBN"))) {
290 taxonName
= (TaxonName
)nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNB
, rank
);
291 if (taxonName
.hasProblem()) {
295 else if (state
.getDataHolder().getNomenclatureCode() != null && (state
.getDataHolder().getNomenclatureCode().toString().equals("Cultivar") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICNCP"))) {
296 taxonName
= (TaxonName
)nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNCP
, rank
);
297 if (taxonName
.hasProblem()) {
302 String message
= String
.format("Parsing problems for %s", scientificName
);
304 for (ParserProblem parserProblem
: taxonName
.getParsingProblems()) {
305 message
+= "\n\t- "+parserProblem
;
308 report
.addInfoMessage(message
);
309 logger
.info(message
);
316 * Create the name without automatic parsing, either because it failed, or because the user deactivated it.
317 * The name is built upon the ABCD fields
318 * @param atomisedMap : the ABCD atomised fields
319 * @param fullName : the full scientific name
321 * @return the corresponding Botanical or Zoological or... name
323 protected TaxonName
setTaxonNameByType(
324 HashMap
<String
, String
> atomisedMap
, String fullName
, STATE state
) {
325 boolean problem
= false;
326 if (logger
.isDebugEnabled()){
327 logger
.debug("settaxonnamebytype " + state
.getDataHolder().getNomenclatureCode().toString());
330 if (state
.getDataHolder().getNomenclatureCode().equals("Zoological") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICZN
.getUuid())) {
331 TaxonName taxonName
= TaxonNameFactory
.NewZoologicalInstance(null);
332 taxonName
.setFullTitleCache(fullName
, true);
333 taxonName
.setGenusOrUninomial(NB(getFromMap(atomisedMap
, "Genus")));
334 taxonName
.setInfraGenericEpithet(NB(getFromMap(atomisedMap
, "SubGenus")));
335 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
,"SpeciesEpithet")));
336 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
,"SubspeciesEpithet")));
338 if (taxonName
.getGenusOrUninomial() != null){
339 taxonName
.setRank(Rank
.GENUS());
342 if (taxonName
.getInfraGenericEpithet() != null){
343 taxonName
.setRank(Rank
.SUBGENUS());
346 if (taxonName
.getSpecificEpithet() != null){
347 taxonName
.setRank(Rank
.SPECIES());
350 if (taxonName
.getInfraSpecificEpithet() != null){
351 taxonName
.setRank(Rank
.SUBSPECIES());
355 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
356 team
= Team
.NewInstance();
357 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"), true);
360 if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
361 team
= Team
.NewInstance();
362 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"), true);
366 taxonName
.setBasionymAuthorship(team
);
369 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
370 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"));
372 else if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
373 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"));
376 if (getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear") != null) {
377 team
= Team
.NewInstance();
378 team
.setTitleCache(getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear"), true);
379 taxonName
.setCombinationAuthorship(team
);
381 if (taxonName
.hasProblem()) {
382 logger
.info("pb ICZN");
389 else if (state
.getDataHolder().getNomenclatureCode().equals("Botanical") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNAFP
.getUuid())) {
390 TaxonName taxonName
= parseScientificName(fullName
, state
, state
.getReport(), null);
391 if (taxonName
!= null){
395 taxonName
= TaxonNameFactory
.NewBotanicalInstance(null);
397 taxonName
.setFullTitleCache(fullName
, true);
398 taxonName
.setGenusOrUninomial(NB(getFromMap(atomisedMap
, "Genus")));
399 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
, "FirstEpithet")));
400 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
, "InfraSpeEpithet")));
402 taxonName
.setRank(Rank
.getRankByName(getFromMap(atomisedMap
, "Rank")));
403 } catch (Exception e
) {
404 if (taxonName
.getInfraSpecificEpithet() != null){
405 taxonName
.setRank(Rank
.SUBSPECIES());
407 else if (taxonName
.getSpecificEpithet() != null){
408 taxonName
.setRank(Rank
.SPECIES());
410 else if (taxonName
.getInfraGenericEpithet() != null){
411 taxonName
.setRank(Rank
.SUBGENUS());
413 else if (taxonName
.getGenusOrUninomial() != null){
414 taxonName
.setRank(Rank
.GENUS());
418 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
419 team
= Team
.NewInstance();
420 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"), true);
421 taxonName
.setBasionymAuthorship(team
);
423 if (getFromMap(atomisedMap
, "AuthorTeam") != null) {
424 team
= Team
.NewInstance();
425 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeam"), true);
426 taxonName
.setCombinationAuthorship(team
);
429 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
430 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"));
432 else if (getFromMap(atomisedMap
, "AuthorTeam") != null) {
433 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeam"));
436 if (getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear") != null) {
437 team
= Team
.NewInstance();
438 team
.setTitleCache(getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear"), true);
439 taxonName
.setCombinationAuthorship(team
);
441 if (taxonName
.hasProblem()) {
442 logger
.info("pb ICBN");
449 else if (state
.getDataHolder().getNomenclatureCode().equals("Bacterial") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNB
.getUuid())) {
450 TaxonName taxonName
= TaxonNameFactory
.NewBacterialInstance(null);
451 taxonName
.setFullTitleCache(fullName
, true);
452 taxonName
.setGenusOrUninomial(getFromMap(atomisedMap
, "Genus"));
453 taxonName
.setInfraGenericEpithet(NB(getFromMap(atomisedMap
, "SubGenus")));
454 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
, "Species")));
455 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
, "SubspeciesEpithet")));
457 if (taxonName
.getGenusOrUninomial() != null){
458 taxonName
.setRank(Rank
.GENUS());
460 else if (taxonName
.getInfraGenericEpithet() != null){
461 taxonName
.setRank(Rank
.SUBGENUS());
463 else if (taxonName
.getSpecificEpithet() != null){
464 taxonName
.setRank(Rank
.SPECIES());
466 else if (taxonName
.getInfraSpecificEpithet() != null){
467 taxonName
.setRank(Rank
.SUBSPECIES());
470 if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
471 Team team
= Team
.NewInstance();
472 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"), true);
473 taxonName
.setCombinationAuthorship(team
);
475 if (getFromMap(atomisedMap
, "ParentheticalAuthorTeamAndYear") != null) {
476 Team team
= Team
.NewInstance();
477 team
.setTitleCache(getFromMap(atomisedMap
, "ParentheticalAuthorTeamAndYear"), true);
478 taxonName
.setBasionymAuthorship(team
);
480 if (taxonName
.hasProblem()) {
481 logger
.info("pb ICNB");
488 else if (state
.getDataHolder().getNomenclatureCode().equals("Cultivar")) {
489 TaxonName taxonName
= TaxonNameFactory
.NewCultivarInstance(null);
491 if (taxonName
.hasProblem()) {
492 logger
.info("pb ICNCP");
502 logger
.info("Problem im setTaxonNameByType ");
503 TaxonName taxonName
= TaxonNameFactory
.NewNonViralInstance(null);
504 taxonName
.setFullTitleCache(fullName
, true);
507 TaxonName tn
= TaxonNameFactory
.NewNonViralInstance(null);
512 * Get a formated string from a hashmap
517 private String
getFromMap(HashMap
<String
, String
> atomisedMap
, String key
) {
519 if (atomisedMap
.containsKey(key
)) {
520 value
= atomisedMap
.get(key
);
524 if (value
!= null && key
.matches(".*Year.*")) {
525 value
= value
.trim();
526 if (value
.matches("[a-z A-Z ]*[0-9]{4}$")) {
527 String tmp
= value
.split("[0-9]{4}$")[0];
528 int year
= Integer
.parseInt(value
.split(tmp
)[1]);
541 catch (Exception e
) {
548 * Very fast and dirty implementation to allow handling of transient objects as described in
549 * https://dev.e-taxonomy.eu/redmine/issues/3726
556 protected UUID
save(CdmBase cdmBase
, SpecimenImportStateBase state
) {
557 ICdmRepository cdmRepository
= state
.getConfig().getCdmAppController();
558 if (cdmRepository
== null){
559 cdmRepository
= this;
562 if (cdmBase
.isInstanceOf(LanguageString
.class)){
563 return cdmRepository
.getTermService().saveLanguageData(CdmBase
.deproxy(cdmBase
, LanguageString
.class));
564 }else if (cdmBase
.isInstanceOf(SpecimenOrObservationBase
.class)){
565 SpecimenOrObservationBase specimen
= CdmBase
.deproxy(cdmBase
, SpecimenOrObservationBase
.class);
567 return cdmRepository
.getOccurrenceService().saveOrUpdate(specimen
);
568 }else if (cdmBase
.isInstanceOf(Reference
.class)){
569 return cdmRepository
.getReferenceService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Reference
.class));
570 }else if (cdmBase
.isInstanceOf(Classification
.class)){
571 return cdmRepository
.getClassificationService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Classification
.class));
572 }else if (cdmBase
.isInstanceOf(AgentBase
.class)){
573 return cdmRepository
.getAgentService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, AgentBase
.class));
574 }else if (cdmBase
.isInstanceOf(Collection
.class)){
575 return cdmRepository
.getCollectionService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Collection
.class));
576 }else if (cdmBase
.isInstanceOf(DescriptionBase
.class)){
577 DescriptionBase description
= CdmBase
.deproxy(cdmBase
, DescriptionBase
.class);
579 return cdmRepository
.getDescriptionService().saveOrUpdate(description
);
580 }else if (cdmBase
.isInstanceOf(TaxonBase
.class)){
581 return cdmRepository
.getTaxonService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonBase
.class));
582 }else if (cdmBase
.isInstanceOf(TaxonName
.class)){
583 return cdmRepository
.getNameService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonName
.class));
584 }else if (cdmBase
.isInstanceOf(TaxonNode
.class)){
585 return cdmRepository
.getTaxonNodeService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonNode
.class));
587 throw new IllegalArgumentException("Class not supported in save method: " + CdmBase
.deproxy(cdmBase
, CdmBase
.class).getClass().getSimpleName());
593 protected SpecimenOrObservationBase
findExistingSpecimen(String unitId
, SpecimenImportStateBase state
){
594 ICdmRepository cdmAppController
= state
.getConfig().getCdmAppController();
595 if(cdmAppController
==null){
596 cdmAppController
= this;
598 FindOccurrencesConfigurator config
= new FindOccurrencesConfigurator();
599 config
.setSignificantIdentifier(unitId
);
600 List
<String
> propertyPaths
= new ArrayList
<>();
601 propertyPaths
.add("derivedFrom.*");
602 config
.setPropertyPaths(propertyPaths
);
603 commitTransaction(state
.getTx());
604 state
.setTx(startTransaction());
606 Pager
<SpecimenOrObservationBase
> existingSpecimens
= cdmAppController
.getOccurrenceService().findByTitle(config
);
607 if(!existingSpecimens
.getRecords().isEmpty()){
608 if(existingSpecimens
.getRecords().size()==1){
609 return existingSpecimens
.getRecords().iterator().next();
613 }catch(NullPointerException e
){
614 logger
.error("searching for existing specimen creates NPE: " + config
.getSignificantIdentifier());
622 protected abstract void importAssociatedUnits(STATE state
, Object item
, DerivedUnitFacade derivedUnitFacade
);
625 * getFacade : get the DerivedUnitFacade based on the recordBasis
628 * @return DerivedUnitFacade
630 protected DerivedUnitFacade
getFacade(STATE state
) {
631 if (logger
.isDebugEnabled()){
632 logger
.info("getFacade()");
634 SpecimenOrObservationType type
= null;
637 if (NB((state
.getDataHolder().getRecordBasis())) != null) {
638 if (state
.getDataHolder().getRecordBasis().toLowerCase().startsWith("s") || state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("specimen")>-1) {// specimen
639 type
= SpecimenOrObservationType
.PreservedSpecimen
;
641 if (state
.getDataHolder().getRecordBasis().toLowerCase().startsWith("o") ||state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("observation")>-1 ) {
642 type
= SpecimenOrObservationType
.Observation
;
644 if (state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("fossil")>-1){
645 type
= SpecimenOrObservationType
.Fossil
;
647 if (state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("living")>-1) {
648 type
= SpecimenOrObservationType
.LivingSpecimen
;
651 logger
.info("The basis of record does not seem to be known: " + state
.getDataHolder().getRecordBasis());
652 type
= SpecimenOrObservationType
.DerivedUnit
;
656 logger
.info("The basis of record is null");
657 type
= SpecimenOrObservationType
.DerivedUnit
;
659 DerivedUnitFacade derivedUnitFacade
= DerivedUnitFacade
.NewInstance(type
);
660 return derivedUnitFacade
;
664 * Look if the Institution does already exist
665 * @param institutionCode: a string with the institutioncode
666 * @param config : the configurator
667 * @return the Institution (existing or new)
669 protected Institution
getInstitution(String institutionCode
, STATE state
) {
670 SpecimenImportConfiguratorBase config
= state
.getConfig();
671 Institution institution
=null;
672 institution
= (Institution
)state
.institutions
.get(institutionCode
);
673 if (institution
!= null){
676 List
<Institution
> institutions
;
678 institutions
= getAgentService().searchInstitutionByCode(institutionCode
);
680 } catch (Exception e
) {
681 institutions
= new ArrayList
<Institution
>();
684 if (institutions
.size() > 0 && config
.isReuseExistingMetaData()) {
685 for (Institution institut
:institutions
){
687 if (institut
.getCode().equalsIgnoreCase(institutionCode
)) {
688 institution
=institut
;
691 }catch(Exception e
){logger
.warn("no institution code in the db");}
694 if (logger
.isDebugEnabled()){
695 if(institution
!=null) {
696 logger
.info("getinstitution " + institution
.toString());
699 if (institution
== null){
700 // create institution
701 institution
= Institution
.NewInstance();
702 institution
.setCode(institutionCode
);
703 institution
.setTitleCache(institutionCode
, true);
704 UUID uuid
= save(institution
, state
);
708 state
.institutions
.put(institutionCode
, institution
);
713 * Look if the Collection does already exist
714 * @param collectionCode
715 * @param collectionCode: a string
716 * @param config : the configurator
717 * @return the Collection (existing or new)
719 protected Collection
getCollection(Institution institution
, String collectionCode
, STATE state
) {
720 SpecimenImportConfiguratorBase config
= state
.getConfig();
721 Collection collection
= null;
722 List
<Collection
> collections
;
723 collection
= (Collection
) state
.collections
.get(collectionCode
);
724 if (collection
!= null){
728 collections
= getCollectionService().searchByCode(collectionCode
);
729 } catch (Exception e
) {
730 collections
= new ArrayList
<Collection
>();
732 if (collections
.size() > 0 && config
.isReuseExistingMetaData()) {
733 for (Collection coll
:collections
){
734 if (coll
.getCode() != null && coll
.getInstitute() != null
735 && coll
.getCode().equalsIgnoreCase(collectionCode
) && coll
.getInstitute().equals(institution
)) {
742 if(collection
== null){
743 collection
=Collection
.NewInstance();
744 collection
.setCode(collectionCode
);
745 collection
.setInstitute(institution
);
746 collection
.setTitleCache(collectionCode
);
747 UUID uuid
= save(collection
, state
);
752 state
.collections
.put(collectionCode
, collection
);
759 * @param citationDetail
762 //FIXME this method is highly critical, because
763 // * it will have serious performance and memory problems with large databases
764 // (databases may easily have >1 Mio source records)
765 // * it does not make sense to search for existing sources and then clone them
766 // we need to search for existing references instead and use them (if exist)
767 // for our new source.
768 protected IdentifiableSource
getIdentifiableSource(Reference reference
, String citationDetail
) {
770 IdentifiableSource sour
= IdentifiableSource
.NewInstance(OriginalSourceType
.Import
,null,null, reference
,citationDetail
);
775 * Add the hierarchy for a Taxon(add higher taxa)
776 * @param classification
777 * @param taxon: a taxon to add as a node
778 * @param state: the ABCD import state
780 protected void addParentTaxon(Taxon taxon
, STATE state
, boolean preferredFlag
, Classification classification
){
781 INonViralName nvname
= taxon
.getName();
782 Rank rank
= nvname
.getRank();
784 Taxon subgenus
=null;
785 Taxon species
= null;
786 Taxon subspecies
= null;
789 if (rank
.isLower(Rank
.GENUS() )){
790 String genusOrUninomial
= nvname
.getGenusOrUninomial();
791 TaxonName taxonName
= getOrCreateTaxonName(genusOrUninomial
, Rank
.GENUS(), preferredFlag
, state
, -1);
792 genus
= getOrCreateTaxonForName(taxonName
, state
);
794 logger
.debug("The genus should not be null " + taxonName
);
797 parent
= linkParentChildNode(null, genus
, classification
, state
);
801 if (rank
.isLower(Rank
.SUBGENUS())){
802 String prefix
= nvname
.getGenusOrUninomial();
803 String name
= nvname
.getInfraGenericEpithet();
805 TaxonName taxonName
= getOrCreateTaxonName(prefix
+" "+name
, Rank
.SUBGENUS(), preferredFlag
, state
, -1);
806 subgenus
= getOrCreateTaxonForName(taxonName
, state
);
808 parent
= linkParentChildNode(genus
, subgenus
, classification
, state
);
811 if (rank
.isLower(Rank
.SPECIES())){
813 String prefix
= nvname
.getGenusOrUninomial();
814 String name
= nvname
.getInfraGenericEpithet();
815 String spe
= nvname
.getSpecificEpithet();
817 TaxonName taxonName
= getOrCreateTaxonName(prefix
+" "+name
+" "+spe
, Rank
.SPECIES(), preferredFlag
, state
, -1);
818 species
= getOrCreateTaxonForName(taxonName
, state
);
820 parent
= linkParentChildNode(subgenus
, species
, classification
, state
);
825 String prefix
= nvname
.getGenusOrUninomial();
826 String name
= nvname
.getSpecificEpithet();
828 TaxonName taxonName
= getOrCreateTaxonName(prefix
+" "+name
, Rank
.SPECIES(), preferredFlag
, state
, -1);
829 species
= getOrCreateTaxonForName(taxonName
, state
);
831 parent
= linkParentChildNode(genus
, species
, classification
, state
);
836 if (rank
.isLower(Rank
.INFRASPECIES())){
837 TaxonName taxonName
= getOrCreateTaxonName(nvname
.getFullTitleCache(), Rank
.SUBSPECIES(), preferredFlag
, state
, -1);
838 subspecies
= getOrCreateTaxonForName(taxonName
, state
);
840 parent
= linkParentChildNode(species
, subspecies
, classification
, state
);
844 //handle cf. and aff. taxa
845 String genusEpithet
= null;
846 if (nvname
.getTitleCache().contains("cf.")){
847 genusEpithet
= nvname
.getTitleCache().substring(0, nvname
.getTitleCache().indexOf("cf."));
848 } else if (nvname
.getTitleCache().contains("aff.")){
849 genusEpithet
= nvname
.getTitleCache().substring(0, nvname
.getTitleCache().indexOf("aff."));
851 if (genusEpithet
!= null){
852 genusEpithet
= genusEpithet
.trim();
853 TaxonName taxonName
= null;
854 if (genusEpithet
.contains(" ")){
855 taxonName
= getOrCreateTaxonName(genusEpithet
, Rank
.SPECIES(), preferredFlag
, state
, -1);
857 taxonName
= getOrCreateTaxonName(genusEpithet
, Rank
.GENUS(), preferredFlag
, state
, -1);
859 genus
= getOrCreateTaxonForName(taxonName
, state
);
861 logger
.debug("The genus should not be null " + taxonName
);
864 parent
= linkParentChildNode(null, genus
, classification
, state
);
868 if (preferredFlag
&& parent
!=taxon
) {
869 linkParentChildNode(parent
, taxon
, classification
, state
);
874 * Link a parent to a child and save it in the current classification
875 * @param parent: the higher Taxon
876 * @param child : the lower (or current) Taxon
877 * return the Taxon from the new created Node
878 * @param classification
881 protected Taxon
linkParentChildNode(Taxon parent
, Taxon child
, Classification classification
, STATE state
) {
882 TaxonNode node
=null;
883 if (parent
!= null) {
884 parent
= (Taxon
) getTaxonService().find(parent
.getUuid());
885 child
= (Taxon
) getTaxonService().find(child
.getUuid());
886 //here we do not have to check if the taxon nodes already exists
887 //this is done by classification.addParentChild()
888 //do not add child node if it already exists
889 if(hasTaxonNodeInClassification(child
, classification
)){
893 node
= classification
.addParentChild(parent
, child
, state
.getRef(), "");
899 logger
.debug("The child should not be null!");
901 child
= (Taxon
) getTaxonService().find(child
.getUuid());
902 //do not add child node if it already exists
903 if(hasTaxonNodeInClassification(child
, classification
)){
907 node
= classification
.addChildTaxon(child
, state
.getRef(), null);
912 state
.getReport().addTaxonNode(node
);
913 return node
.getTaxon();
915 String message
= "Could not create taxon node for " +child
;
916 state
.getReport().addInfoMessage(message
);
917 logger
.warn(message
);
921 protected Taxon
getOrCreateTaxonForName(TaxonName taxonName
, STATE state
){
922 if (taxonName
!= null){
923 Set
<Taxon
> acceptedTaxa
= taxonName
.getTaxa();
924 if(acceptedTaxa
.size()>0){
925 Taxon firstAcceptedTaxon
= acceptedTaxa
.iterator().next();
926 if(acceptedTaxa
.size()>1){
927 String message
= "More than one accepted taxon was found for taxon name: "
928 + taxonName
.getTitleCache() + "!\n" + firstAcceptedTaxon
+ "was chosen for "+state
.getDerivedUnitBase();
929 state
.getReport().addInfoMessage(message
);
930 logger
.warn(message
);
933 return firstAcceptedTaxon
;
937 Set
<TaxonBase
> taxonAndSynonyms
= taxonName
.getTaxonBases();
938 for (TaxonBase taxonBase
: taxonAndSynonyms
) {
939 if(taxonBase
.isInstanceOf(Synonym
.class)){
940 Synonym synonym
= HibernateProxyHelper
.deproxy(taxonBase
, Synonym
.class);
941 Taxon acceptedTaxonOfSynonym
= synonym
.getAcceptedTaxon();
942 if(acceptedTaxonOfSynonym
== null){
943 String message
= "No accepted taxon could be found for taxon name: "
944 + taxonName
.getTitleCache()
946 state
.getReport().addInfoMessage(message
);
947 logger
.warn(message
);
950 return acceptedTaxonOfSynonym
;
955 Taxon taxon
= Taxon
.NewInstance(taxonName
, state
.getRef());
957 state
.getReport().addTaxon(taxon
);
958 logger
.info("Created new taxon "+ taxon
);
965 private boolean hasTaxonNodeInClassification(Taxon taxon
, Classification classification
){
966 if(taxon
.getTaxonNodes()!=null){
967 for (TaxonNode node
: taxon
.getTaxonNodes()){
968 if(node
.getClassification().equals(classification
)){
977 * HandleIdentifications : get the scientific names present in the ABCD
978 * document and store link them with the observation/specimen data
979 * @param state: the current ABCD import state
980 * @param derivedUnitFacade : the current derivedunitfacade
982 protected void handleIdentifications(STATE state
, DerivedUnitFacade derivedUnitFacade
) {
983 SpecimenImportConfiguratorBase config
= state
.getConfig();
986 String scientificName
= "";
987 boolean preferredFlag
= false;
989 if (state
.getDataHolder().getNomenclatureCode() == ""){
990 if (config
.getNomenclaturalCode() != null){
991 if (config
.getNomenclaturalCode() != null){
992 state
.getDataHolder().setNomenclatureCode(config
.getNomenclaturalCode().toString());
998 for (int i
= 0; i
< state
.getDataHolder().getIdentificationList().size(); i
++) {
999 Identification identification
= state
.getDataHolder().getIdentificationList().get(i
);
1000 scientificName
= identification
.getScientificName().replaceAll(" et ", " & ");
1002 String preferred
= identification
.getPreferred();
1003 preferredFlag
= false;
1004 if (preferred
!= null || state
.getDataHolder().getIdentificationList().size()==1){
1005 if (state
.getDataHolder().getIdentificationList().size()==1){
1006 preferredFlag
= true;
1007 }else if (preferred
!= null && (preferred
.equals("1") || preferred
.toLowerCase().indexOf("true") != -1) ) {
1008 preferredFlag
= true;
1012 if (identification
.getCode() != null){
1013 if (identification
.getCode().indexOf(':') != -1) {
1014 state
.getDataHolder().setNomenclatureCode(identification
.getCode().split(COLON
)[1]);
1017 state
.getDataHolder().setNomenclatureCode(identification
.getCode());
1020 TaxonName taxonName
= getOrCreateTaxonName(scientificName
, null, preferredFlag
, state
, i
);
1021 Taxon taxon
= getOrCreateTaxonForName(taxonName
, state
);
1022 addTaxonNode(taxon
, state
,preferredFlag
);
1023 linkDeterminationEvent(state
, taxon
, preferredFlag
, derivedUnitFacade
, identification
.getIdentifier(), identification
.getDate(), identification
.getModifier());
1028 * @param taxon : a taxon to add as a node
1029 * @param state : the ABCD import state
1031 protected void addTaxonNode(Taxon taxon
, STATE state
, boolean preferredFlag
) {
1032 SpecimenImportConfiguratorBase
<?
,?
,?
> config
= state
.getConfig();
1033 logger
.info("link taxon to a taxonNode "+taxon
.getTitleCache());
1034 //only add nodes if not already existing in current classification or default classification
1036 //check if node exists in current classification
1037 //NOTE: we cannot use hasTaxonNodeInClassification() here because we are first creating it here
1038 if (!existsInClassification(taxon
,state
.getClassification(), state
)){
1039 if(config
.isMoveNewTaxaToDefaultClassification()){
1040 //check if node exists in default classification
1041 if (!existsInClassification(taxon
, state
.getDefaultClassification(true), state
)){
1042 addParentTaxon(taxon
, state
, preferredFlag
, state
.getDefaultClassification(true));
1045 //add non-existing taxon to current classification
1046 addParentTaxon(taxon
, state
, preferredFlag
, state
.getClassification());
1053 private boolean existsInClassification(Taxon taxon
, Classification classification
, STATE state
){
1054 boolean exist
= false;
1055 ICdmRepository cdmAppController
= state
.getConfig().getCdmAppController();
1056 if(cdmAppController
==null){
1057 cdmAppController
= this;
1059 if (classification
!= null){
1060 if (!taxon
.getTaxonNodes().isEmpty()){
1061 for (TaxonNode node
:taxon
.getTaxonNodes()){
1062 if (node
.getClassification().equals(classification
)){
1067 // we do not need this because we already searched for taxa in db in the previous steps
1068 // List<UuidAndTitleCache<TaxonNode>> uuidAndTitleCacheOfAllTaxa = cdmAppController.getClassificationService().getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification.getUuid());
1069 // if (uuidAndTitleCacheOfAllTaxa != null){
1070 // for (UuidAndTitleCache p : uuidAndTitleCacheOfAllTaxa){
1072 // if(p.getTitleCache().equals(taxon.getTitleCache())) {
1076 // catch(Exception e){
1077 // logger.warn("TaxonNode doesn't seem to have a taxon");
1086 * join DeterminationEvent to the Taxon Object
1087 * @param state : the ABCD import state
1088 * @param taxon: the current Taxon
1089 * @param preferredFlag :if the current name is preferred
1090 * @param derivedFacade : the derived Unit Facade
1092 @SuppressWarnings("rawtypes")
1093 protected void linkDeterminationEvent(STATE state
, Taxon taxon
, boolean preferredFlag
, DerivedUnitFacade derivedFacade
, String identifierStr
, String dateStr
, String modifier
) {
1094 SpecimenImportConfiguratorBase config
= state
.getConfig();
1095 if (logger
.isDebugEnabled()){
1096 logger
.info("start linkdetermination with taxon:" + taxon
.getUuid()+", "+taxon
);
1099 DeterminationEvent determinationEvent
= DeterminationEvent
.NewInstance();
1100 //determinationEvent.setTaxon(taxon);
1101 determinationEvent
.setTaxonName(taxon
.getName());
1102 determinationEvent
.setPreferredFlag(preferredFlag
);
1105 determinationEvent
.setIdentifiedUnit(state
.getDerivedUnitBase());
1106 if (state
.getPersonStore().get(identifierStr
) != null){
1107 determinationEvent
.setActor((AgentBase
)state
.getPersonStore().get(identifierStr
));
1108 } else if (identifierStr
!= null){
1109 Person identifier
= Person
.NewTitledInstance(identifierStr
);
1110 determinationEvent
.setActor(identifier
);
1112 if (dateStr
!= null){
1113 determinationEvent
.setTimeperiod(TimePeriodParser
.parseString(dateStr
));
1115 if (modifier
!= null){
1116 if (modifier
.equals("cf.")){
1117 determinationEvent
.setModifier(DefinedTerm
.DETERMINATION_MODIFIER_CONFER());
1118 }else if (modifier
.equals("aff.")){
1119 determinationEvent
.setModifier(DefinedTerm
.DETERMINATION_MODIFIER_AFFINIS());
1122 state
.getDerivedUnitBase().addDetermination(determinationEvent
);
1124 if (logger
.isDebugEnabled()){
1125 logger
.debug("NB TYPES INFO: "+ state
.getDataHolder().getStatusList().size());
1127 for (SpecimenTypeDesignationStatus specimenTypeDesignationstatus
: state
.getDataHolder().getStatusList()) {
1128 if (specimenTypeDesignationstatus
!= null) {
1129 if (logger
.isDebugEnabled()){
1130 logger
.debug("specimenTypeDesignationstatus :"+ specimenTypeDesignationstatus
);
1133 ICdmRepository cdmAppController
= config
.getCdmAppController();
1134 if(cdmAppController
== null){
1135 cdmAppController
= this;
1137 specimenTypeDesignationstatus
= HibernateProxyHelper
.deproxy(cdmAppController
.getTermService().find(specimenTypeDesignationstatus
.getUuid()), SpecimenTypeDesignationStatus
.class);
1139 TaxonName name
= taxon
.getName();
1140 SpecimenTypeDesignation designation
= SpecimenTypeDesignation
.NewInstance();
1142 designation
.setTypeStatus(specimenTypeDesignationstatus
);
1143 designation
.setTypeSpecimen(state
.getDerivedUnitBase());
1144 name
.addTypeDesignation(designation
, true);
1147 save(state
.getDerivedUnitBase(), state
);
1149 for (String
[] fullReference
: state
.getDataHolder().getReferenceList()) {
1152 String strReference
=fullReference
[0];
1153 String citationDetail
= fullReference
[1];
1154 String citationURL
= fullReference
[2];
1155 List
<Reference
> references
= getReferenceService().listByTitleWithRestrictions(Reference
.class, "strReference", MatchMode
.EXACT
, null, null, null, null, null);
1157 if (!references
.isEmpty()){
1158 Reference reference
= null;
1159 for (Reference refe
: references
) {
1160 if (refe
.getTitleCache().equalsIgnoreCase(strReference
)) {
1165 if (reference
==null){
1166 reference
= ReferenceFactory
.newGeneric();
1167 reference
.setTitleCache(strReference
, true);
1168 save(reference
, state
);
1170 determinationEvent
.addReference(reference
);
1173 save(state
.getDerivedUnitBase(), state
);
1175 if (config
.isAddIndividualsAssociationsSuchAsSpecimenAndObservations() && preferredFlag
) {
1176 //do not add IndividualsAssociation to non-preferred taxa
1177 if (logger
.isDebugEnabled()){
1178 logger
.debug("isDoCreateIndividualsAssociations");
1181 makeIndividualsAssociation(state
, taxon
, determinationEvent
);
1183 save(state
.getDerivedUnitBase(), state
);
1188 * create and link each association (specimen, observation..) to the accepted taxon
1189 * @param state : the ABCD import state
1190 * @param taxon: the current Taxon
1191 * @param determinationEvent:the determinationevent
1193 protected void makeIndividualsAssociation(STATE state
, Taxon taxon
, DeterminationEvent determinationEvent
) {
1194 SpecimenImportConfiguratorBase
<?
,?
,?
> config
= state
.getConfig();
1195 SpecimenUserInteraction sui
= config
.getSpecimenUserInteraction();
1197 if (logger
.isDebugEnabled()){
1198 logger
.info("MAKE INDIVIDUALS ASSOCIATION");
1201 TaxonDescription taxonDescription
= null;
1202 Set
<TaxonDescription
> descriptions
= taxon
.getDescriptions();
1203 if (state
.getDescriptionPerTaxon(taxon
.getUuid()) != null){
1204 taxonDescription
= state
.getDescriptionPerTaxon(taxon
.getUuid());
1206 if (taxonDescription
== null && !descriptions
.isEmpty() && state
.getConfig().isReuseExistingDescriptiveGroups()){
1207 taxonDescription
= descriptions
.iterator().next();
1210 if (taxonDescription
== null){
1211 taxonDescription
= TaxonDescription
.NewInstance(taxon
, false);
1212 if(sourceNotLinkedToElement(taxonDescription
,state
.getRef(),null)) {
1213 taxonDescription
.addSource(OriginalSourceType
.Import
, null, null, state
.getRef(), null);
1215 state
.setDescriptionGroup(taxonDescription
);
1216 taxon
.addDescription(taxonDescription
);
1219 //PREPARE REFERENCE QUESTIONS
1221 Map
<String
,OriginalSourceBase
<?
>> sourceMap
= new HashMap
<String
, OriginalSourceBase
<?
>>();
1223 List
<IdentifiableSource
> issTmp
= new ArrayList
<>();//getCommonService().list(IdentifiableSource.class, null, null, null, null);
1224 List
<DescriptionElementSource
> issTmp2
= new ArrayList
<>();//getCommonService().list(DescriptionElementSource.class, null, null, null, null);
1226 Set
<OriginalSourceBase
> osbSet
= new HashSet
<OriginalSourceBase
>();
1228 osbSet
.addAll(issTmp2
);
1231 osbSet
.addAll(issTmp
);
1235 addToSourceMap(sourceMap
, osbSet
);
1238 if(sourceNotLinkedToElement(taxonDescription
,state
.getRef(),null)) {
1239 taxonDescription
.addSource(OriginalSourceType
.Import
,null, null, state
.getRef(), null);
1242 state
.setDescriptionGroup(taxonDescription
);
1244 IndividualsAssociation indAssociation
= IndividualsAssociation
.NewInstance();
1245 Feature feature
= makeFeature(state
.getDerivedUnitBase());
1246 indAssociation
.setAssociatedSpecimenOrObservation(state
.getDerivedUnitBase());
1247 indAssociation
.setFeature(feature
);
1249 if(sourceNotLinkedToElement(indAssociation
,state
.getImportReference(state
.getActualAccessPoint()),null)) {
1250 indAssociation
.addSource(OriginalSourceType
.Import
,null, null, state
.getImportReference(state
.getActualAccessPoint()), null);
1252 if(sourceNotLinkedToElement(state
.getDerivedUnitBase(), state
.getImportReference(state
.getActualAccessPoint()),null)) {
1253 state
.getDerivedUnitBase().addSource(OriginalSourceType
.Import
,null, null, state
.getImportReference(state
.getActualAccessPoint()), null);
1255 for (Reference citation
: determinationEvent
.getReferences()) {
1256 if(sourceNotLinkedToElement(indAssociation
,citation
,null))
1258 indAssociation
.addSource(DescriptionElementSource
.NewInstance(OriginalSourceType
.Import
, null, null, citation
, null));
1260 if(sourceNotLinkedToElement(state
.getDerivedUnitBase(), state
.getImportReference(state
.getActualAccessPoint()),null)) {
1261 state
.getDerivedUnitBase().addSource(OriginalSourceType
.Import
,null, null, state
.getImportReference(state
.getActualAccessPoint()), null);
1266 taxonDescription
.addElement(indAssociation
);
1268 save(taxonDescription
, state
);
1270 state
.getReport().addDerivate(state
.getDerivedUnitBase(), config
);
1271 state
.getReport().addIndividualAssociation(taxon
, state
.getDataHolder().getUnitID(), state
.getDerivedUnitBase());
1275 * @param derivedUnitBase2
1280 private boolean sourceNotLinkedToElement(DerivedUnit derivedUnitBase2
, Reference b
, String d
) {
1281 Set
<IdentifiableSource
> linkedSources
= derivedUnitBase2
.getSources();
1282 for (IdentifiableSource is
:linkedSources
){
1283 Reference a
= is
.getCitation();
1284 String c
= is
.getCitationMicroReference();
1286 boolean refMatch
=false;
1287 boolean microMatch
=false;
1290 if (a
==null && b
==null) {
1293 if (a
!=null && b
!=null) {
1294 if (a
.getTitleCache().equalsIgnoreCase(b
.getTitleCache())) {
1298 }catch(Exception e
){}
1302 if (c
==null && d
==null) {
1305 if(c
!=null && d
!=null) {
1306 if(c
.equalsIgnoreCase(d
)) {
1311 catch(Exception e
){}
1313 if (microMatch
&& refMatch
) {
1322 private <T
extends OriginalSourceBase
<?
>> boolean sourceNotLinkedToElement(ISourceable
<T
> sourcable
, Reference reference
, String microReference
) {
1323 Set
<T
> linkedSources
= sourcable
.getSources();
1324 for (T is
:linkedSources
){
1325 Reference unitReference
= is
.getCitation();
1326 String unitMicroReference
= is
.getCitationMicroReference();
1328 boolean refMatch
=false;
1329 boolean microMatch
=false;
1332 if (unitReference
==null && reference
==null) {
1335 if (unitReference
!=null && reference
!=null) {
1336 if (unitReference
.getTitleCache().equalsIgnoreCase(reference
.getTitleCache())) {
1340 }catch(Exception e
){}
1343 if (unitMicroReference
==null && microReference
==null) {
1346 if(unitMicroReference
!=null && microReference
!=null) {
1347 if(unitMicroReference
.equalsIgnoreCase(microReference
)) {
1352 catch(Exception e
){}
1354 if (microMatch
&& refMatch
) {
1362 * look for the Feature object (FieldObs, Specimen,...)
1363 * @param unit : a specimen or obersvation base
1364 * @return the corresponding Feature
1366 private Feature
makeFeature(SpecimenOrObservationBase
<?
> unit
) {
1367 SpecimenOrObservationType type
= unit
.getRecordBasis();
1371 if (type
.isFeatureObservation()){
1372 return Feature
.OBSERVATION();
1373 }else if (type
.isFeatureSpecimen()){
1374 return Feature
.SPECIMEN();
1375 }else if (type
== SpecimenOrObservationType
.DerivedUnit
){
1376 return Feature
.OBSERVATION();
1377 // return getFeature("Specimen or observation");
1379 String message
= "Unhandled record basis '%s' for defining individuals association feature type. Use default.";
1380 logger
.warn(String
.format(message
, type
.getMessage()));
1381 return Feature
.OBSERVATION();
1382 // return getFeature("Specimen or observation");
1392 protected void addToSourceMap(Map
<String
, OriginalSourceBase
<?
>> sourceMap
, Set
<OriginalSourceBase
> osbSet
) {
1393 for( OriginalSourceBase
<?
> osb
:osbSet
) {
1394 if(osb
.getCitation()!=null && osb
.getCitationMicroReference() !=null && !osb
.getCitationMicroReference().isEmpty()) {
1396 sourceMap
.put(osb
.getCitation().getTitleCache()+ "---"+osb
.getCitationMicroReference(),osb
);
1397 }catch(NullPointerException e
){logger
.warn("null pointer problem (no ref?) with "+osb
);}
1398 } else if(osb
.getCitation()!=null){
1400 sourceMap
.put(osb
.getCitation().getTitleCache(),osb
);
1401 }catch(NullPointerException e
){logger
.warn("null pointer problem (no ref?) with "+osb
);}