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
.ICdmApplicationConfiguration
;
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
.Team
;
35 import eu
.etaxonomy
.cdm
.model
.common
.CdmBase
;
36 import eu
.etaxonomy
.cdm
.model
.common
.ISourceable
;
37 import eu
.etaxonomy
.cdm
.model
.common
.IdentifiableSource
;
38 import eu
.etaxonomy
.cdm
.model
.common
.LanguageString
;
39 import eu
.etaxonomy
.cdm
.model
.common
.OriginalSourceBase
;
40 import eu
.etaxonomy
.cdm
.model
.common
.OriginalSourceType
;
41 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionBase
;
42 import eu
.etaxonomy
.cdm
.model
.description
.DescriptionElementSource
;
43 import eu
.etaxonomy
.cdm
.model
.description
.Feature
;
44 import eu
.etaxonomy
.cdm
.model
.description
.IndividualsAssociation
;
45 import eu
.etaxonomy
.cdm
.model
.description
.TaxonDescription
;
46 import eu
.etaxonomy
.cdm
.model
.name
.BacterialName
;
47 import eu
.etaxonomy
.cdm
.model
.name
.BotanicalName
;
48 import eu
.etaxonomy
.cdm
.model
.name
.CultivarPlantName
;
49 import eu
.etaxonomy
.cdm
.model
.name
.INonViralName
;
50 import eu
.etaxonomy
.cdm
.model
.name
.NomenclaturalCode
;
51 import eu
.etaxonomy
.cdm
.model
.name
.NonViralName
;
52 import eu
.etaxonomy
.cdm
.model
.name
.Rank
;
53 import eu
.etaxonomy
.cdm
.model
.name
.SpecimenTypeDesignation
;
54 import eu
.etaxonomy
.cdm
.model
.name
.SpecimenTypeDesignationStatus
;
55 import eu
.etaxonomy
.cdm
.model
.name
.TaxonNameBase
;
56 import eu
.etaxonomy
.cdm
.model
.name
.ZoologicalName
;
57 import eu
.etaxonomy
.cdm
.model
.occurrence
.Collection
;
58 import eu
.etaxonomy
.cdm
.model
.occurrence
.DerivedUnit
;
59 import eu
.etaxonomy
.cdm
.model
.occurrence
.DeterminationEvent
;
60 import eu
.etaxonomy
.cdm
.model
.occurrence
.SpecimenOrObservationBase
;
61 import eu
.etaxonomy
.cdm
.model
.occurrence
.SpecimenOrObservationType
;
62 import eu
.etaxonomy
.cdm
.model
.reference
.Reference
;
63 import eu
.etaxonomy
.cdm
.model
.reference
.ReferenceFactory
;
64 import eu
.etaxonomy
.cdm
.model
.taxon
.Classification
;
65 import eu
.etaxonomy
.cdm
.model
.taxon
.Synonym
;
66 import eu
.etaxonomy
.cdm
.model
.taxon
.Taxon
;
67 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonBase
;
68 import eu
.etaxonomy
.cdm
.model
.taxon
.TaxonNode
;
69 import eu
.etaxonomy
.cdm
.persistence
.dto
.UuidAndTitleCache
;
70 import eu
.etaxonomy
.cdm
.persistence
.query
.MatchMode
;
71 import eu
.etaxonomy
.cdm
.strategy
.parser
.NonViralNameParserImpl
;
72 import eu
.etaxonomy
.cdm
.strategy
.parser
.ParserProblem
;
79 public abstract class SpecimenImportBase
<CONFIG
extends IImportConfigurator
, STATE
extends SpecimenImportStateBase
> extends CdmImportBase
<CONFIG
, STATE
> {
81 private static final long serialVersionUID
= 4423065367998125678L;
82 private static final Logger logger
= Logger
.getLogger(SpecimenImportBase
.class);
83 protected final boolean DEBUG
= true;
85 protected static final UUID SPECIMEN_SCAN_TERM
= UUID
.fromString("acda15be-c0e2-4ea8-8783-b9b0c4ad7f03");
87 private static final String COLON
= ":";
91 protected abstract void doInvoke(STATE state
);
94 * Handle a single unit
98 protected abstract void handleSingleUnit(STATE state
, Object item
) ;
102 protected TaxonNameBase
<?
, ?
> getOrCreateTaxonName(String scientificName
, Rank rank
, boolean preferredFlag
, STATE state
, int unitIndexInAbcdFile
){
103 TaxonNameBase
<?
, ?
> taxonName
= null;
104 SpecimenImportConfiguratorBase
<?
,?
> config
= state
.getConfig();
106 //check atomised name data for rank
107 //new name will be created
108 NonViralName
<?
> atomisedTaxonName
= null;
109 if (rank
==null && unitIndexInAbcdFile
>=0 && ((state
.getDataHolder().getAtomisedIdentificationList() != null && !state
.getDataHolder().getAtomisedIdentificationList().isEmpty())|| state
.getDataHolder().getAtomisedIdentificationList().size() > 0)) {
110 atomisedTaxonName
= setTaxonNameByType(state
.getDataHolder().getAtomisedIdentificationList().get(unitIndexInAbcdFile
), scientificName
, state
);
111 if(atomisedTaxonName
!=null){
112 rank
= atomisedTaxonName
.getRank();
115 if(config
.isReuseExistingTaxaWhenPossible()){
116 NonViralName
<?
> parsedName
= atomisedTaxonName
;
117 if(parsedName
==null){
118 parsedName
= parseScientificName(scientificName
, state
, state
.getReport());
120 atomisedTaxonName
= parsedName
;
121 if(config
.isIgnoreAuthorship() && parsedName
!=null && preferredFlag
){
122 // do not ignore authorship for non-preferred names because they need
123 // to be created for the determination history
124 String nameCache
= parsedName
.getNameCache();
125 List
<NonViralName
> names
= getNameService().findNamesByNameCache(nameCache
, MatchMode
.EXACT
, null);
126 if (!names
.isEmpty()){
127 return getBestMatchingName(scientificName
, new ArrayList
<TaxonNameBase
>(names
), state
);
130 //search for existing names
131 List
<TaxonNameBase
> names
= getNameService().listByTitle(TaxonNameBase
.class, scientificName
, MatchMode
.EXACT
, null, null, null, null, null);
132 taxonName
= getBestMatchingName(scientificName
, names
, state
);
133 //still nothing found -> try with the atomised name full title cache
134 if(taxonName
==null && atomisedTaxonName
!=null){
135 names
= getNameService().listByTitle(TaxonNameBase
.class, atomisedTaxonName
.getFullTitleCache(), MatchMode
.EXACT
, null, null, null, null, null);
136 taxonName
= getBestMatchingName(atomisedTaxonName
.getTitleCache(), names
, state
);
137 //still nothing found -> try with the atomised name title cache
139 names
= getNameService().listByTitle(TaxonNameBase
.class, atomisedTaxonName
.getTitleCache(), MatchMode
.EXACT
, null, null, null, null, null);
140 taxonName
= getBestMatchingName(atomisedTaxonName
.getTitleCache(), names
, state
);
148 if(taxonName
==null && atomisedTaxonName
!=null){
149 taxonName
= atomisedTaxonName
;
150 state
.getReport().addName(taxonName
);
151 logger
.info("Created new taxon name "+taxonName
);
152 if(taxonName
.hasProblem()){
153 state
.getReport().addInfoMessage(String
.format("Created %s with parsing problems", taxonName
));
155 if(!atomisedTaxonName
.getTitleCache().equals(scientificName
)){
156 state
.getReport().addInfoMessage(String
.format("Taxon %s was parsed as %s", scientificName
, atomisedTaxonName
.getTitleCache()));
159 else if(taxonName
==null){
160 //create new taxon name
162 if (state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNAFP
)){
163 taxonName
= TaxonNameBase
.NewBotanicalInstance(rank
);
164 }else if (state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICZN
)){
165 taxonName
= TaxonNameBase
.NewZoologicalInstance(rank
);
167 taxonName
= TaxonNameBase
.NewNonViralInstance(rank
);
169 taxonName
.setFullTitleCache(scientificName
,true);
170 taxonName
.setTitleCache(scientificName
, true);
171 state
.getReport().addName(taxonName
);
172 logger
.info("Created new taxon name "+taxonName
);
174 save(taxonName
, state
);
178 protected TaxonNameBase
<?
, ?
> getBestMatchingName(String scientificName
, java
.util
.Collection
<TaxonNameBase
> names
, STATE state
){
179 List
<TaxonNameBase
> namesWithAcceptedTaxa
= new ArrayList
<>();
180 for (TaxonNameBase name
: names
) {
181 if(!name
.getTaxa().isEmpty()){
182 namesWithAcceptedTaxa
.add(name
);
185 String message
= "More than one taxon name was found for "+scientificName
+"!";
186 //check for names with accepted taxa
187 if(namesWithAcceptedTaxa
.size()>0){
188 if(namesWithAcceptedTaxa
.size()>1){
189 state
.getReport().addInfoMessage(message
);
190 logger
.warn(message
);
193 return namesWithAcceptedTaxa
.iterator().next();
195 //no names with accepted taxa found -> check accepted taxa of synonyms
196 List
<Taxon
> taxaFromSynonyms
= new ArrayList
<>();
197 for (TaxonNameBase name
: names
) {
198 Set
<TaxonBase
> taxonBases
= name
.getTaxonBases();
199 for (TaxonBase taxonBase
: taxonBases
) {
200 if(taxonBase
.isInstanceOf(Synonym
.class)){
201 Synonym synonym
= HibernateProxyHelper
.deproxy(taxonBase
, Synonym
.class);
202 taxaFromSynonyms
.add(synonym
.getAcceptedTaxon());
206 if(taxaFromSynonyms
.size()>0){
207 if(taxaFromSynonyms
.size()>1){
208 state
.getReport().addInfoMessage(message
);
209 logger
.warn(message
);
212 return taxaFromSynonyms
.iterator().next().getName();
217 * Parse automatically the scientific name
218 * @param scientificName the scientific name to parse
219 * @param state the current import state
220 * @param report the import report
221 * @return a parsed name
223 protected NonViralName
<?
> parseScientificName(String scientificName
, STATE state
, SpecimenImportReport report
) {
224 NonViralNameParserImpl nvnpi
= NonViralNameParserImpl
.NewInstance();
225 NonViralName
<?
> taxonName
= null;
226 boolean problem
= false;
229 logger
.info("parseScientificName " + state
.getDataHolder().getNomenclatureCode().toString());
232 if (state
.getDataHolder().getNomenclatureCode().toString().equals("Zoological") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICZN")) {
233 taxonName
= nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICZN
, null);
234 if (taxonName
.hasProblem()) {
238 else if (state
.getDataHolder().getNomenclatureCode().toString().equals("Botanical") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICBN")) {
239 taxonName
= nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNAFP
, null);
240 if (taxonName
.hasProblem()) {
244 else if (state
.getDataHolder().getNomenclatureCode().toString().equals("Bacterial") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICBN")) {
245 taxonName
= nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNB
, null);
246 if (taxonName
.hasProblem()) {
250 else if (state
.getDataHolder().getNomenclatureCode().toString().equals("Cultivar") || state
.getDataHolder().getNomenclatureCode().toString().contains("ICNCP")) {
251 taxonName
= nvnpi
.parseFullName(scientificName
, NomenclaturalCode
.ICNCP
, null);
252 if (taxonName
.hasProblem()) {
257 String message
= String
.format("Parsing problems for %s", scientificName
);
259 for (ParserProblem parserProblem
: taxonName
.getParsingProblems()) {
260 message
+= "\n\t- "+parserProblem
;
263 report
.addInfoMessage(message
);
264 logger
.info(message
);
271 * Create the name without automatic parsing, either because it failed, or because the user deactivated it.
272 * The name is built upon the ABCD fields
273 * @param atomisedMap : the ABCD atomised fields
274 * @param fullName : the full scientific name
276 * @return the corresponding Botanical or Zoological or... name
278 protected NonViralName
<?
> setTaxonNameByType(
279 HashMap
<String
, String
> atomisedMap
, String fullName
, STATE state
) {
280 boolean problem
= false;
282 logger
.info("settaxonnamebytype " + state
.getDataHolder().getNomenclatureCode().toString());
285 if (state
.getDataHolder().getNomenclatureCode().equals("Zoological") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICZN
.getUuid())) {
286 NonViralName
<ZoologicalName
> taxonName
= TaxonNameBase
.NewZoologicalInstance(null);
287 taxonName
.setFullTitleCache(fullName
, true);
288 taxonName
.setGenusOrUninomial(NB(getFromMap(atomisedMap
, "Genus")));
289 taxonName
.setInfraGenericEpithet(NB(getFromMap(atomisedMap
, "SubGenus")));
290 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
,"SpeciesEpithet")));
291 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
,"SubspeciesEpithet")));
293 if (taxonName
.getGenusOrUninomial() != null){
294 taxonName
.setRank(Rank
.GENUS());
297 if (taxonName
.getInfraGenericEpithet() != null){
298 taxonName
.setRank(Rank
.SUBGENUS());
301 if (taxonName
.getSpecificEpithet() != null){
302 taxonName
.setRank(Rank
.SPECIES());
305 if (taxonName
.getInfraSpecificEpithet() != null){
306 taxonName
.setRank(Rank
.SUBSPECIES());
310 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
311 team
= Team
.NewInstance();
312 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"), true);
315 if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
316 team
= Team
.NewInstance();
317 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"), true);
321 taxonName
.setBasionymAuthorship(team
);
324 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
325 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"));
327 else if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
328 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"));
331 if (getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear") != null) {
332 team
= Team
.NewInstance();
333 team
.setTitleCache(getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear"), true);
334 taxonName
.setCombinationAuthorship(team
);
336 if (taxonName
.hasProblem()) {
337 logger
.info("pb ICZN");
344 else if (state
.getDataHolder().getNomenclatureCode().equals("Botanical") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNAFP
.getUuid())) {
345 BotanicalName taxonName
= (BotanicalName
) parseScientificName(fullName
, state
, state
.getReport());
346 if (taxonName
!= null){
350 taxonName
= TaxonNameBase
.NewBotanicalInstance(null);
352 taxonName
.setFullTitleCache(fullName
, true);
353 taxonName
.setGenusOrUninomial(NB(getFromMap(atomisedMap
, "Genus")));
354 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
, "FirstEpithet")));
355 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
, "InfraSpeEpithet")));
357 taxonName
.setRank(Rank
.getRankByName(getFromMap(atomisedMap
, "Rank")));
358 } catch (Exception e
) {
359 if (taxonName
.getInfraSpecificEpithet() != null){
360 taxonName
.setRank(Rank
.SUBSPECIES());
362 else if (taxonName
.getSpecificEpithet() != null){
363 taxonName
.setRank(Rank
.SPECIES());
365 else if (taxonName
.getInfraGenericEpithet() != null){
366 taxonName
.setRank(Rank
.SUBGENUS());
368 else if (taxonName
.getGenusOrUninomial() != null){
369 taxonName
.setRank(Rank
.GENUS());
373 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
374 team
= Team
.NewInstance();
375 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"), true);
376 taxonName
.setBasionymAuthorship(team
);
378 if (getFromMap(atomisedMap
, "AuthorTeam") != null) {
379 team
= Team
.NewInstance();
380 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeam"), true);
381 taxonName
.setCombinationAuthorship(team
);
384 if (getFromMap(atomisedMap
, "AuthorTeamParenthesis") != null) {
385 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeamParenthesis"));
387 else if (getFromMap(atomisedMap
, "AuthorTeam") != null) {
388 taxonName
.setAuthorshipCache(getFromMap(atomisedMap
, "AuthorTeam"));
391 if (getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear") != null) {
392 team
= Team
.NewInstance();
393 team
.setTitleCache(getFromMap(atomisedMap
, "CombinationAuthorTeamAndYear"), true);
394 taxonName
.setCombinationAuthorship(team
);
396 if (taxonName
.hasProblem()) {
397 logger
.info("pb ICBN");
404 else if (state
.getDataHolder().getNomenclatureCode().equals("Bacterial") || state
.getDataHolder().getNomenclatureCode().equals(NomenclaturalCode
.ICNB
.getUuid())) {
405 NonViralName
<BacterialName
> taxonName
= TaxonNameBase
.NewBacterialInstance(null);
406 taxonName
.setFullTitleCache(fullName
, true);
407 taxonName
.setGenusOrUninomial(getFromMap(atomisedMap
, "Genus"));
408 taxonName
.setInfraGenericEpithet(NB(getFromMap(atomisedMap
, "SubGenus")));
409 taxonName
.setSpecificEpithet(NB(getFromMap(atomisedMap
, "Species")));
410 taxonName
.setInfraSpecificEpithet(NB(getFromMap(atomisedMap
, "SubspeciesEpithet")));
412 if (taxonName
.getGenusOrUninomial() != null){
413 taxonName
.setRank(Rank
.GENUS());
415 else if (taxonName
.getInfraGenericEpithet() != null){
416 taxonName
.setRank(Rank
.SUBGENUS());
418 else if (taxonName
.getSpecificEpithet() != null){
419 taxonName
.setRank(Rank
.SPECIES());
421 else if (taxonName
.getInfraSpecificEpithet() != null){
422 taxonName
.setRank(Rank
.SUBSPECIES());
425 if (getFromMap(atomisedMap
, "AuthorTeamAndYear") != null) {
426 Team team
= Team
.NewInstance();
427 team
.setTitleCache(getFromMap(atomisedMap
, "AuthorTeamAndYear"), true);
428 taxonName
.setCombinationAuthorship(team
);
430 if (getFromMap(atomisedMap
, "ParentheticalAuthorTeamAndYear") != null) {
431 Team team
= Team
.NewInstance();
432 team
.setTitleCache(getFromMap(atomisedMap
, "ParentheticalAuthorTeamAndYear"), true);
433 taxonName
.setBasionymAuthorship(team
);
435 if (taxonName
.hasProblem()) {
436 logger
.info("pb ICNB");
443 else if (state
.getDataHolder().getNomenclatureCode().equals("Cultivar")) {
444 CultivarPlantName taxonName
= CultivarPlantName
.NewInstance(null);
446 if (taxonName
.hasProblem()) {
447 logger
.info("pb ICNCP");
457 logger
.info("Problem im setTaxonNameByType ");
458 NonViralName
<?
> taxonName
= TaxonNameBase
.NewNonViralInstance(null);
459 taxonName
.setFullTitleCache(fullName
, true);
462 NonViralName
<?
> tn
= TaxonNameBase
.NewNonViralInstance(null);
467 * Get a formated string from a hashmap
472 private String
getFromMap(HashMap
<String
, String
> atomisedMap
, String key
) {
474 if (atomisedMap
.containsKey(key
)) {
475 value
= atomisedMap
.get(key
);
479 if (value
!= null && key
.matches(".*Year.*")) {
480 value
= value
.trim();
481 if (value
.matches("[a-z A-Z ]*[0-9]{4}$")) {
482 String tmp
= value
.split("[0-9]{4}$")[0];
483 int year
= Integer
.parseInt(value
.split(tmp
)[1]);
496 catch (Exception e
) {
503 * Very fast and dirty implementation to allow handling of transient objects as described in
504 * https://dev.e-taxonomy.eu/trac/ticket/3726
511 protected UUID
save(CdmBase cdmBase
, SpecimenImportStateBase state
) {
512 ICdmApplicationConfiguration cdmRepository
= state
.getConfig().getCdmAppController();
513 if (cdmRepository
== null){
514 cdmRepository
= this;
517 if (cdmBase
.isInstanceOf(LanguageString
.class)){
518 return cdmRepository
.getTermService().saveLanguageData(CdmBase
.deproxy(cdmBase
, LanguageString
.class));
519 }else if (cdmBase
.isInstanceOf(SpecimenOrObservationBase
.class)){
520 return cdmRepository
.getOccurrenceService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, SpecimenOrObservationBase
.class));
521 }else if (cdmBase
.isInstanceOf(Reference
.class)){
522 return cdmRepository
.getReferenceService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Reference
.class));
523 }else if (cdmBase
.isInstanceOf(Classification
.class)){
524 return cdmRepository
.getClassificationService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Classification
.class));
525 }else if (cdmBase
.isInstanceOf(AgentBase
.class)){
526 return cdmRepository
.getAgentService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, AgentBase
.class));
527 }else if (cdmBase
.isInstanceOf(Collection
.class)){
528 return cdmRepository
.getCollectionService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, Collection
.class));
529 }else if (cdmBase
.isInstanceOf(DescriptionBase
.class)){
530 return cdmRepository
.getDescriptionService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, DescriptionBase
.class));
531 }else if (cdmBase
.isInstanceOf(TaxonBase
.class)){
532 return cdmRepository
.getTaxonService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonBase
.class));
533 }else if (cdmBase
.isInstanceOf(TaxonNameBase
.class)){
534 return cdmRepository
.getNameService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonNameBase
.class));
535 }else if (cdmBase
.isInstanceOf(TaxonNode
.class)){
536 return cdmRepository
.getTaxonNodeService().saveOrUpdate(CdmBase
.deproxy(cdmBase
, TaxonNode
.class));
538 throw new IllegalArgumentException("Class not supported in save method: " + CdmBase
.deproxy(cdmBase
, CdmBase
.class).getClass().getSimpleName());
544 protected SpecimenOrObservationBase
findExistingSpecimen(String unitId
, SpecimenImportStateBase state
){
545 ICdmApplicationConfiguration cdmAppController
= state
.getConfig().getCdmAppController();
546 if(cdmAppController
==null){
547 cdmAppController
= this;
549 FindOccurrencesConfigurator config
= new FindOccurrencesConfigurator();
550 config
.setSignificantIdentifier(unitId
);
551 Pager
<SpecimenOrObservationBase
> existingSpecimens
= cdmAppController
.getOccurrenceService().findByTitle(config
);
552 if(!existingSpecimens
.getRecords().isEmpty()){
553 if(existingSpecimens
.getRecords().size()==1){
554 return existingSpecimens
.getRecords().iterator().next();
560 protected abstract void importAssociatedUnits(STATE state
, Object item
, DerivedUnitFacade derivedUnitFacade
);
563 * getFacade : get the DerivedUnitFacade based on the recordBasis
566 * @return DerivedUnitFacade
568 protected DerivedUnitFacade
getFacade(STATE state
) {
570 logger
.info("getFacade()");
572 SpecimenOrObservationType type
= null;
575 if (NB((state
.getDataHolder().getRecordBasis())) != null) {
576 if (state
.getDataHolder().getRecordBasis().toLowerCase().startsWith("s") || state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("specimen")>-1) {// specimen
577 type
= SpecimenOrObservationType
.PreservedSpecimen
;
579 if (state
.getDataHolder().getRecordBasis().toLowerCase().startsWith("o") ||state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("observation")>-1 ) {
580 type
= SpecimenOrObservationType
.Observation
;
582 if (state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("fossil")>-1){
583 type
= SpecimenOrObservationType
.Fossil
;
585 if (state
.getDataHolder().getRecordBasis().toLowerCase().indexOf("living")>-1) {
586 type
= SpecimenOrObservationType
.LivingSpecimen
;
589 logger
.info("The basis of record does not seem to be known: " + state
.getDataHolder().getRecordBasis());
590 type
= SpecimenOrObservationType
.DerivedUnit
;
594 logger
.info("The basis of record is null");
595 type
= SpecimenOrObservationType
.DerivedUnit
;
597 DerivedUnitFacade derivedUnitFacade
= DerivedUnitFacade
.NewInstance(type
);
598 return derivedUnitFacade
;
602 * Look if the Institution does already exist
603 * @param institutionCode: a string with the institutioncode
604 * @param config : the configurator
605 * @return the Institution (existing or new)
607 protected Institution
getInstitution(String institutionCode
, STATE state
) {
608 SpecimenImportConfiguratorBase config
= state
.getConfig();
609 Institution institution
=null;
610 institution
= (Institution
)state
.institutions
.get(institutionCode
);
611 if (institution
!= null){
614 List
<Institution
> institutions
;
616 institutions
= getAgentService().searchInstitutionByCode(institutionCode
);
618 } catch (Exception e
) {
619 institutions
= new ArrayList
<Institution
>();
622 if (institutions
.size() > 0 && config
.isReuseExistingMetaData()) {
623 for (Institution institut
:institutions
){
625 if (institut
.getCode().equalsIgnoreCase(institutionCode
)) {
626 institution
=institut
;
629 }catch(Exception e
){logger
.warn("no institution code in the db");}
633 if(institution
!=null) {
634 logger
.info("getinstitution " + institution
.toString());
637 if (institution
== null){
638 // create institution
639 institution
= Institution
.NewInstance();
640 institution
.setCode(institutionCode
);
641 institution
.setTitleCache(institutionCode
, true);
642 UUID uuid
= save(institution
, state
);
646 state
.institutions
.put(institutionCode
, institution
);
651 * Look if the Collection does already exist
652 * @param collectionCode
653 * @param collectionCode: a string
654 * @param config : the configurator
655 * @return the Collection (existing or new)
657 protected Collection
getCollection(Institution institution
, String collectionCode
, STATE state
) {
658 SpecimenImportConfiguratorBase config
= state
.getConfig();
659 Collection collection
= null;
660 List
<Collection
> collections
;
661 collection
= (Collection
) state
.collections
.get(collectionCode
);
662 if (collection
!= null){
666 collections
= getCollectionService().searchByCode(collectionCode
);
667 } catch (Exception e
) {
668 collections
= new ArrayList
<Collection
>();
670 if (collections
.size() > 0 && config
.isReuseExistingMetaData()) {
671 for (Collection coll
:collections
){
672 if (coll
.getCode() != null && coll
.getInstitute() != null
673 && coll
.getCode().equalsIgnoreCase(collectionCode
) && coll
.getInstitute().equals(institution
)) {
680 if(collection
== null){
681 collection
=Collection
.NewInstance();
682 collection
.setCode(collectionCode
);
683 collection
.setInstitute(institution
);
684 collection
.setTitleCache(collectionCode
);
685 UUID uuid
= save(collection
, state
);
690 state
.collections
.put(collectionCode
, collection
);
697 * @param citationDetail
700 //FIXME this method is highly critical, because
701 // * it will have serious performance and memory problems with large databases
702 // (databases may easily have >1 Mio source records)
703 // * it does not make sense to search for existing sources and then clone them
704 // we need to search for existing references instead and use them (if exist)
705 // for our new source.
706 protected IdentifiableSource
getIdentifiableSource(Reference reference
, String citationDetail
) {
708 /* List<IdentifiableSource> issTmp = getCommonService().list(IdentifiableSource.class, null, null, null, null);
711 if (reference != null){
713 for (OriginalSourceBase<?> osb: issTmp){
714 if (osb.getCitation() != null && osb.getCitation().getTitleCache().equalsIgnoreCase(reference.getTitleCache())){
715 String osbDetail = osb.getCitationMicroReference();
716 if ((StringUtils.isBlank(osbDetail) && StringUtils.isBlank(citationDetail))
717 || (osbDetail != null && osbDetail.equalsIgnoreCase(citationDetail)) ) {
718 // System.out.println("REFERENCE FOUND RETURN EXISTING SOURCE");
719 return (IdentifiableSource) osb.clone();
723 } catch (CloneNotSupportedException e) {
724 throw new RuntimeException(e);
725 } catch (Exception e1){
726 e1.printStackTrace();
730 IdentifiableSource sour
= IdentifiableSource
.NewInstance(OriginalSourceType
.Import
,null,null, reference
,citationDetail
);
735 * Add the hierarchy for a Taxon(add higher taxa)
736 * @param classification
737 * @param taxon: a taxon to add as a node
738 * @param state: the ABCD import state
740 protected void addParentTaxon(Taxon taxon
, STATE state
, boolean preferredFlag
, Classification classification
){
741 INonViralName nvname
= taxon
.getName();
742 Rank rank
= nvname
.getRank();
744 Taxon subgenus
=null;
745 Taxon species
= null;
746 Taxon subspecies
= null;
749 if (rank
.isLower(Rank
.GENUS() )){
750 String genusOrUninomial
= nvname
.getGenusOrUninomial();
751 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(genusOrUninomial
, Rank
.GENUS(), preferredFlag
, state
, -1);
752 genus
= getOrCreateTaxonForName(taxonName
, state
);
754 parent
= linkParentChildNode(null, genus
, classification
, state
);
758 if (rank
.isLower(Rank
.SUBGENUS())){
759 String prefix
= nvname
.getGenusOrUninomial();
760 String name
= nvname
.getInfraGenericEpithet();
762 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(prefix
+" "+name
, Rank
.SUBGENUS(), preferredFlag
, state
, -1);
763 subgenus
= getOrCreateTaxonForName(taxonName
, state
);
765 parent
= linkParentChildNode(genus
, subgenus
, classification
, state
);
768 if (rank
.isLower(Rank
.SPECIES())){
770 String prefix
= nvname
.getGenusOrUninomial();
771 String name
= nvname
.getInfraGenericEpithet();
772 String spe
= nvname
.getSpecificEpithet();
774 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(prefix
+" "+name
+" "+spe
, Rank
.SPECIES(), preferredFlag
, state
, -1);
775 species
= getOrCreateTaxonForName(taxonName
, state
);
777 parent
= linkParentChildNode(subgenus
, species
, classification
, state
);
782 String prefix
= nvname
.getGenusOrUninomial();
783 String name
= nvname
.getSpecificEpithet();
785 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(prefix
+" "+name
, Rank
.SPECIES(), preferredFlag
, state
, -1);
786 species
= getOrCreateTaxonForName(taxonName
, state
);
788 parent
= linkParentChildNode(genus
, species
, classification
, state
);
793 if (rank
.isLower(Rank
.INFRASPECIES())){
794 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(nvname
.getFullTitleCache(), Rank
.SUBSPECIES(), preferredFlag
, state
, -1);
795 subspecies
= getOrCreateTaxonForName(taxonName
, state
);
797 parent
= linkParentChildNode(species
, subspecies
, classification
, state
);
801 if (preferredFlag
&& parent
!=taxon
) {
802 linkParentChildNode(parent
, taxon
, classification
, state
);
807 * Link a parent to a child and save it in the current classification
808 * @param parent: the higher Taxon
809 * @param child : the lower (or current) Taxon
810 * return the Taxon from the new created Node
811 * @param classification
814 protected Taxon
linkParentChildNode(Taxon parent
, Taxon child
, Classification classification
, STATE state
) {
815 TaxonNode node
=null;
816 if (parent
!= null) {
817 parent
= (Taxon
) getTaxonService().find(parent
.getUuid());
818 child
= (Taxon
) getTaxonService().find(child
.getUuid());
819 //here we do not have to check if the taxon nodes already exists
820 //this is done by classification.addParentChild()
821 //do not add child node if it already exists
822 if(hasTaxonNodeInClassification(child
, classification
)){
826 node
= classification
.addParentChild(parent
, child
, state
.getRef(), "");
831 child
= (Taxon
) getTaxonService().find(child
.getUuid());
832 //do not add child node if it already exists
833 if(hasTaxonNodeInClassification(child
, classification
)){
837 node
= classification
.addChildTaxon(child
, state
.getRef(), null);
842 state
.getReport().addTaxonNode(node
);
843 return node
.getTaxon();
845 String message
= "Could not create taxon node for " +child
;
846 state
.getReport().addInfoMessage(message
);
847 logger
.warn(message
);
851 protected Taxon
getOrCreateTaxonForName(TaxonNameBase
<?
, ?
> taxonNameBase
, STATE state
){
853 Set
<Taxon
> acceptedTaxa
= taxonNameBase
.getTaxa();
854 if(acceptedTaxa
.size()>0){
855 Taxon firstAcceptedTaxon
= acceptedTaxa
.iterator().next();
856 if(acceptedTaxa
.size()>1){
857 String message
= "More than one accepted taxon was found for taxon name: "
858 + taxonNameBase
.getTitleCache() + "!\n" + firstAcceptedTaxon
+ "was chosen for "+state
.getDerivedUnitBase();
859 state
.getReport().addInfoMessage(message
);
860 logger
.warn(message
);
863 return firstAcceptedTaxon
;
867 Set
<TaxonBase
> taxonAndSynonyms
= taxonNameBase
.getTaxonBases();
868 for (TaxonBase taxonBase
: taxonAndSynonyms
) {
869 if(taxonBase
.isInstanceOf(Synonym
.class)){
870 Synonym synonym
= HibernateProxyHelper
.deproxy(taxonBase
, Synonym
.class);
871 Taxon acceptedTaxonOfSynonym
= synonym
.getAcceptedTaxon();
872 if(acceptedTaxonOfSynonym
== null){
873 String message
= "No accepted taxon could be found for taxon name: "
874 + taxonNameBase
.getTitleCache()
876 state
.getReport().addInfoMessage(message
);
877 logger
.warn(message
);
880 return acceptedTaxonOfSynonym
;
885 Taxon taxon
= Taxon
.NewInstance(taxonNameBase
, state
.getRef());
887 state
.getReport().addTaxon(taxon
);
888 logger
.info("Created new taxon "+ taxon
);
892 private boolean hasTaxonNodeInClassification(Taxon taxon
, Classification classification
){
893 if(taxon
.getTaxonNodes()!=null){
894 for (TaxonNode node
: taxon
.getTaxonNodes()){
895 if(node
.getClassification().equals(classification
)){
904 * HandleIdentifications : get the scientific names present in the ABCD
905 * document and store link them with the observation/specimen data
906 * @param state: the current ABCD import state
907 * @param derivedUnitFacade : the current derivedunitfacade
909 protected void handleIdentifications(STATE state
, DerivedUnitFacade derivedUnitFacade
) {
910 SpecimenImportConfiguratorBase config
= state
.getConfig();
913 String scientificName
= "";
914 boolean preferredFlag
= false;
916 if (state
.getDataHolder().getNomenclatureCode() == ""){
917 if (config
.getNomenclaturalCode() != null){
918 if (config
.getNomenclaturalCode() != null){
919 state
.getDataHolder().setNomenclatureCode(config
.getNomenclaturalCode().toString());
924 for (int i
= 0; i
< state
.getDataHolder().getIdentificationList().size(); i
++) {
925 Identification identification
= state
.getDataHolder().getIdentificationList().get(i
);
926 scientificName
= identification
.getScientificName().replaceAll(" et ", " & ");
928 String preferred
= identification
.getPreferred();
929 if (preferred
.equals("1") || preferred
.toLowerCase().indexOf("true") != -1 || state
.getDataHolder().getIdentificationList().size()==1) {
930 preferredFlag
= true;
933 preferredFlag
= false;
935 if (identification
.getCode() != null){
936 if (identification
.getCode().indexOf(':') != -1) {
937 state
.getDataHolder().setNomenclatureCode(identification
.getCode().split(COLON
)[1]);
940 state
.getDataHolder().setNomenclatureCode(identification
.getCode());
943 TaxonNameBase
<?
,?
> taxonName
= getOrCreateTaxonName(scientificName
, null, preferredFlag
, state
, i
);
944 Taxon taxon
= getOrCreateTaxonForName(taxonName
, state
);
945 addTaxonNode(taxon
, state
,preferredFlag
);
946 linkDeterminationEvent(state
, taxon
, preferredFlag
, derivedUnitFacade
);
951 * @param taxon : a taxon to add as a node
952 * @param state : the ABCD import state
954 protected void addTaxonNode(Taxon taxon
, STATE state
, boolean preferredFlag
) {
955 SpecimenImportConfiguratorBase config
= state
.getConfig();
956 logger
.info("link taxon to a taxonNode "+taxon
.getTitleCache());
957 //only add nodes if not already existing in current classification or default classification
959 //check if node exists in current classification
960 //NOTE: we cannot use hasTaxonNodeInClassification() here because we are first creating it here
961 if (!existsInClassification(taxon
,state
.getClassification(), state
)){
962 if(config
.isMoveNewTaxaToDefaultClassification()){
963 //check if node exists in default classification
964 if (!existsInClassification(taxon
, state
.getDefaultClassification(), state
)){
965 addParentTaxon(taxon
, state
, preferredFlag
, state
.getDefaultClassification());
969 //add non-existing taxon to current classification
970 addParentTaxon(taxon
, state
, preferredFlag
, state
.getClassification());
976 private boolean existsInClassification(Taxon taxon
, Classification classification
, STATE state
){
977 boolean exist
= false;
978 ICdmApplicationConfiguration cdmAppController
= state
.getConfig().getCdmAppController();
979 if(cdmAppController
==null){
980 cdmAppController
= this;
982 if (classification
!= null){
983 List
<UuidAndTitleCache
<TaxonNode
>> uuidAndTitleCacheOfAllTaxa
= cdmAppController
.getClassificationService().getTaxonNodeUuidAndTitleCacheOfAcceptedTaxaByClassification(classification
.getUuid());
984 if (uuidAndTitleCacheOfAllTaxa
!= null){
985 for (UuidAndTitleCache p
: uuidAndTitleCacheOfAllTaxa
){
987 if(p
.getTitleCache().equals(taxon
.getTitleCache())) {
992 logger
.warn("TaxonNode doesn't seem to have a taxon");
1001 * join DeterminationEvent to the Taxon Object
1002 * @param state : the ABCD import state
1003 * @param taxon: the current Taxon
1004 * @param preferredFlag :if the current name is preferred
1005 * @param derivedFacade : the derived Unit Facade
1007 @SuppressWarnings("rawtypes")
1008 protected void linkDeterminationEvent(STATE state
, Taxon taxon
, boolean preferredFlag
, DerivedUnitFacade derivedFacade
) {
1009 SpecimenImportConfiguratorBase config
= state
.getConfig();
1011 logger
.info("start linkdetermination with taxon:" + taxon
.getUuid()+", "+taxon
);
1014 DeterminationEvent determinationEvent
= DeterminationEvent
.NewInstance();
1015 determinationEvent
.setTaxonName(taxon
.getName());
1016 determinationEvent
.setPreferredFlag(preferredFlag
);
1018 determinationEvent
.setIdentifiedUnit(state
.getDerivedUnitBase());
1019 state
.getDerivedUnitBase().addDetermination(determinationEvent
);
1022 logger
.info("NB TYPES INFO: "+ state
.getDataHolder().getStatusList().size());
1024 for (SpecimenTypeDesignationStatus specimenTypeDesignationstatus
: state
.getDataHolder().getStatusList()) {
1025 if (specimenTypeDesignationstatus
!= null) {
1027 logger
.info("specimenTypeDesignationstatus :"+ specimenTypeDesignationstatus
);
1030 ICdmApplicationConfiguration cdmAppController
= config
.getCdmAppController();
1031 if(cdmAppController
== null){
1032 cdmAppController
= this;
1034 specimenTypeDesignationstatus
= (SpecimenTypeDesignationStatus
) cdmAppController
.getTermService().find(specimenTypeDesignationstatus
.getUuid());
1036 TaxonNameBase
<?
,?
> name
= taxon
.getName();
1037 SpecimenTypeDesignation designation
= SpecimenTypeDesignation
.NewInstance();
1039 designation
.setTypeStatus(specimenTypeDesignationstatus
);
1040 designation
.setTypeSpecimen(state
.getDerivedUnitBase());
1041 name
.addTypeDesignation(designation
, true);
1045 for (String
[] fullReference
: state
.getDataHolder().getReferenceList()) {
1048 String strReference
=fullReference
[0];
1049 String citationDetail
= fullReference
[1];
1050 String citationURL
= fullReference
[2];
1051 List
<Reference
> references
= getReferenceService().listByTitle(Reference
.class, "strReference", MatchMode
.EXACT
, null, null, null, null, null);
1053 if (!references
.isEmpty()){
1054 Reference reference
= null;
1055 for (Reference refe
: references
) {
1056 if (refe
.getTitleCache().equalsIgnoreCase(strReference
)) {
1061 if (reference
==null){
1062 reference
= ReferenceFactory
.newGeneric();
1063 reference
.setTitleCache(strReference
, true);
1064 save(reference
, state
);
1066 determinationEvent
.addReference(reference
);
1069 save(state
.getDerivedUnitBase(), state
);
1071 if (config
.isAddIndividualsAssociationsSuchAsSpecimenAndObservations() && preferredFlag
) {
1072 //do not add IndividualsAssociation to non-preferred taxa
1074 logger
.info("isDoCreateIndividualsAssociations");
1077 makeIndividualsAssociation(state
, taxon
, determinationEvent
);
1079 save(state
.getDerivedUnitBase(), state
);
1084 * create and link each association (specimen, observation..) to the accepted taxon
1085 * @param state : the ABCD import state
1086 * @param taxon: the current Taxon
1087 * @param determinationEvent:the determinationevent
1089 protected void makeIndividualsAssociation(STATE state
, Taxon taxon
, DeterminationEvent determinationEvent
) {
1090 SpecimenImportConfiguratorBase config
= state
.getConfig();
1091 SpecimenUserInteraction sui
= config
.getSpecimenUserInteraction();
1094 logger
.info("MAKE INDIVIDUALS ASSOCIATION");
1097 TaxonDescription taxonDescription
= null;
1098 Set
<TaxonDescription
> descriptions
= taxon
.getDescriptions();
1099 // if (((Abcd206ImportConfigurator) state.getConfig()).isInteractWithUser()){
1100 // if(!state.isDescriptionGroupSet()){
1101 // taxonDescription = sui.askForDescriptionGroup(descriptions);
1102 // state.setDescriptionGroup(taxonDescription);
1103 // state.setDescriptionGroupSet(true);
1105 // taxonDescription=state.getDescriptionGroup();
1108 for (TaxonDescription description
: descriptions
){
1109 Set
<IdentifiableSource
> sources
= new HashSet
<>();
1110 sources
.addAll(description
.getTaxon().getSources());
1111 sources
.addAll(description
.getSources());
1112 for (IdentifiableSource source
:sources
){
1113 if(state
.getRef().equals(source
.getCitation())) {
1114 taxonDescription
= description
;
1119 if (taxonDescription
== null){
1120 taxonDescription
= TaxonDescription
.NewInstance(taxon
, false);
1121 if(sourceNotLinkedToElement(taxonDescription
,state
.getRef(),null)) {
1122 taxonDescription
.addSource(OriginalSourceType
.Import
, null, null, state
.getRef(), null);
1124 state
.setDescriptionGroup(taxonDescription
);
1125 taxon
.addDescription(taxonDescription
);
1128 //PREPARE REFERENCE QUESTIONS
1130 Map
<String
,OriginalSourceBase
<?
>> sourceMap
= new HashMap
<String
, OriginalSourceBase
<?
>>();
1132 List
<IdentifiableSource
> issTmp
= new ArrayList
<>();//getCommonService().list(IdentifiableSource.class, null, null, null, null);
1133 List
<DescriptionElementSource
> issTmp2
= new ArrayList
<>();//getCommonService().list(DescriptionElementSource.class, null, null, null, null);
1135 Set
<OriginalSourceBase
> osbSet
= new HashSet
<OriginalSourceBase
>();
1137 osbSet
.addAll(issTmp2
);
1140 osbSet
.addAll(issTmp
);
1144 addToSourceMap(sourceMap
, osbSet
);
1146 // if (((Abcd206ImportConfigurator) state.getConfig()).isInteractWithUser()){
1147 // List<OriginalSourceBase<?>> res = null;
1148 // if(!state.isDescriptionSourcesSet()){
1149 // res = sui.askForSource(sourceMap, "the description group ("+taxon+")",
1150 // "The current reference is "+state.getRef().getTitleCache(),getReferenceService(), state.getDataHolder().docSources);
1151 // state.setDescriptionRefs(res);
1152 // state.setDescriptionSourcesSet(true);
1155 // res=state.getDescriptionRefs();
1158 // for (OriginalSourceBase<?> sour:res){
1159 // if(sour.isInstanceOf(IdentifiableSource.class)){
1161 // if(sourceNotLinkedToElement(taxonDescription,sour)) {
1162 // taxonDescription.addSource((IdentifiableSource)sour.clone());
1164 // } catch (CloneNotSupportedException e) {
1165 // logger.warn("no cloning?");
1168 // if(sourceNotLinkedToElement(taxonDescription,sour)) {
1169 // taxonDescription.addSource(OriginalSourceType.Import,null, null, sour.getCitation(),sour.getCitationMicroReference());
1176 if(sourceNotLinkedToElement(taxonDescription
,state
.getRef(),null)) {
1177 taxonDescription
.addSource(OriginalSourceType
.Import
,null, null, state
.getRef(), null);
1180 state
.setDescriptionGroup(taxonDescription
);
1182 IndividualsAssociation indAssociation
= IndividualsAssociation
.NewInstance();
1183 Feature feature
= makeFeature(state
.getDerivedUnitBase());
1184 indAssociation
.setAssociatedSpecimenOrObservation(state
.getDerivedUnitBase());
1185 indAssociation
.setFeature(feature
);
1187 // if (((Abcd206ImportConfigurator) state.getConfig()).isInteractWithUser()){
1188 // sourceMap = new HashMap<String, OriginalSourceBase<?>>();
1190 // issTmp = getCommonService().list(IdentifiableSource.class, null, null, null, null);
1191 // issTmp2 = getCommonService().list(DescriptionElementSource.class, null, null, null, null);
1193 // osbSet = new HashSet<OriginalSourceBase>();
1194 // if(issTmp2!=null) {
1195 // osbSet.addAll(issTmp2);
1197 // if(issTmp!=null) {
1198 // osbSet.addAll(issTmp);
1202 // addToSourceMap(sourceMap, osbSet);
1204 // List<OriginalSourceBase<?>> sources =null;
1205 // if(!state.isAssociationSourcesSet()) {
1206 // sources = sui.askForSource(sourceMap, "descriptive element (association) ",taxon.toString(),
1207 // getReferenceService(),state.getDataHolder().getDocSources());
1208 // state.setAssociationRefs(sources);
1209 // state.setAssociationSourcesSet(true);
1212 // sources=state.getAssociationRefs();
1214 // if(sources !=null) {
1215 // for (OriginalSourceBase<?> source: sources) {
1216 // if(source !=null) {
1217 // if(source.isInstanceOf(DescriptionElementSource.class)){
1219 // if(sourceNotLinkedToElement(indAssociation,source)) {
1220 // indAssociation.addSource((DescriptionElementSource)source.clone());
1222 // } catch (CloneNotSupportedException e) {
1223 // logger.warn("clone forbidden?");
1226 // if(sourceNotLinkedToElement(indAssociation,source)) {
1227 // indAssociation.addSource(OriginalSourceType.Import,null, null, source.getCitation(),source.getCitationMicroReference());
1230 // if(sourceNotLinkedToElement(state.getDerivedUnitBase(), source)) {
1231 // state.getDerivedUnitBase().addSource((IdentifiableSource) source.clone());
1233 // } catch (CloneNotSupportedException e) {
1234 // // TODO Auto-generated catch block
1235 // e.printStackTrace();
1243 if(sourceNotLinkedToElement(indAssociation
,state
.getRef(),null)) {
1244 indAssociation
.addSource(OriginalSourceType
.Import
,null, null, state
.getRef(), null);
1246 if(sourceNotLinkedToElement(state
.getDerivedUnitBase(), state
.getRef(),null)) {
1247 state
.getDerivedUnitBase().addSource(OriginalSourceType
.Import
,null, null, state
.getRef(), null);
1249 for (Reference citation
: determinationEvent
.getReferences()) {
1250 if(sourceNotLinkedToElement(indAssociation
,citation
,null))
1252 indAssociation
.addSource(DescriptionElementSource
.NewInstance(OriginalSourceType
.Import
, null, null, citation
, null));
1254 if(sourceNotLinkedToElement(state
.getDerivedUnitBase(), state
.getRef(),null)) {
1255 state
.getDerivedUnitBase().addSource(OriginalSourceType
.Import
,null, null, state
.getRef(), null);
1260 taxonDescription
.addElement(indAssociation
);
1262 save(taxonDescription
, state
);
1264 state
.getReport().addDerivate(state
.getDerivedUnitBase(), config
);
1265 state
.getReport().addIndividualAssociation(taxon
, state
.getDataHolder().getUnitID(), state
.getDerivedUnitBase());
1269 * @param derivedUnitBase2
1274 private boolean sourceNotLinkedToElement(DerivedUnit derivedUnitBase2
, Reference b
, String d
) {
1275 Set
<IdentifiableSource
> linkedSources
= derivedUnitBase2
.getSources();
1276 for (IdentifiableSource is
:linkedSources
){
1277 Reference a
= is
.getCitation();
1278 String c
= is
.getCitationMicroReference();
1280 boolean refMatch
=false;
1281 boolean microMatch
=false;
1284 if (a
==null && b
==null) {
1287 if (a
!=null && b
!=null) {
1288 if (a
.getTitleCache().equalsIgnoreCase(b
.getTitleCache())) {
1292 }catch(Exception e
){}
1296 if (c
==null && d
==null) {
1299 if(c
!=null && d
!=null) {
1300 if(c
.equalsIgnoreCase(d
)) {
1305 catch(Exception e
){}
1307 if (microMatch
&& refMatch
) {
1316 private <T
extends OriginalSourceBase
<?
>> boolean sourceNotLinkedToElement(ISourceable
<T
> sourcable
, Reference reference
, String microReference
) {
1317 Set
<T
> linkedSources
= sourcable
.getSources();
1318 for (T is
:linkedSources
){
1319 Reference unitReference
= is
.getCitation();
1320 String unitMicroReference
= is
.getCitationMicroReference();
1322 boolean refMatch
=false;
1323 boolean microMatch
=false;
1326 if (unitReference
==null && reference
==null) {
1329 if (unitReference
!=null && reference
!=null) {
1330 if (unitReference
.getTitleCache().equalsIgnoreCase(reference
.getTitleCache())) {
1334 }catch(Exception e
){}
1337 if (unitMicroReference
==null && microReference
==null) {
1340 if(unitMicroReference
!=null && microReference
!=null) {
1341 if(unitMicroReference
.equalsIgnoreCase(microReference
)) {
1346 catch(Exception e
){}
1348 if (microMatch
&& refMatch
) {
1356 * look for the Feature object (FieldObs, Specimen,...)
1357 * @param unit : a specimen or obersvation base
1358 * @return the corresponding Feature
1360 private Feature
makeFeature(SpecimenOrObservationBase
<?
> unit
) {
1361 SpecimenOrObservationType type
= unit
.getRecordBasis();
1365 if (type
.isFeatureObservation()){
1366 return Feature
.OBSERVATION();
1367 }else if (type
.isFeatureSpecimen()){
1368 return Feature
.SPECIMEN();
1369 }else if (type
== SpecimenOrObservationType
.DerivedUnit
){
1370 return Feature
.OBSERVATION();
1371 // return getFeature("Specimen or observation");
1373 String message
= "Unhandled record basis '%s' for defining individuals association feature type. Use default.";
1374 logger
.warn(String
.format(message
, type
.getMessage()));
1375 return Feature
.OBSERVATION();
1376 // return getFeature("Specimen or observation");
1386 protected void addToSourceMap(Map
<String
, OriginalSourceBase
<?
>> sourceMap
, Set
<OriginalSourceBase
> osbSet
) {
1387 for( OriginalSourceBase
<?
> osb
:osbSet
) {
1388 if(osb
.getCitation()!=null && osb
.getCitationMicroReference() !=null && !osb
.getCitationMicroReference().isEmpty()) {
1390 sourceMap
.put(osb
.getCitation().getTitleCache()+ "---"+osb
.getCitationMicroReference(),osb
);
1391 }catch(NullPointerException e
){logger
.warn("null pointer problem (no ref?) with "+osb
);}
1392 } else if(osb
.getCitation()!=null){
1394 sourceMap
.put(osb
.getCitation().getTitleCache(),osb
);
1395 }catch(NullPointerException e
){logger
.warn("null pointer problem (no ref?) with "+osb
);}