Project

General

Profile

« Previous | Next » 

Revision 89dc0db4

Added by Andreas Müller almost 9 years ago

Improve E+M import post methods #3979

View differences:

app-import/src/main/java/eu/etaxonomy/cdm/app/berlinModelImport/EuroMedActivator.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

  
10
package eu.etaxonomy.cdm.app.berlinModelImport;
11

  
12
import java.io.IOException;
13
import java.io.InputStream;
14
import java.io.InputStreamReader;
15
import java.io.Reader;
16
import java.util.Arrays;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Set;
21
import java.util.UUID;
22

  
23
import org.apache.log4j.Logger;
24
import org.springframework.security.core.GrantedAuthority;
25
import org.springframework.transaction.TransactionStatus;
26

  
27
import eu.etaxonomy.cdm.api.application.FirstDataInserter;
28
import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
29
import eu.etaxonomy.cdm.api.service.IGroupService;
30
import eu.etaxonomy.cdm.api.service.description.TransmissionEngineDistribution;
31
import eu.etaxonomy.cdm.api.service.description.TransmissionEngineDistribution.AggregationMode;
32
import eu.etaxonomy.cdm.api.service.pager.Pager;
33
import eu.etaxonomy.cdm.app.common.CdmDestinations;
34
import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
35
import eu.etaxonomy.cdm.database.DbSchemaValidation;
36
import eu.etaxonomy.cdm.database.ICdmDataSource;
37
import eu.etaxonomy.cdm.ext.geo.IEditGeoService;
38
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
39
import eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportConfigurator;
40
import eu.etaxonomy.cdm.io.common.CdmDefaultImport;
41
import eu.etaxonomy.cdm.io.common.CdmImportBase;
42
import eu.etaxonomy.cdm.io.common.IImportConfigurator.CHECK;
43
import eu.etaxonomy.cdm.io.common.IImportConfigurator.DO_REFERENCES;
44
import eu.etaxonomy.cdm.io.common.IImportConfigurator.EDITOR;
45
import eu.etaxonomy.cdm.io.common.Source;
46
import eu.etaxonomy.cdm.model.agent.Person;
47
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
48
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
49
import eu.etaxonomy.cdm.model.common.Group;
50
import eu.etaxonomy.cdm.model.common.Language;
51
import eu.etaxonomy.cdm.model.common.Marker;
52
import eu.etaxonomy.cdm.model.common.MarkerType;
53
import eu.etaxonomy.cdm.model.common.Representation;
54
import eu.etaxonomy.cdm.model.common.TermVocabulary;
55
import eu.etaxonomy.cdm.model.common.User;
56
import eu.etaxonomy.cdm.model.description.Feature;
57
import eu.etaxonomy.cdm.model.description.FeatureNode;
58
import eu.etaxonomy.cdm.model.description.FeatureTree;
59
import eu.etaxonomy.cdm.model.location.NamedArea;
60
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
61
import eu.etaxonomy.cdm.model.location.NamedAreaType;
62
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
63
import eu.etaxonomy.cdm.model.name.Rank;
64
import eu.etaxonomy.cdm.model.taxon.Taxon;
65
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
66
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
67
import eu.etaxonomy.cdm.persistence.query.MatchMode;
68
import eu.etaxonomy.cdm.persistence.query.OrderHint;
69

  
70

  
71
/**
72
 * TODO add the following to a wiki page:
73
 * HINT: If you are about to import into a mysql data base running under windows and if you wish to dump and restore the resulting data bas under another operation systen
74
 * you must set the mysql system variable lower_case_table_names = 0 in order to create data base with table compatible names.
75
 *
76
 *
77
 * @author a.mueller
78
 *
79
 */
80
public class EuroMedActivator {
81
	private static final Logger logger = Logger.getLogger(EuroMedActivator.class);
82

  
83
	//database validation status (create, update, validate ...)
84
	static DbSchemaValidation hbm2dll = DbSchemaValidation.VALIDATE;
85
	static final Source berlinModelSource = BerlinModelSources.euroMed_BGBM42();
86
//	static final Source berlinModelSource = BerlinModelSources.euroMed_PESI3();
87

  
88
	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_euroMed();
89

  
90
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_pesi_euromed();
91
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_local_euromed3();
92
//	static final ICdmDataSource cdmDestination = CdmDestinations.localH2();
93

  
94
	static final boolean includePesiExport = false;
95

  
96
	static final int sourceSecId = 7000000; //500000
97
	static final UUID classificationUuid = UUID.fromString("314a68f9-8449-495a-91c2-92fde8bcf344");
98
	static final boolean useSingleClassification = true;
99
	static final String classificationName = "Euro+Med 2014";
100
	static final UUID featureTreeUuid = UUID.fromString("6a5e1c2b-ec0d-46c8-9c7d-a2059267ffb7");
101
	static final Object[] featureKeyList = new Integer[]{1, 31, 4, 98, 41};
102

  
103
	// set to zero for unlimited nameFacts
104
	static final int maximumNumberOfNameFacts = 0;
105

  
106
	static final int partitionSize = 2500;
107

  
108
	//check - import
109
	static final CHECK check = CHECK.IMPORT_WITHOUT_CHECK;
110

  
111
	//editor - import
112
	static final EDITOR editor = EDITOR.EDITOR_AS_EDITOR;
113

  
114
	//NomenclaturalCode
115
	static final NomenclaturalCode nomenclaturalCode = NomenclaturalCode.ICNAFP;
116

  
117
	//ignore null
118
	static final boolean ignoreNull = true;
119

  
120
	static final boolean switchSpeciesGroup = true;
121

  
122
	static boolean useClassification = true;
123

  
124
	static boolean isSplitTdwgCodes = false;
125
	static boolean useEmAreaVocabulary = true;
126

  
127
	private final boolean removeHttpMapsAnchor = true;
128

  
129

  
130
	static final String infrGenericRankAbbrev = "[unranked]";
131
	static final String infrSpecificRankAbbrev = "[unranked]";
132

  
133

  
134
	static String taxonTable = "v_cdm_exp_taxaAll";
135
	static String classificationQuery = " SELECT DISTINCT t.PTRefFk, r.RefCache FROM PTaxon t INNER JOIN Reference r ON t.PTRefFk = r.RefId WHERE t.PTRefFk = " + sourceSecId;
136
	static String relPTaxonIdQuery = " SELECT r.RelPTaxonId " +
137
					" FROM RelPTaxon AS r INNER JOIN v_cdm_exp_taxaDirect AS a ON r.PTNameFk2 = a.PTNameFk AND r.PTRefFk2 = a.PTRefFk" +
138
					" WHERE r.RelPTaxonID NOT IN (1883791,1883800,1883823,1883852,1883853,1883864,1883896,1883921,1883943,1883944,1883955,1883972,1884008,1884030,1884031,1884035) " + //Unpublished Kew taxa which are not imported anymore
139
					" ";  // AND r.RelQualifierFk =1
140
	static String nameIdTable = " v_cdm_exp_namesAll ";
141
	static String referenceIdTable = " v_cdm_exp_refAll ";
142
	static String refDetailFilter =  " RefDetailID IN (SELECT RefDetailID FROM v_cdm_exp_RefDetail) ";
143
	static String factFilter = " factId IN ( SELECT factId FROM v_cdm_exp_factsAll WHERE FactCategoryFk NOT IN (12, 14, 249, 251))";
144
	static String occurrenceFilter = " occurrenceId IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
145
	static String occurrenceSourceFilter = " occurrenceFk IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
146
	static String commonNameFilter = " commonNameId IN ( SELECT commonNameId FROM v_cdm_exp_commonNamesAll )";
147
	static String webMarkerFilter = " TableNameFk <> 500 OR ( RIdentifierFk IN (SELECT RIdentifier FROM v_cdm_exp_taxaAll)) ";
148
	static String authorTeamFilter = null; // " authorTeamId IN (SELECT authorTeamId FROM v_cdm_exp_authorTeamsAll) ";
149
	static String authorFilter = null;  // " authorId IN (SELECT authorId FROM v_cdm_exp_authorsAll) ";
150

  
151

  
152

  
153
// **************** ALL *********************
154

  
155
	boolean invers = !(hbm2dll == DbSchemaValidation.CREATE);
156

  
157
	static final boolean doUser = true;
158
//	//authors
159
	static final boolean doAuthors = true;
160
	//references
161
	static final DO_REFERENCES doReferences =  DO_REFERENCES.ALL;
162
	//names
163
	static final boolean doTaxonNames = true;
164
	static final boolean doRelNames = true;
165
	static final boolean doNameStatus = true;
166
	static final boolean doTypes = false;  //serious types do not exist in E+M
167
	static final boolean doNameFacts = true;
168

  
169
	//taxa
170
	static final boolean doTaxa = true;
171
	static final boolean doRelTaxa = true;  //FIXME revert
172
	static final boolean doFacts = true;
173
	static final boolean doOccurences = true;
174
	static final boolean doCommonNames = true;
175

  
176
	//etc.
177
	static final boolean doMarker = true;
178

  
179

  
180
	public void importEm2CDM (Source source, ICdmDataSource destination, DbSchemaValidation hbm2dll){
181
		System.out.println("Start import from BerlinModel("+ berlinModelSource.getDatabase() + ") to " + cdmDestination.getDatabase() + " ...");
182
		//make BerlinModel Source
183

  
184
		BerlinModelImportConfigurator config = BerlinModelImportConfigurator.NewInstance(source,  destination);
185

  
186
		config.setClassificationName(classificationName);
187

  
188
		config.setClassificationUuid(classificationUuid);
189
		config.setSourceSecId(sourceSecId);
190
		config.setNomenclaturalCode(nomenclaturalCode);
191
		config.setIgnoreNull(ignoreNull);
192

  
193
		config.setDoAuthors(doAuthors ^ invers);
194
		config.setDoReferences(invers ? doReferences.invers() : doReferences);
195
		config.setDoTaxonNames(doTaxonNames ^ invers);
196
		config.setDoRelNames(doRelNames ^ invers);
197
		config.setDoNameStatus(doNameStatus ^ invers);
198
		config.setDoTypes(doTypes);  //always false
199
		config.setDoNameFacts(doNameFacts ^ invers);
200
		config.setDoTaxa(doTaxa ^ invers);
201
		config.setDoRelTaxa(doRelTaxa ^ invers);
202
		config.setDoFacts(doFacts ^ invers);
203
		config.setDoOccurrence(doOccurences ^ invers);
204
		config.setDoCommonNames(doCommonNames ^ invers);
205

  
206
		config.setDoMarker(doMarker ^ invers);
207
		config.setDoUser(doUser ^ invers);
208

  
209
		config.setUseClassification(useClassification);
210
		config.setSourceRefUuid(BerlinModelTransformer.uuidSourceRefEuroMed);
211
		config.setEditor(editor);
212
		config.setDbSchemaValidation(hbm2dll);
213

  
214
		// maximum number of name facts to import
215
		config.setMaximumNumberOfNameFacts(maximumNumberOfNameFacts);
216

  
217
		config.setInfrGenericRankAbbrev(infrGenericRankAbbrev);
218
		config.setInfrSpecificRankAbbrev(infrSpecificRankAbbrev);
219
		config.setRemoveHttpMapsAnchor(removeHttpMapsAnchor);
220

  
221
//		filter
222
		config.setTaxonTable(taxonTable);
223
		config.setClassificationQuery(classificationQuery);
224
		config.setRelTaxaIdQuery(relPTaxonIdQuery);
225
		config.setNameIdTable(nameIdTable);
226
		config.setReferenceIdTable(referenceIdTable);
227
		config.setAuthorTeamFilter(authorTeamFilter);
228
		config.setAuthorFilter(authorFilter);
229
		config.setFactFilter(factFilter);
230
		config.setRefDetailFilter(refDetailFilter);
231
		config.setCommonNameFilter(commonNameFilter);
232
		config.setOccurrenceFilter(occurrenceFilter);
233
		config.setOccurrenceSourceFilter(occurrenceSourceFilter);
234
		config.setWebMarkerFilter(webMarkerFilter);
235
		config.setUseSingleClassification(useSingleClassification);
236

  
237
		//TDWG codes
238
		config.setSplitTdwgCodes(isSplitTdwgCodes);
239
		config.setUseEmAreaVocabulary(useEmAreaVocabulary);
240

  
241
		config.setCheck(check);
242
		config.setEditor(editor);
243
		config.setRecordsPerTransaction(partitionSize);
244

  
245
		config.setSwitchSpeciesGroup(switchSpeciesGroup);
246

  
247
		// invoke import
248
		CdmDefaultImport<BerlinModelImportConfigurator> bmImport = new CdmDefaultImport<BerlinModelImportConfigurator>();
249
		bmImport.invoke(config);
250

  
251
		renameRanks(config, bmImport);
252

  
253
		createFeatureTree(config, bmImport);
254

  
255
		changeCommonNameLabel(config, bmImport);
256

  
257
        runTransmissionEngine(config, bmImport);
258

  
259
        importShapefile(config, bmImport);
260

  
261
        createUsersAndRoles(config, bmImport);
262

  
263
	    markAreasAsHidden(config, bmImport);
264

  
265
		System.out.println("End import from BerlinModel ("+ source.getDatabase() + ")...");
266
	}
267

  
268
    private void renameRanks(BerlinModelImportConfigurator config,
269
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
270
        //Rename Ranks (still needed?)
271
		if (config.isDoTaxonNames() && (config.getCheck().isImport() )  ){
272
			ICdmApplicationConfiguration app = bmImport.getCdmAppController();
273
			TransactionStatus tx = app.startTransaction();
274
			try {
275
				Rank sectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
276
				Representation repr = sectBot.getRepresentation(Language.ENGLISH());
277
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
278
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
279
				sectBot.setTitleCache(null, false);  //to definetely update the titleCache also
280
				app.getTermService().saveOrUpdate(sectBot);
281

  
282
				Rank subSectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
283
				repr = subSectBot.getRepresentation(Language.ENGLISH());
284
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
285
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
286
				subSectBot.setTitleCache(null, false);  //to definetely update the titleCache also
287
				app.getTermService().saveOrUpdate(subSectBot);
288
				app.commitTransaction(tx);
289
			} catch (Exception e) {
290
				e.printStackTrace();
291
			}
292
		}
293
    }
294

  
295
    private void createFeatureTree(BerlinModelImportConfigurator config,
296
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
297
        //create feature tree
298
		if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
299
			ICdmApplicationConfiguration app = bmImport.getCdmAppController();
300
			TransactionStatus tx = app.startTransaction();
301

  
302
			//make feature tree
303
			FeatureTree tree = TreeCreator.flatTree(featureTreeUuid, config.getFeatureMap(), featureKeyList);
304
			FeatureNode imageNode = FeatureNode.NewInstance(Feature.IMAGE());
305
			tree.getRoot().addChild(imageNode);
306
			FeatureNode distributionNode = FeatureNode.NewInstance(Feature.DISTRIBUTION());
307
			tree.getRoot().addChild(distributionNode, 1);
308
			FeatureNode commonNameNode = FeatureNode.NewInstance(Feature.COMMON_NAME());
309
			tree.getRoot().addChild(commonNameNode, 2);
310
			app.getFeatureTreeService().saveOrUpdate(tree);
311

  
312
            app.commitTransaction(tx);
313
		}
314
    }
315

  
316
    private void changeCommonNameLabel(BerlinModelImportConfigurator config,
317
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
318
        //Change common name label
319
	    if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
320
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
321
	        TransactionStatus tx = app.startTransaction();
322

  
323
	        DefinedTermBase<?> commonNameFeature = app.getTermService().find(Feature.COMMON_NAME().getUuid());
324
            commonNameFeature.setLabel("Common Names", Language.ENGLISH());
325
            commonNameFeature.setTitleCache(null, false);  //to definitely update the titleCache also
326
            app.getTermService().saveOrUpdate(commonNameFeature);
327

  
328
            app.commitTransaction(tx);
329
	    }
330
    }
331

  
332
    //1. run transmission engine #3979
333
    private void runTransmissionEngine(BerlinModelImportConfigurator config,
334
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
335
        //Transmission engine #3979 .1
336
        if (true || config.isDoOccurrence() && (config.getCheck().isImport()  )  ){
337
            ICdmApplicationConfiguration app = bmImport.getCdmAppController();
338

  
339
            final List<String> term_init_strategy = Arrays.asList(new String []{
340
                    "representations"
341
            });
342

  
343
            UUID uuidSuperAreaLevel = BerlinModelTransformer.uuidEuroMedAreaLevelFirst;
344
            NamedAreaLevel euroMedLevel1 = (NamedAreaLevel)app.getTermService().find(uuidSuperAreaLevel);
345

  
346
            Pager<NamedArea> areaPager = app.getTermService().list(
347
                    euroMedLevel1,
348
                    (NamedAreaType) null,
349
                    null,
350
                    null,
351
                    (List<OrderHint>) null,
352
                    term_init_strategy);
353
            TransmissionEngineDistribution transmissionEngineDistribution = (TransmissionEngineDistribution)app.getBean("transmissionEngineDistribution");
354
            transmissionEngineDistribution.accumulate(
355
                    AggregationMode.byAreasAndRanks,
356
                    areaPager.getRecords(),
357
                    Rank.SUBSPECIES(),
358
                    Rank.GENUS(),
359
                    null,
360
                    DefaultProgressMonitor.NewInstance());
361
        }
362
    }
363

  
364
    //5.Mark areas to be hidden #3979 .5
365
    private void markAreasAsHidden(BerlinModelImportConfigurator config,
366
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
367

  
368
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
369
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
370
	        TransactionStatus tx = app.startTransaction();
371

  
372
	        MarkerType hiddenAreaMarkerType = MarkerType.NewInstance("Used to hide distributions for the named areas in publications", "Hidden Area", null);
373
	        hiddenAreaMarkerType.setUuid(BerlinModelTransformer.uuidHiddenArea);
374
	        @SuppressWarnings("unchecked")
375
            TermVocabulary<MarkerType> vocUserDefinedMarkerTypes = app.getVocabularyService().find(CdmImportBase.uuidUserDefinedMarkerTypeVocabulary);
376
	        if (vocUserDefinedMarkerTypes == null){
377
	            String message = "Marker type vocabulary could not be found. Hidden areas not added.";
378
	            logger.error(message);
379
	            System.out.println(message);
380
	        }else{
381
	            vocUserDefinedMarkerTypes.addTerm(hiddenAreaMarkerType);
382
	            app.getVocabularyService().saveOrUpdate(vocUserDefinedMarkerTypes);
383

  
384
	            //Add hidden area marker to Rs(C) and Rs(N)
385
	            NamedArea rs_c = (NamedArea)app.getTermService().find(BerlinModelTransformer.uuidRs_C);
386
	            rs_c.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
387
	            app.getTermService().saveOrUpdate(rs_c);
388
	            NamedArea rs_n = (NamedArea)app.getTermService().find(BerlinModelTransformer.uuidRs_N);
389
                rs_n.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
390
                app.getTermService().saveOrUpdate(rs_n);
391
	        }
392
	        app.commitTransaction(tx);
393
	    }
394
    }
395

  
396
    //2. import shapefile attributes #3979 .2
397
    private void importShapefile(BerlinModelImportConfigurator config,
398
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
399

  
400
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
401

  
402
	       UUID areaVocabularyUuid = BerlinModelTransformer.uuidVocEuroMedAreas;
403
           List<String> idSearchFields = Arrays.asList(new String[]{"EMAREA","PARENT"});
404
           String wmsLayerName = "euromed_2013";
405
           Set<UUID> areaUuidSet = null;
406

  
407
           ICdmApplicationConfiguration app = bmImport.getCdmAppController();
408
           IEditGeoService geoService = (IEditGeoService)app.getBean("editGeoService");
409

  
410
           Map<NamedArea, String> resultMap;
411
           try {
412
//             URL url =  ClassLoader.getSystemResource("myConfig.txt");
413
//             FileReader fileReader = new FileReader(url.getFile());
414
               InputStream in = EuroMedActivator.class.getResourceAsStream("/euromed/euromed_2013.csv");
415
               Reader reader = new InputStreamReader(in, "UTF-8");
416

  
417
               resultMap = geoService.mapShapeFileToNamedAreas(
418
                           reader, idSearchFields , wmsLayerName , areaVocabularyUuid, areaUuidSet);
419
               Map<String, String> flatResultMap = new HashMap<String, String>(resultMap.size());
420
               for(NamedArea area : resultMap.keySet()){
421
                   flatResultMap.put(area.getTitleCache() + " [" + area.getUuid() + "]", resultMap.get(area));
422
               }
423
           } catch (IOException e) {
424
                String message = "IOException when reading from mapping file or creating result map.";
425
                logger.error(message);
426
                System.out.println(message);
427
           }
428
	    }
429
    }
430

  
431
    //4. Create users and assign roles  #3979
432
    private void createUsersAndRoles(
433
            BerlinModelImportConfigurator config,
434
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
435

  
436
        if (config.isDoRelTaxa() && (config.getCheck().isImport())){
437
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
438
	        TransactionStatus tx = app.startTransaction();
439

  
440
	        //eraabstraube
441
	        String eraabstraube = "eraabstraube";
442
	        List<User> users = app.getUserService().listByUsername(eraabstraube, MatchMode.EXACT, null, null, null, null, null);
443
	        User userEraabStraube;
444
	        if (users.isEmpty()){
445
	            userEraabStraube = User.NewInstance(eraabstraube, eraabstraube);
446
	        }else{
447
	            userEraabStraube = users.get(0);
448
	        }
449
	        if (userEraabStraube.getPerson() == null){
450
    	        Person eckhard = Person.NewInstance();
451
                eckhard.setLastname("von Raab-Straube");
452
                eckhard.setFirstname("Eckhard");
453
                eckhard.setPrefix("Dr.");
454
                userEraabStraube.setPerson(eckhard);
455
	        }
456
            app.getUserService().saveOrUpdate(userEraabStraube);
457

  
458
            //groups
459
            Group groupEditor = app.getGroupService().load(Group.groupEditorUuid);
460
            groupEditor.addMember(userEraabStraube);
461
            app.getGroupService().saveOrUpdate(groupEditor);
462

  
463
            Group groupProjectManager = app.getGroupService().load(Group.groupProjectManagerUuid);
464
            groupProjectManager.addMember(userEraabStraube);
465
            app.getGroupService().saveOrUpdate(groupProjectManager);
466

  
467
            String[] publishRoles = new String[]{Role.ROLE_PUBLISH.toString()};
468
            Group groupPublisher = checkGroup(app.getGroupService(), Group.groupPublisherUuid, "Publisher", publishRoles);
469
            groupPublisher.addMember(userEraabStraube);
470
            app.getGroupService().saveOrUpdate(groupPublisher);
471

  
472
            UUID uuidEuroMedPlantBaseGroup = UUID.fromString("91be42ea-ad04-4458-9836-389277e773db");
473
            String[] emPlantBaseRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]"};
474
            Group euroMedPlantbase = checkGroup(app.getGroupService(), uuidEuroMedPlantBaseGroup, "Euro+Med Plantbase", emPlantBaseRoles);
475
            euroMedPlantbase.addMember(userEraabStraube);
476
            app.getGroupService().saveOrUpdate(euroMedPlantbase);
477

  
478
            //cichorieae-editor
479
            String cichorieaeEditor = "cichorieae-editor";
480
            app.getUserService().listByUsername(cichorieaeEditor, MatchMode.EXACT, null, null, null, null, null);
481
            User userCichEditor;
482
            if (users.isEmpty()){
483
                userCichEditor = User.NewInstance(cichorieaeEditor, cichorieaeEditor);
484
            }else{
485
                userCichEditor = users.get(0);
486
            }
487
            app.getUserService().saveOrUpdate(userCichEditor);
488

  
489
            //groups
490
            groupEditor.addMember(userCichEditor);
491
            app.getGroupService().saveOrUpdate(groupEditor);
492

  
493
            UUID uuidCichorieaeSubtree = null;
494
            UUID uuidCichorieae = UUID.fromString("63c7dbeb-b9a2-48b8-a75f-e3fe5e161f7c");
495
            Taxon cich = (Taxon)app.getTaxonService().find(uuidCichorieae);
496
            if (cich != null){
497
                TaxonNode cichNode = cich.getTaxonNodes().iterator().next();
498
                if (cichNode != null){
499
                    uuidCichorieaeSubtree = cichNode.getUuid();
500
                }
501
            }
502

  
503
            String[] cichorieaeRoles = new String[]{};
504
            if (uuidCichorieaeSubtree != null){
505
                cichorieaeRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]{"+uuidCichorieaeSubtree.toString()+"}"};
506
            }else{
507
                String message = "Cichorieae node could not be found";
508
                logger.warn(message);
509
                System.out.println(message);
510
            }
511
            UUID uuidCichorieaeGroup = UUID.fromString("a630938d-dd4f-48c2-9406-91def487b11e");
512
            String cichorieaeGroupName = "Cichorieae";
513
            Group cichorieaeGroup = checkGroup(app.getGroupService(), uuidCichorieaeGroup, cichorieaeGroupName, cichorieaeRoles);
514
            cichorieaeGroup.addMember(userCichEditor);
515
            app.getGroupService().saveOrUpdate(cichorieaeGroup);
516

  
517
            app.commitTransaction(tx);
518
	    }
519
    }
520

  
521
	/**
522
	  * copied from {@link FirstDataInserter#checkGroup}
523
     */
524
    private Group checkGroup(IGroupService groupService, UUID groupUuid, String groupName, String[] requiredAuthorities) {
525
        Group group = groupService.load(groupUuid);
526
        if(group == null){
527
            group = Group.NewInstance();
528
            group.setUuid(groupUuid);
529
            logger.info("New Group '" + groupName + "' created");
530
        }
531
        group.setName(groupName); // force name
532

  
533
        Set<GrantedAuthority> grantedAuthorities = group.getGrantedAuthorities();
534

  
535
        for(String a : requiredAuthorities){
536
            boolean isMissing = true;
537
            for(GrantedAuthority ga : grantedAuthorities){
538
                if(a.equals(ga.getAuthority())){
539
                    isMissing = false;
540
                    break;
541
                }
542
            }
543
            if(isMissing){
544
                GrantedAuthorityImpl newGa = GrantedAuthorityImpl.NewInstance();
545
                newGa.setAuthority(a);
546
                group.addGrantedAuthority(newGa);
547
                logger.info("New GrantedAuthority '" + a + "' added  to '" + groupName + "'");
548
            }
549
        }
550
        groupService.saveOrUpdate(group);
551
        logger.info("Check of group  '" + groupName + "' done");
552
        return group;
553
    }
554

  
555

  
556
	/**
557
	 * @param args
558
	 */
559
	public static void main(String[] args) {
560
		EuroMedActivator importActivator = new EuroMedActivator();
561
		Source source = berlinModelSource;
562
		ICdmDataSource cdmRepository = CdmDestinations.chooseDestination(args) != null ? CdmDestinations.chooseDestination(args) : cdmDestination;
563

  
564
		importActivator.importEm2CDM(source, cdmRepository, hbm2dll);
565
		if (includePesiExport){
566
			//not available from here since E+M was moved to app-import
567
//			PesiExportActivatorEM exportActivator = new PesiExportActivatorEM();
568
//			exportActivator.doExport(cdmRepository);
569
		}
570

  
571
	}
572

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

  
10
package eu.etaxonomy.cdm.app.berlinModelImport;
11

  
12
import java.io.IOException;
13
import java.io.InputStream;
14
import java.io.InputStreamReader;
15
import java.io.Reader;
16
import java.util.Arrays;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Set;
21
import java.util.UUID;
22

  
23
import org.apache.log4j.Logger;
24
import org.springframework.security.core.GrantedAuthority;
25
import org.springframework.transaction.TransactionStatus;
26

  
27
import eu.etaxonomy.cdm.api.application.FirstDataInserter;
28
import eu.etaxonomy.cdm.api.application.ICdmApplicationConfiguration;
29
import eu.etaxonomy.cdm.api.service.IGroupService;
30
import eu.etaxonomy.cdm.api.service.description.TransmissionEngineDistribution;
31
import eu.etaxonomy.cdm.api.service.description.TransmissionEngineDistribution.AggregationMode;
32
import eu.etaxonomy.cdm.api.service.pager.Pager;
33
import eu.etaxonomy.cdm.app.common.CdmDestinations;
34
import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;
35
import eu.etaxonomy.cdm.database.DbSchemaValidation;
36
import eu.etaxonomy.cdm.database.ICdmDataSource;
37
import eu.etaxonomy.cdm.ext.geo.IEditGeoService;
38
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
39
import eu.etaxonomy.cdm.io.berlinModel.in.BerlinModelImportConfigurator;
40
import eu.etaxonomy.cdm.io.common.CdmDefaultImport;
41
import eu.etaxonomy.cdm.io.common.CdmImportBase;
42
import eu.etaxonomy.cdm.io.common.IImportConfigurator.CHECK;
43
import eu.etaxonomy.cdm.io.common.IImportConfigurator.DO_REFERENCES;
44
import eu.etaxonomy.cdm.io.common.IImportConfigurator.EDITOR;
45
import eu.etaxonomy.cdm.io.common.Source;
46
import eu.etaxonomy.cdm.model.agent.Person;
47
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
48
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
49
import eu.etaxonomy.cdm.model.common.Group;
50
import eu.etaxonomy.cdm.model.common.Language;
51
import eu.etaxonomy.cdm.model.common.Marker;
52
import eu.etaxonomy.cdm.model.common.MarkerType;
53
import eu.etaxonomy.cdm.model.common.Representation;
54
import eu.etaxonomy.cdm.model.common.TermVocabulary;
55
import eu.etaxonomy.cdm.model.common.User;
56
import eu.etaxonomy.cdm.model.description.Feature;
57
import eu.etaxonomy.cdm.model.description.FeatureNode;
58
import eu.etaxonomy.cdm.model.description.FeatureTree;
59
import eu.etaxonomy.cdm.model.location.NamedArea;
60
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
61
import eu.etaxonomy.cdm.model.location.NamedAreaType;
62
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
63
import eu.etaxonomy.cdm.model.name.Rank;
64
import eu.etaxonomy.cdm.model.taxon.Taxon;
65
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
66
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
67
import eu.etaxonomy.cdm.persistence.query.MatchMode;
68
import eu.etaxonomy.cdm.persistence.query.OrderHint;
69

  
70

  
71
/**
72
 * TODO add the following to a wiki page:
73
 * HINT: If you are about to import into a mysql data base running under windows and if you wish to dump and restore the resulting data bas under another operation systen
74
 * you must set the mysql system variable lower_case_table_names = 0 in order to create data base with table compatible names.
75
 *
76
 *
77
 * @author a.mueller
78
 *
79
 */
80
public class EuroMedActivator {
81
	private static final Logger logger = Logger.getLogger(EuroMedActivator.class);
82

  
83
	//database validation status (create, update, validate ...)
84
	static DbSchemaValidation hbm2dll = DbSchemaValidation.VALIDATE;
85
	static final Source berlinModelSource = BerlinModelSources.euroMed_BGBM42();
86
//	static final Source berlinModelSource = BerlinModelSources.euroMed_PESI3();
87

  
88
	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_euroMed();
89

  
90
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_pesi_euromed();
91
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_local_euromed3();
92
//	static final ICdmDataSource cdmDestination = CdmDestinations.localH2();
93

  
94
	static final boolean includePesiExport = false;
95

  
96
	static final int sourceSecId = 7000000; //500000
97
	static final UUID classificationUuid = UUID.fromString("314a68f9-8449-495a-91c2-92fde8bcf344");
98
	static final boolean useSingleClassification = true;
99
	static final String classificationName = "Euro+Med 2014";
100
	static final UUID featureTreeUuid = UUID.fromString("6a5e1c2b-ec0d-46c8-9c7d-a2059267ffb7");
101
	static final Object[] featureKeyList = new Integer[]{1, 31, 4, 98, 41};
102

  
103
	// set to zero for unlimited nameFacts
104
	static final int maximumNumberOfNameFacts = 0;
105

  
106
	static final int partitionSize = 2500;
107

  
108
	//check - import
109
	static final CHECK check = CHECK.IMPORT_WITHOUT_CHECK;
110

  
111
	//editor - import
112
	static final EDITOR editor = EDITOR.EDITOR_AS_EDITOR;
113

  
114
	//NomenclaturalCode
115
	static final NomenclaturalCode nomenclaturalCode = NomenclaturalCode.ICNAFP;
116

  
117
	//ignore null
118
	static final boolean ignoreNull = true;
119

  
120
	static final boolean switchSpeciesGroup = true;
121

  
122
	static boolean useClassification = true;
123

  
124
	static boolean isSplitTdwgCodes = false;
125
	static boolean useEmAreaVocabulary = true;
126

  
127
	private final boolean removeHttpMapsAnchor = true;
128

  
129

  
130
	static final String infrGenericRankAbbrev = "[unranked]";
131
	static final String infrSpecificRankAbbrev = "[unranked]";
132

  
133

  
134
	static String taxonTable = "v_cdm_exp_taxaAll";
135
	static String classificationQuery = " SELECT DISTINCT t.PTRefFk, r.RefCache FROM PTaxon t INNER JOIN Reference r ON t.PTRefFk = r.RefId WHERE t.PTRefFk = " + sourceSecId;
136
	static String relPTaxonIdQuery = " SELECT r.RelPTaxonId " +
137
					" FROM RelPTaxon AS r INNER JOIN v_cdm_exp_taxaDirect AS a ON r.PTNameFk2 = a.PTNameFk AND r.PTRefFk2 = a.PTRefFk" +
138
					" WHERE r.RelPTaxonID NOT IN (1883791,1883800,1883823,1883852,1883853,1883864,1883896,1883921,1883943,1883944,1883955,1883972,1884008,1884030,1884031,1884035) " + //Unpublished Kew taxa which are not imported anymore
139
					" ";  // AND r.RelQualifierFk =1
140
	static String nameIdTable = " v_cdm_exp_namesAll ";
141
	static String referenceIdTable = " v_cdm_exp_refAll ";
142
	static String refDetailFilter =  " RefDetailID IN (SELECT RefDetailID FROM v_cdm_exp_RefDetail) ";
143
	static String factFilter = " factId IN ( SELECT factId FROM v_cdm_exp_factsAll WHERE FactCategoryFk NOT IN (12, 14, 249, 251))";
144
	static String occurrenceFilter = " occurrenceId IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
145
	static String occurrenceSourceFilter = " occurrenceFk IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
146
	static String commonNameFilter = " commonNameId IN ( SELECT commonNameId FROM v_cdm_exp_commonNamesAll )";
147
	static String webMarkerFilter = " TableNameFk <> 500 OR ( RIdentifierFk IN (SELECT RIdentifier FROM v_cdm_exp_taxaAll)) ";
148
	static String authorTeamFilter = null; // " authorTeamId IN (SELECT authorTeamId FROM v_cdm_exp_authorTeamsAll) ";
149
	static String authorFilter = null;  // " authorId IN (SELECT authorId FROM v_cdm_exp_authorsAll) ";
150

  
151

  
152

  
153
// **************** ALL *********************
154

  
155
	boolean invers = !(hbm2dll == DbSchemaValidation.CREATE);
156

  
157
	static final boolean doUser = true;
158
//	//authors
159
	static final boolean doAuthors = true;
160
	//references
161
	static final DO_REFERENCES doReferences =  DO_REFERENCES.ALL;
162
	//names
163
	static final boolean doTaxonNames = true;
164
	static final boolean doRelNames = true;
165
	static final boolean doNameStatus = true;
166
	static final boolean doTypes = false;  //serious types do not exist in E+M
167
	static final boolean doNameFacts = true;
168

  
169
	//taxa
170
	static final boolean doTaxa = true;
171
	static final boolean doRelTaxa = true;  //FIXME revert
172
	static final boolean doFacts = true;
173
	static final boolean doOccurences = true;
174
	static final boolean doCommonNames = true;
175

  
176
	//etc.
177
	static final boolean doMarker = true;
178

  
179

  
180
	public void importEm2CDM (Source source, ICdmDataSource destination, DbSchemaValidation hbm2dll){
181
		System.out.println("Start import from BerlinModel("+ berlinModelSource.getDatabase() + ") to " + cdmDestination.getDatabase() + " ...");
182
		//make BerlinModel Source
183

  
184
		BerlinModelImportConfigurator config = BerlinModelImportConfigurator.NewInstance(source,  destination);
185

  
186
		config.setClassificationName(classificationName);
187

  
188
		config.setClassificationUuid(classificationUuid);
189
		config.setSourceSecId(sourceSecId);
190
		config.setNomenclaturalCode(nomenclaturalCode);
191
		config.setIgnoreNull(ignoreNull);
192

  
193
		config.setDoAuthors(doAuthors ^ invers);
194
		config.setDoReferences(invers ? doReferences.invers() : doReferences);
195
		config.setDoTaxonNames(doTaxonNames ^ invers);
196
		config.setDoRelNames(doRelNames ^ invers);
197
		config.setDoNameStatus(doNameStatus ^ invers);
198
		config.setDoTypes(doTypes);  //always false
199
		config.setDoNameFacts(doNameFacts ^ invers);
200
		config.setDoTaxa(doTaxa ^ invers);
201
		config.setDoRelTaxa(doRelTaxa ^ invers);
202
		config.setDoFacts(doFacts ^ invers);
203
		config.setDoOccurrence(doOccurences ^ invers);
204
		config.setDoCommonNames(doCommonNames ^ invers);
205

  
206
		config.setDoMarker(doMarker ^ invers);
207
		config.setDoUser(doUser ^ invers);
208

  
209
		config.setUseClassification(useClassification);
210
		config.setSourceRefUuid(BerlinModelTransformer.uuidSourceRefEuroMed);
211
		config.setEditor(editor);
212
		config.setDbSchemaValidation(hbm2dll);
213

  
214
		// maximum number of name facts to import
215
		config.setMaximumNumberOfNameFacts(maximumNumberOfNameFacts);
216

  
217
		config.setInfrGenericRankAbbrev(infrGenericRankAbbrev);
218
		config.setInfrSpecificRankAbbrev(infrSpecificRankAbbrev);
219
		config.setRemoveHttpMapsAnchor(removeHttpMapsAnchor);
220

  
221
//		filter
222
		config.setTaxonTable(taxonTable);
223
		config.setClassificationQuery(classificationQuery);
224
		config.setRelTaxaIdQuery(relPTaxonIdQuery);
225
		config.setNameIdTable(nameIdTable);
226
		config.setReferenceIdTable(referenceIdTable);
227
		config.setAuthorTeamFilter(authorTeamFilter);
228
		config.setAuthorFilter(authorFilter);
229
		config.setFactFilter(factFilter);
230
		config.setRefDetailFilter(refDetailFilter);
231
		config.setCommonNameFilter(commonNameFilter);
232
		config.setOccurrenceFilter(occurrenceFilter);
233
		config.setOccurrenceSourceFilter(occurrenceSourceFilter);
234
		config.setWebMarkerFilter(webMarkerFilter);
235
		config.setUseSingleClassification(useSingleClassification);
236

  
237
		//TDWG codes
238
		config.setSplitTdwgCodes(isSplitTdwgCodes);
239
		config.setUseEmAreaVocabulary(useEmAreaVocabulary);
240

  
241
		config.setCheck(check);
242
		config.setEditor(editor);
243
		config.setRecordsPerTransaction(partitionSize);
244

  
245
		config.setSwitchSpeciesGroup(switchSpeciesGroup);
246

  
247
		// invoke import
248
		CdmDefaultImport<BerlinModelImportConfigurator> bmImport = new CdmDefaultImport<BerlinModelImportConfigurator>();
249
		bmImport.invoke(config);
250

  
251
		renameRanks(config, bmImport);
252

  
253
		createFeatureTree(config, bmImport);
254

  
255
		changeCommonNameLabel(config, bmImport);
256

  
257
        runTransmissionEngine(config, bmImport);
258

  
259
        importShapefile(config, bmImport);
260

  
261
        createUsersAndRoles(config, bmImport);
262

  
263
	    markAreasAsHidden(config, bmImport);
264

  
265
		System.out.println("End import from BerlinModel ("+ source.getDatabase() + ")...");
266
	}
267

  
268
    private void renameRanks(BerlinModelImportConfigurator config,
269
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
270
        //Rename Ranks (still needed?)
271
		if (config.isDoTaxonNames() && (config.getCheck().isImport() )  ){
272
			ICdmApplicationConfiguration app = bmImport.getCdmAppController();
273
			TransactionStatus tx = app.startTransaction();
274
			try {
275
				Rank sectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
276
				Representation repr = sectBot.getRepresentation(Language.ENGLISH());
277
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
278
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
279
				sectBot.setTitleCache(null, false);  //to definetely update the titleCache also
280
				app.getTermService().saveOrUpdate(sectBot);
281

  
282
				Rank subSectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
283
				repr = subSectBot.getRepresentation(Language.ENGLISH());
284
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
285
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
286
				subSectBot.setTitleCache(null, false);  //to definetely update the titleCache also
287
				app.getTermService().saveOrUpdate(subSectBot);
288
				app.commitTransaction(tx);
289
			} catch (Exception e) {
290
				e.printStackTrace();
291
			}
292
		}
293
    }
294

  
295
    private void createFeatureTree(BerlinModelImportConfigurator config,
296
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
297
        //create feature tree
298
		if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
299
			ICdmApplicationConfiguration app = bmImport.getCdmAppController();
300
			TransactionStatus tx = app.startTransaction();
301

  
302
			//make feature tree
303
			FeatureTree tree = TreeCreator.flatTree(featureTreeUuid, config.getFeatureMap(), featureKeyList);
304
			FeatureNode imageNode = FeatureNode.NewInstance(Feature.IMAGE());
305
			tree.getRoot().addChild(imageNode);
306
			FeatureNode distributionNode = FeatureNode.NewInstance(Feature.DISTRIBUTION());
307
			tree.getRoot().addChild(distributionNode, 1);
308
			FeatureNode commonNameNode = FeatureNode.NewInstance(Feature.COMMON_NAME());
309
			tree.getRoot().addChild(commonNameNode, 2);
310
			app.getFeatureTreeService().saveOrUpdate(tree);
311

  
312
            app.commitTransaction(tx);
313
		}
314
    }
315

  
316
    private void changeCommonNameLabel(BerlinModelImportConfigurator config,
317
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
318
        //Change common name label
319
	    if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
320
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
321
	        TransactionStatus tx = app.startTransaction();
322

  
323
	        DefinedTermBase<?> commonNameFeature = app.getTermService().find(Feature.COMMON_NAME().getUuid());
324
            commonNameFeature.setLabel("Common Names", Language.ENGLISH());
325
            commonNameFeature.setTitleCache(null, false);  //to definitely update the titleCache also
326
            app.getTermService().saveOrUpdate(commonNameFeature);
327

  
328
            app.commitTransaction(tx);
329
	    }
330
    }
331

  
332
    //1. run transmission engine #3979
333
    private void runTransmissionEngine(BerlinModelImportConfigurator config,
334
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
335
        //Transmission engine #3979 .1
336
        if (true || config.isDoOccurrence() && (config.getCheck().isImport()  )  ){
337
            ICdmApplicationConfiguration app = bmImport.getCdmAppController();
338

  
339
            final List<String> term_init_strategy = Arrays.asList(new String []{
340
                    "representations"
341
            });
342

  
343
            UUID uuidSuperAreaLevel = BerlinModelTransformer.uuidEuroMedAreaLevelFirst;
344
            NamedAreaLevel euroMedLevel1 = (NamedAreaLevel)app.getTermService().find(uuidSuperAreaLevel);
345

  
346
            Pager<NamedArea> areaPager = app.getTermService().list(
347
                    euroMedLevel1,
348
                    (NamedAreaType) null,
349
                    null,
350
                    null,
351
                    (List<OrderHint>) null,
352
                    term_init_strategy);
353
            TransmissionEngineDistribution transmissionEngineDistribution = (TransmissionEngineDistribution)app.getBean("transmissionEngineDistribution");
354
            transmissionEngineDistribution.accumulate(
355
                    AggregationMode.byAreasAndRanks,
356
                    areaPager.getRecords(),
357
                    Rank.SUBSPECIES(),
358
                    Rank.GENUS(),
359
                    null,
360
                    DefaultProgressMonitor.NewInstance());
361
        }
362
    }
363

  
364
    //5.Mark areas to be hidden #3979 .5
365
    private void markAreasAsHidden(BerlinModelImportConfigurator config,
366
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
367

  
368
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
369
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
370
	        TransactionStatus tx = app.startTransaction();
371

  
372
	        MarkerType hiddenAreaMarkerType = MarkerType.NewInstance("Used to hide distributions for the named areas in publications", "Hidden Area", null);
373
	        hiddenAreaMarkerType.setUuid(BerlinModelTransformer.uuidHiddenArea);
374
	        @SuppressWarnings("unchecked")
375
            TermVocabulary<MarkerType> vocUserDefinedMarkerTypes = app.getVocabularyService().find(CdmImportBase.uuidUserDefinedMarkerTypeVocabulary);
376
	        if (vocUserDefinedMarkerTypes == null){
377
	            String message = "Marker type vocabulary could not be found. Hidden areas not added.";
378
	            logger.error(message);
379
	            System.out.println(message);
380
	        }else{
381
	            vocUserDefinedMarkerTypes.addTerm(hiddenAreaMarkerType);
382
	            app.getVocabularyService().saveOrUpdate(vocUserDefinedMarkerTypes);
383

  
384
	            //Add hidden area marker to Rs(C) and Rs(N)
385
	            NamedArea rs_c = (NamedArea)app.getTermService().find(BerlinModelTransformer.uuidRs_C);
386
	            rs_c.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
387
	            app.getTermService().saveOrUpdate(rs_c);
388
	            NamedArea rs_n = (NamedArea)app.getTermService().find(BerlinModelTransformer.uuidRs_N);
389
                rs_n.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
390
                app.getTermService().saveOrUpdate(rs_n);
391
	        }
392
	        app.commitTransaction(tx);
393
	    }
394
    }
395

  
396
    //2. import shapefile attributes #3979 .2
397
    private void importShapefile(BerlinModelImportConfigurator config,
398
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
399

  
400
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
401

  
402
	       UUID areaVocabularyUuid = BerlinModelTransformer.uuidVocEuroMedAreas;
403
           List<String> idSearchFields = Arrays.asList(new String[]{"EMAREA","PARENT"});
404
           String wmsLayerName = "euromed_2013";
405
           Set<UUID> areaUuidSet = null;
406

  
407
           ICdmApplicationConfiguration app = bmImport.getCdmAppController();
408
           IEditGeoService geoService = (IEditGeoService)app.getBean("editGeoService");
409

  
410
           Map<NamedArea, String> resultMap;
411
           try {
412
//             URL url =  ClassLoader.getSystemResource("myConfig.txt");
413
//             FileReader fileReader = new FileReader(url.getFile());
414
               InputStream in = EuroMedActivator.class.getResourceAsStream("/euromed/euromed_2013.csv");
415
               Reader reader = new InputStreamReader(in, "UTF-8");
416

  
417
               resultMap = geoService.mapShapeFileToNamedAreas(
418
                           reader, idSearchFields , wmsLayerName , areaVocabularyUuid, areaUuidSet);
419
               Map<String, String> flatResultMap = new HashMap<String, String>(resultMap.size());
420
               for(NamedArea area : resultMap.keySet()){
421
                   flatResultMap.put(area.getTitleCache() + " [" + area.getUuid() + "]", resultMap.get(area));
422
               }
423
           } catch (IOException e) {
424
                String message = "IOException when reading from mapping file or creating result map.";
425
                logger.error(message);
426
                System.out.println(message);
427
           }
428
	    }
429
    }
430

  
431
    //4. Create users and assign roles  #3979
432
    private void createUsersAndRoles(
433
            BerlinModelImportConfigurator config,
434
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
435

  
436
        if (config.isDoRelTaxa() && (config.getCheck().isImport())){
437
	        ICdmApplicationConfiguration app = bmImport.getCdmAppController();
438
	        TransactionStatus tx = app.startTransaction();
439

  
440
	        //eraabstraube
441
	        String eraabstraube = "eraabstraube";
442
	        List<User> users = app.getUserService().listByUsername(eraabstraube, MatchMode.EXACT, null, null, null, null, null);
443
	        User userEraabStraube;
444
	        if (users.isEmpty()){
445
	            userEraabStraube = User.NewInstance(eraabstraube, eraabstraube);
446
	        }else{
447
	            userEraabStraube = users.get(0);
448
	        }
449
	        if (userEraabStraube.getPerson() == null){
450
    	        Person eckhard = Person.NewInstance();
451
                eckhard.setLastname("von Raab-Straube");
452
                eckhard.setFirstname("Eckhard");
453
                eckhard.setPrefix("Dr.");
454
                userEraabStraube.setPerson(eckhard);
455
	        }
456
            app.getUserService().saveOrUpdate(userEraabStraube);
457

  
458
            //groups
459
            Group groupEditor = app.getGroupService().load(Group.groupEditorUuid);
460
            groupEditor.addMember(userEraabStraube);
461
            app.getGroupService().saveOrUpdate(groupEditor);
462

  
463
            Group groupProjectManager = app.getGroupService().load(Group.groupProjectManagerUuid);
464
            groupProjectManager.addMember(userEraabStraube);
465
            app.getGroupService().saveOrUpdate(groupProjectManager);
466

  
467
            String[] publishRoles = new String[]{Role.ROLE_PUBLISH.toString()};
468
            Group groupPublisher = checkGroup(app.getGroupService(), Group.groupPublisherUuid, "Publisher", publishRoles);
469
            groupPublisher.addMember(userEraabStraube);
470
            app.getGroupService().saveOrUpdate(groupPublisher);
471

  
472
            UUID uuidEuroMedPlantBaseGroup = UUID.fromString("91be42ea-ad04-4458-9836-389277e773db");
473
            String[] emPlantBaseRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]"};
474
            Group euroMedPlantbase = checkGroup(app.getGroupService(), uuidEuroMedPlantBaseGroup, "Euro+Med Plantbase", emPlantBaseRoles);
475
            euroMedPlantbase.addMember(userEraabStraube);
476
            app.getGroupService().saveOrUpdate(euroMedPlantbase);
477

  
478
            //cichorieae-editor
479
            String cichorieaeEditor = "cichorieae-editor";
480
            app.getUserService().listByUsername(cichorieaeEditor, MatchMode.EXACT, null, null, null, null, null);
481
            User userCichEditor;
482
            if (users.isEmpty()){
483
                userCichEditor = User.NewInstance(cichorieaeEditor, cichorieaeEditor);
484
            }else{
485
                userCichEditor = users.get(0);
486
            }
487
            app.getUserService().saveOrUpdate(userCichEditor);
488

  
489
            //groups
490
            groupEditor.addMember(userCichEditor);
491
            app.getGroupService().saveOrUpdate(groupEditor);
492

  
493
            UUID uuidCichorieaeSubtree = null;
494
            UUID uuidCichorieae = UUID.fromString("63c7dbeb-b9a2-48b8-a75f-e3fe5e161f7c");
495
            Taxon cich = (Taxon)app.getTaxonService().find(uuidCichorieae);
496
            if (cich != null){
497
                TaxonNode cichNode = cich.getTaxonNodes().iterator().next();
498
                if (cichNode != null){
499
                    uuidCichorieaeSubtree = cichNode.getUuid();
500
                }
501
            }
502

  
503
            String[] cichorieaeRoles = new String[]{};
504
            if (uuidCichorieaeSubtree != null){
505
                cichorieaeRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]{"+uuidCichorieaeSubtree.toString()+"}"};
506
            }else{
507
                String message = "Cichorieae node could not be found";
508
                logger.warn(message);
509
                System.out.println(message);
510
            }
511
            UUID uuidCichorieaeGroup = UUID.fromString("a630938d-dd4f-48c2-9406-91def487b11e");
512
            String cichorieaeGroupName = "Cichorieae";
513
            Group cichorieaeGroup = checkGroup(app.getGroupService(), uuidCichorieaeGroup, cichorieaeGroupName, cichorieaeRoles);
514
            cichorieaeGroup.addMember(userCichEditor);
515
            app.getGroupService().saveOrUpdate(cichorieaeGroup);
516

  
517
            app.commitTransaction(tx);
518
	    }
519
    }
520

  
521
	/**
522
	  * copied from {@link FirstDataInserter#checkGroup}
523
     */
524
    private Group checkGroup(IGroupService groupService, UUID groupUuid, String groupName, String[] requiredAuthorities) {
525
        Group group = groupService.load(groupUuid);
526
        if(group == null){
527
            group = Group.NewInstance();
528
            group.setUuid(groupUuid);
529
            logger.info("New Group '" + groupName + "' created");
530
        }
531
        group.setName(groupName); // force name
532

  
533
        Set<GrantedAuthority> grantedAuthorities = group.getGrantedAuthorities();
534

  
535
        for(String a : requiredAuthorities){
536
            boolean isMissing = true;
537
            for(GrantedAuthority ga : grantedAuthorities){
538
                if(a.equals(ga.getAuthority())){
539
                    isMissing = false;
540
                    break;
541
                }
542
            }
543
            if(isMissing){
544
                GrantedAuthorityImpl newGa = GrantedAuthorityImpl.NewInstance();
545
                newGa.setAuthority(a);
546
                group.addGrantedAuthority(newGa);
547
                logger.info("New GrantedAuthority '" + a + "' added  to '" + groupName + "'");
548
            }
549
        }
550
        groupService.saveOrUpdate(group);
551
        logger.info("Check of group  '" + groupName + "' done");
552
        return group;
553
    }
554

  
555

  
556
	/**
557
	 * @param args
558
	 */
559
	public static void main(String[] args) {
560
		EuroMedActivator importActivator = new EuroMedActivator();
561
		Source source = berlinModelSource;
562
		ICdmDataSource cdmRepository = CdmDestinations.chooseDestination(args) != null ? CdmDestinations.chooseDestination(args) : cdmDestination;
563

  
564
		importActivator.importEm2CDM(source, cdmRepository, hbm2dll);
565
		if (includePesiExport){
566
			//not available from here since E+M was moved to app-import
567
//			PesiExportActivatorEM exportActivator = new PesiExportActivatorEM();
568
//			exportActivator.doExport(cdmRepository);
569
		}
570

  
571
	}
572

  
573
}
app-import/src/main/java/eu/etaxonomy/cdm/io/berlinModel/in/BerlinModelOccurrenceImport.java
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9

  
10
package eu.etaxonomy.cdm.io.berlinModel.in;
11

  
12
import java.net.URI;
13
import java.sql.ResultSet;
14
import java.sql.SQLException;
15
import java.util.ArrayList;
16
import java.util.HashMap;
17
import java.util.HashSet;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.Set;
21
import java.util.UUID;
22

  
23
import org.apache.commons.lang.StringUtils;
24
import org.apache.log4j.Logger;
25
import org.springframework.stereotype.Component;
26
import org.springframework.transaction.TransactionStatus;
27

  
28
import eu.etaxonomy.cdm.common.CdmUtils;
29
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
30
import eu.etaxonomy.cdm.io.berlinModel.BerlinModelTransformer;
31
import eu.etaxonomy.cdm.io.berlinModel.in.validation.BerlinModelOccurrenceImportValidator;
32
import eu.etaxonomy.cdm.io.common.IOValidator;
33
import eu.etaxonomy.cdm.io.common.ResultSetPartitioner;
34
import eu.etaxonomy.cdm.io.common.Source;
35
import eu.etaxonomy.cdm.io.common.TdwgAreaProvider;
36
import eu.etaxonomy.cdm.model.common.Annotation;
37
import eu.etaxonomy.cdm.model.common.AnnotationType;
38
import eu.etaxonomy.cdm.model.common.CdmBase;
39
import eu.etaxonomy.cdm.model.common.ExtensionType;
40
import eu.etaxonomy.cdm.model.common.Language;
41
import eu.etaxonomy.cdm.model.common.Marker;
42
import eu.etaxonomy.cdm.model.common.MarkerType;
43
import eu.etaxonomy.cdm.model.common.OriginalSourceType;
44
import eu.etaxonomy.cdm.model.common.TermType;
45
import eu.etaxonomy.cdm.model.common.TermVocabulary;
46
import eu.etaxonomy.cdm.model.description.DescriptionElementBase;
47
import eu.etaxonomy.cdm.model.description.Distribution;
48
import eu.etaxonomy.cdm.model.description.PresenceAbsenceTerm;
49
import eu.etaxonomy.cdm.model.description.TaxonDescription;
50
import eu.etaxonomy.cdm.model.location.NamedArea;
51
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
52
import eu.etaxonomy.cdm.model.location.NamedAreaType;
53
import eu.etaxonomy.cdm.model.reference.Reference;
54
import eu.etaxonomy.cdm.model.taxon.Taxon;
55
import eu.etaxonomy.cdm.model.taxon.TaxonBase;
56
import eu.etaxonomy.cdm.strategy.exceptions.UnknownCdmTypeException;
57

  
58

  
59
/**
60
 * @author a.mueller
61
 * @created 20.03.2008
62
 */
63
@Component
64
public class BerlinModelOccurrenceImport  extends BerlinModelImportBase {
65
	private static final String EM_AREA_NAMESPACE = "emArea";
66

  
67
	private static final Logger logger = Logger.getLogger(BerlinModelOccurrenceImport.class);
68

  
69
	public static final String NAMESPACE = "Occurrence";
70

  
71

  
72
	private static int modCount = 5000;
73
	private static final String pluralString = "occurrences";
74
	private static final String dbTableName = "emOccurrence";  //??
75

  
76

  
77
	public BerlinModelOccurrenceImport(){
78
		super(dbTableName, pluralString);
79
	}
80

  
81
	@Override
82
	protected String getIdQuery(BerlinModelImportState state) {
83
		String result = " SELECT occurrenceId FROM " + getTableName();
84
		if (StringUtils.isNotBlank(state.getConfig().getOccurrenceFilter())){
85
			result += " WHERE " +  state.getConfig().getOccurrenceFilter();
86
		}
87
		return result;
88
	}
89

  
90
	@Override
91
	protected String getRecordQuery(BerlinModelImportConfigurator config) {
92
			String emCode = config.isIncludesAreaEmCode()? ", emArea.EMCode" : "";
93
			String strQuery =   //DISTINCT because otherwise emOccurrenceSource creates multiple records for a single distribution
94
            " SELECT DISTINCT PTaxon.RIdentifier AS taxonId, emOccurrence.OccurrenceId, emOccurrence.Native, emOccurrence.Introduced, " +
95
            		" emOccurrence.Cultivated, emOccurrence.Notes occNotes, " +
96
            		" emOccurSumCat.emOccurSumCatId, emOccurSumCat.Short, emOccurSumCat.Description, " +
97
                	" emOccurSumCat.OutputCode, emArea.AreaId, emArea.TDWGCode " + emCode +
98
                " FROM emOccurrence INNER JOIN " +
99
                	" emArea ON emOccurrence.AreaFk = emArea.AreaId INNER JOIN " +
100
                	" PTaxon ON emOccurrence.PTNameFk = PTaxon.PTNameFk AND emOccurrence.PTRefFk = PTaxon.PTRefFk LEFT OUTER JOIN " +
101
                	" emOccurSumCat ON emOccurrence.SummaryStatus = emOccurSumCat.emOccurSumCatId LEFT OUTER JOIN " +
102
                	" emOccurrenceSource ON emOccurrence.OccurrenceId = emOccurrenceSource.OccurrenceFk " +
103
            " WHERE (emOccurrence.OccurrenceId IN (" + ID_LIST_TOKEN + ")  )" +
104
                " ORDER BY PTaxon.RIdentifier";
105
		return strQuery;
106
	}
107

  
108
	private Map<Integer, NamedArea> euroMedAreas = new HashMap<Integer, NamedArea>();
109

  
110

  
111
	@Override
112
	public void doInvoke(BerlinModelImportState state) {
113
		if (state.getConfig().isUseEmAreaVocabulary()){
114
			try {
115
				createEuroMedAreas(state);
116
			} catch (Exception e) {
117
				logger.error("Exception occurred when trying to create euroMed Areas");
118
				e.printStackTrace();
119
				state.setSuccess(false);
120
			}
121
		}
122
		super.doInvoke(state);
123
		//reset
124
		euroMedAreas = new HashMap<Integer, NamedArea>();
125
	}
126

  
127
	private TermVocabulary<NamedArea> createEuroMedAreas(BerlinModelImportState state) throws SQLException {
128
		logger.warn("Start creating E+M areas");
129
		Source source = state.getConfig().getSource();
130
		Reference<?> sourceReference = state.getConfig().getSourceReference();
131

  
132
		TransactionStatus txStatus = this.startTransaction();
133

  
134
		sourceReference = getSourceReference(sourceReference);
135

  
136
		TermVocabulary<NamedArea> euroMedAreas = makeEmptyEuroMedVocabulary();
137

  
138
		MarkerType eurMarkerType = getMarkerType(state, BerlinModelTransformer.uuidEurArea, "eur", "eur Area", "eur");
139
		MarkerType euroMedAreaMarkerType = getMarkerType(state, BerlinModelTransformer.uuidEurMedArea, "EuroMedArea", "EuroMedArea", "EuroMedArea");
140
		ExtensionType isoCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidIsoCode, "IsoCode", "IsoCode", "iso");
141
		ExtensionType tdwgCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidTdwgAreaCode, "TDWG code", "TDWG Area code", "tdwg");
142
		ExtensionType mclCodeExtType = getExtensionType(state, BerlinModelTransformer.uuidMclCode, "MCL code", "MedCheckList code", "mcl");
143
		NamedAreaLevel areaLevelTop = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelTop, "Euro+Med top area level", "Euro+Med top area level. This level is only to be used for the area representing the complete Euro+Med area", "e+m top", null);
144
		NamedAreaLevel areaLevelEm1 = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelFirst, "Euro+Med 1. area level", "Euro+Med 1. area level", "e+m 1.", null);
145
		NamedAreaLevel areaLevelEm2 = getNamedAreaLevel(state, BerlinModelTransformer.uuidEuroMedAreaLevelSecond, "Euro+Med 2. area level", "Euro+Med 2. area level", "Euro+Med 1. area level", null);
146

  
147

  
148
		String sql = "SELECT * , CASE WHEN EMCode = 'EM' THEN 'a' ELSE 'b' END as isEM " +
149
				" FROM emArea " +
150
				" ORDER BY isEM, EMCode";
151
		ResultSet rs = source.getResultSet(sql);
152

  
153
		NamedArea euroMedArea = null;
154
		NamedArea lastLevel2Area = null;
155

  
156
		//euroMedArea (EMCode = 'EM')
157
		rs.next();
158
		euroMedArea = makeSingleEuroMedArea(rs, eurMarkerType, euroMedAreaMarkerType, isoCodeExtType, tdwgCodeExtType, mclCodeExtType,
159
				areaLevelTop, areaLevelEm1 , areaLevelEm2, sourceReference, euroMedArea, lastLevel2Area);
160
		euroMedAreas.addTerm(euroMedArea);
161

  
162
		//all other areas
163
		while (rs.next()){
164
			NamedArea newArea = makeSingleEuroMedArea(rs, eurMarkerType, euroMedAreaMarkerType,
165
					isoCodeExtType, tdwgCodeExtType, mclCodeExtType,
166
					areaLevelTop, areaLevelEm1 , areaLevelEm2, sourceReference, euroMedArea, lastLevel2Area);
167
			euroMedAreas.addTerm(newArea);
168
			if (newArea.getPartOf().equals(euroMedArea)){
169
				lastLevel2Area = newArea;
170
			}
171
			getVocabularyService().saveOrUpdate(euroMedAreas);
172
		}
173

  
174
		commitTransaction(txStatus);
175
		logger.warn("Created E+M areas");
176

  
177
		return euroMedAreas;
178
	}
179

  
180
	/**
181
	 * @param sourceReference
182
	 * @return
183
	 */
184
	private Reference<?> getSourceReference(Reference<?> sourceReference) {
185
		Reference<?> persistentSourceReference = getReferenceService().find(sourceReference.getUuid());  //just to be sure
186
		if (persistentSourceReference != null){
187
			sourceReference = persistentSourceReference;
188
		}
189
		return sourceReference;
190
	}
191

  
192
	/**
193
	 * @param eurMarkerType
194
	 * @param euroMedAreaMarkerType
195
	 * @param isoCodeExtType
196
	 * @param tdwgCodeExtType
197
	 * @param mclCodeExtType
198
	 * @param rs
199
	 * @param areaLevelEm2
200
	 * @param areaLevelEm1
201
	 * @param areaLevelTop
202
	 * @throws SQLException
203
	 */
204
	private NamedArea makeSingleEuroMedArea(ResultSet rs, MarkerType eurMarkerType,
205
			MarkerType euroMedAreaMarkerType, ExtensionType isoCodeExtType,
206
			ExtensionType tdwgCodeExtType, ExtensionType mclCodeExtType,
207
			NamedAreaLevel areaLevelTop, NamedAreaLevel areaLevelEm1, NamedAreaLevel areaLevelEm2,
208
			Reference<?> sourceReference, NamedArea euroMedArea, NamedArea level2Area) throws SQLException {
209
		Integer areaId = rs.getInt("AreaId");
210
		String emCode = nullSafeTrim(rs.getString("EMCode"));
211
		String isoCode = nullSafeTrim(rs.getString("ISOCode"));
212
		String tdwgCode = nullSafeTrim(rs.getString("TDWGCode"));
213
		String unit = nullSafeTrim(rs.getString("Unit"));
214
//				      ,[Status]
215
//				      ,[OutputOrder]
216
		boolean eurMarker = rs.getBoolean("eur");
217
		boolean euroMedAreaMarker = rs.getBoolean("EuroMedArea");
218
		String notes = nullSafeTrim(rs.getString("Notes"));
219
		String mclCode = nullSafeTrim(rs.getString("MCLCode"));
220
		String geoSearch = nullSafeTrim(rs.getString("NameForGeoSearch"));
221

  
222
		if (isBlank(emCode)){
223
			emCode = unit;
224
		}
225

  
226
		//uuid
227
		UUID uuid = BerlinModelTransformer.getEMAreaUuid(emCode);
228
		NamedArea area = (NamedArea)getTermService().find(uuid);
229
		if (area == null){
230
			//label
231
			area = NamedArea.NewInstance(geoSearch, unit, emCode);
232
			if (uuid != null){
233
				area.setUuid(uuid);
234
			}else{
235
				logger.warn("Uuuid for emCode could not be defined: " + emCode);
236
			}
237
		}
238

  
239

  
240
		//code
241
		area.setIdInVocabulary(emCode);
242
		//notes
243
		if (StringUtils.isNotEmpty(notes)){
244
			area.addAnnotation(Annotation.NewInstance(notes, AnnotationType.EDITORIAL(), Language.DEFAULT()));
245
		}
246
		//markers
247
		area.addMarker(Marker.NewInstance(eurMarkerType, eurMarker));
248
		area.addMarker(Marker.NewInstance(euroMedAreaMarkerType, euroMedAreaMarker));
249

  
250
		//extensions
251
		if (isNotBlank(isoCode)){
252
			area.addExtension(isoCode, isoCodeExtType);
253
		}
254
		if (isNotBlank(tdwgCode)){
255
			area.addExtension(tdwgCode, tdwgCodeExtType);
256
		}
257
		if (isNotBlank(mclCode)){
258
			area.addExtension(mclCode, mclCodeExtType);
259
		}
260

  
261
		//type
262
		area.setType(NamedAreaType.ADMINISTRATION_AREA());
263

  
264
		//source
265
		area.addSource(OriginalSourceType.Import, String.valueOf(areaId), EM_AREA_NAMESPACE, sourceReference, null);
266

  
267
		//parent
268
		if (euroMedArea != null){
269
			if (emCode.contains("(")){
270
				area.setPartOf(level2Area);
271
				area.setLevel(areaLevelEm2);
272
			}else{
273
				area.setPartOf(euroMedArea);
274
				area.setLevel(areaLevelEm1);
275
			}
276
		}else{
277
			area.setLevel(areaLevelTop);
278
		}
279
		this.euroMedAreas.put(areaId, area);
280

  
281
		//save
282
		getTermService().saveOrUpdate(area);
283

  
284
		return area;
285
	}
286

  
287
	private String nullSafeTrim(String string) {
288
		if (string == null){
289
			return null;
290
		}else{
291
			return string.trim();
292
		}
293
	}
294

  
295
	/**
296
	 *
297
	 */
298
	private TermVocabulary<NamedArea> makeEmptyEuroMedVocabulary() {
299
		TermType type = TermType.NamedArea;
300
		String description = "Euro+Med area vocabulary";
301
		String label = "E+M areas";
302
		String abbrev = null;
303
		URI termSourceUri = null;
304
		TermVocabulary<NamedArea> result = TermVocabulary.NewInstance(type, description, label, abbrev, termSourceUri);
305

  
306
		result.setUuid(BerlinModelTransformer.uuidVocEuroMedAreas);
307
		getVocabularyService().save(result);
308
		return result;
309
	}
310

  
311
	@Override
312
	public boolean doPartition(ResultSetPartitioner partitioner, BerlinModelImportState state) {
313
		boolean success = true;
314
		Set<TaxonBase> taxaToSave = new HashSet<TaxonBase>();
315

  
316
		Map<String, TaxonBase<?>> taxonMap = partitioner.getObjectMap(BerlinModelTaxonImport.NAMESPACE);
317

  
318
		ResultSet rs = partitioner.getResultSet();
319

  
320
		try {
321
			//map to store the mapping of duplicate berlin model occurrences to their real distributions
322
			//duplicated may occur due to area mappings from BM areas to TDWG areas
323
			Map<Integer, String> duplicateMap = new HashMap<Integer, String>();
324
			int oldTaxonId = -1;
325
			TaxonDescription oldDescription = null;
326
			int i = 0;
327
			int countDescriptions = 0;
328
			int countDistributions = 0;
329
			int countDuplicates = 0;
330
			//for each reference
331
            while (rs.next()){
332

  
333
            	if ((i++ % modCount) == 0 && i!= 1 ){ logger.info("Facts handled: " + (i-1));}
334

  
335
                int occurrenceId = rs.getInt("OccurrenceId");
336
                int newTaxonId = rs.getInt("taxonId");
337
                String notes = nullSafeTrim(rs.getString("occNotes"));
338

  
339
                Integer emStatusId = nullSafeInt(rs, "emOccurSumCatId");
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff