Project

General

Profile

Download (32.6 KB) Statistics
| Branch: | Revision:
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.ICdmRepository;
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.IImportConfigurator.CHECK;
42
import eu.etaxonomy.cdm.io.common.IImportConfigurator.DO_REFERENCES;
43
import eu.etaxonomy.cdm.io.common.IImportConfigurator.EDITOR;
44
import eu.etaxonomy.cdm.io.common.Source;
45
import eu.etaxonomy.cdm.model.agent.Person;
46
import eu.etaxonomy.cdm.model.common.DefinedTermBase;
47
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
48
import eu.etaxonomy.cdm.model.common.Group;
49
import eu.etaxonomy.cdm.model.common.Language;
50
import eu.etaxonomy.cdm.model.common.Representation;
51
import eu.etaxonomy.cdm.model.common.User;
52
import eu.etaxonomy.cdm.model.description.Feature;
53
import eu.etaxonomy.cdm.model.description.FeatureNode;
54
import eu.etaxonomy.cdm.model.description.FeatureTree;
55
import eu.etaxonomy.cdm.model.location.NamedArea;
56
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
57
import eu.etaxonomy.cdm.model.location.NamedAreaType;
58
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
59
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
60
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
61
import eu.etaxonomy.cdm.model.name.Rank;
62
import eu.etaxonomy.cdm.model.taxon.Taxon;
63
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
64
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
65
import eu.etaxonomy.cdm.persistence.query.MatchMode;
66
import eu.etaxonomy.cdm.persistence.query.OrderHint;
67

    
68

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

    
80
	//database validation status (create, update, validate ...)
81
	static DbSchemaValidation hbm2dll = DbSchemaValidation.CREATE;
82
	static final Source berlinModelSource = BerlinModelSources.euroMed_BGBM42();
83

    
84
//    static final ICdmDataSource cdmDestination = CdmDestinations.localH2();
85
  static final ICdmDataSource cdmDestination = CdmDestinations.cdm_production_euromed_caucasus();
86
//    static final ICdmDataSource cdmDestination = CdmDestinations.cdm_local_euromed_caucasus();
87
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_euroMed();
88

    
89
    //check - import
90
    static final CHECK check = CHECK.IMPORT_WITHOUT_CHECK;
91

    
92
    static final boolean doUser = true;
93
//  //authors
94
    static final boolean doAuthors = true;
95
    //references
96
    static final DO_REFERENCES doReferences =  DO_REFERENCES.ALL;
97
    //names
98
    static final boolean doTaxonNames = true;
99
    static final boolean doRelNames = true;
100
    static final boolean doNameStatus = true;
101
    static final boolean doNameFacts = true;
102

    
103
    //taxa
104
    static final boolean doTaxa = true;
105
    static final boolean doRelTaxa = true;
106

    
107
    static final boolean doNamedAreas = true;
108

    
109
    //not relevant for caucasus
110
    static final boolean doFacts = false;
111
    static final boolean doOccurrences = false;
112
    static final boolean doOccurrenceSources =false;
113
    static final boolean doCommonNames = false;  //currently takes very long
114

    
115
  //serious types do not exist in E+M except for name types which are handled in name relations
116
    static final boolean doTypes = false;  //serious types do not exist in E+M except for name types which are handled in name relations
117

    
118

    
119
    static final boolean doRunTransmissionEngine = false; // (hbm2dll == DbSchemaValidation.VALIDATE);
120

    
121
    //etc.
122
    static final boolean doMarker = false;  //no relevant markers exist
123

    
124
    boolean invers = !(hbm2dll == DbSchemaValidation.CREATE);
125

    
126
    boolean doPreliminaryRefDetailsWithNames = true;
127

    
128
    boolean logNotMatchingOldNames = false;
129
    boolean logMatchingNotExportedOldNames = false;  //true
130
    boolean checkOldNameIsSynonym = true;
131

    
132
	static final boolean includePesiExport = false;
133

    
134
	static final int sourceSecId = 7000000; //500000
135
	static final UUID classificationUuid = UUID.fromString("314a68f9-8449-495a-91c2-92fde8bcf344");
136
	static final boolean useSingleClassification = true;
137
	static final String classificationName = "Euro+Med (Caucasus) 2018";
138
	static final UUID featureTreeUuid = UUID.fromString("6a5e1c2b-ec0d-46c8-9c7d-a2059267ffb7");
139
	static final Object[] featureKeyList = new Integer[]{1, 31, 4, 98, 41};
140

    
141
	// set to zero for unlimited nameFacts
142
	static final int maximumNumberOfNameFacts = 0;
143

    
144
	static final int partitionSize = 2500;
145

    
146

    
147
	//editor - import
148
	static final EDITOR editor = EDITOR.EDITOR_AS_EDITOR;
149

    
150
	//NomenclaturalCode
151
	static final NomenclaturalCode nomenclaturalCode = NomenclaturalCode.ICNAFP;
152

    
153
	//ignore null
154
	static final boolean ignoreNull = false;
155

    
156
	static final boolean switchSpeciesGroup = true;
157

    
158
	static boolean useClassification = true;
159

    
160
	static boolean isSplitTdwgCodes = false;
161
	static boolean useEmAreaVocabulary = true;
162

    
163
	private final boolean removeHttpMapsAnchor = true;
164

    
165

    
166
	static final String infrGenericRankAbbrev = "[unranked]";
167
	static final String infrSpecificRankAbbrev = "[unranked]";
168

    
169
	static boolean useLastScrutinyAsSec = true;
170
	static boolean warnForDifferingSynonymReference = false;
171

    
172

    
173
	static String taxonTable = "v_cdm_exp_taxaAll";
174
	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;
175
	static String relPTaxonIdQuery = " SELECT r.RelPTaxonId "
176
					+ " FROM RelPTaxon AS r "
177
					+ "   INNER JOIN v_cdm_exp_taxaDirect AS a ON r.PTNameFk2 = a.PTNameFk AND r.PTRefFk2 = a.PTRefFk "
178
					+ "   INNER JOIN PTaxon As pt1 ON pt1.PTNameFk = r.PTNameFk1 AND pt1.PTRefFk = r.PTRefFk1 "
179
					+ " WHERE r.RelPTaxonID NOT IN (1874890,1874959,1874932,1874793,1874956,1874971,1874902,1874696) " //Relations to unpublished Kew genus taxa of Bethulaceae which are not imported anymore, but Bethulaceae is still imported
180
					+ "     AND NOT (pt1.PTRefFk = 8000000 AND pt1.publishFlag = 0) ";
181
	static String nameIdTable = " v_cdm_exp_namesAll ";
182
	static String referenceIdTable = " v_cdm_exp_refAll ";
183
	static String refDetailFilter =  " RefDetailID IN (SELECT RefDetailID FROM v_cdm_exp_RefDetail) ";
184
	static String factFilter = " factId IN ( SELECT factId FROM v_cdm_exp_factsAll WHERE FactCategoryFk NOT IN (12, 14, 249, 251))";
185
	static String occurrenceFilter = " occurrenceId IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
186
	static String occurrenceSourceFilter = " occurrenceFk IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
187
	static String commonNameFilter = " commonNameId IN ( SELECT commonNameId FROM v_cdm_exp_commonNamesAll )";
188
	static String webMarkerFilter = " TableNameFk <> 500 OR ( RIdentifierFk IN (SELECT RIdentifier FROM v_cdm_exp_taxaAll)) ";
189
	static String authorTeamFilter =  " authorTeamId IN (SELECT drvTab.authorTeamId FROM (SELECT authorTeamId FROM v_cdm_exp_authorTeamsAll) as drvTab) ";
190
	static String authorFilter = " authorId IN (SELECT drvTab.authorId FROM (SELECT authorId FROM v_cdm_exp_authorsAll) as drvTab) ";
191

    
192

    
193

    
194
// **************** ALL *********************
195

    
196

    
197

    
198

    
199
	public void importEm2CDM (Source source, ICdmDataSource destination, DbSchemaValidation hbm2dll){
200
		System.out.println("Start import from BerlinModel("+ berlinModelSource.getDatabase() + ") to " + cdmDestination.getDatabase() + " ...");
201
		//make BerlinModel Source
202

    
203
		BerlinModelImportConfigurator config = BerlinModelImportConfigurator.NewInstance(source,  destination);
204

    
205
		config.setClassificationName(classificationName);
206

    
207
		config.setClassificationUuid(classificationUuid);
208
		config.setSourceSecId(sourceSecId);
209
		config.setNomenclaturalCode(nomenclaturalCode);
210
		config.setIgnoreNull(ignoreNull);
211

    
212
		config.setDoAuthors(doAuthors ^ invers);
213
		config.setDoReferences(invers ? doReferences.invers() : doReferences);
214
		config.setDoTaxonNames(doTaxonNames ^ invers);
215
		config.setDoRelNames(doRelNames ^ invers);
216
		config.setDoNameStatus(doNameStatus ^ invers);
217
		config.setDoTypes(doTypes);  //always false
218
		config.setDoNameFacts(doNameFacts ^ invers);
219
		config.setDoTaxa(doTaxa ^ invers);
220
		config.setDoRelTaxa(doRelTaxa ^ invers);
221
		config.setDoNamedAreas(doNamedAreas ^ invers);
222

    
223
		config.setDoFacts(doFacts);
224
		config.setDoOccurrence(doOccurrences);
225
		config.setDoOccurrenceSources(doOccurrenceSources);
226
        config.setDoCommonNames(doCommonNames);
227

    
228
		config.setDoMarker(doMarker);
229
		config.setDoUser(doUser ^ invers);
230

    
231
		config.setEuroMed(true);
232
		config.setDoSourceNumber(true);
233

    
234
		config.setLogNotMatchingOldNames(logNotMatchingOldNames);
235
		config.setLogMatchingNotExportedOldNames(logMatchingNotExportedOldNames);
236
		config.setCheckOldNameIsSynonym(checkOldNameIsSynonym);
237

    
238
		config.setUseClassification(useClassification);
239
		config.setSourceRefUuid(BerlinModelTransformer.uuidSourceRefEuroMed);
240
		config.setEditor(editor);
241
		config.setDbSchemaValidation(hbm2dll);
242
		config.setUseLastScrutinyAsSec(useLastScrutinyAsSec);
243
		config.setWarnForDifferingSynonymReference(warnForDifferingSynonymReference);
244

    
245
		// maximum number of name facts to import
246
		config.setMaximumNumberOfNameFacts(maximumNumberOfNameFacts);
247

    
248
		config.setInfrGenericRankAbbrev(infrGenericRankAbbrev);
249
		config.setInfrSpecificRankAbbrev(infrSpecificRankAbbrev);
250
		config.setRemoveHttpMapsAnchor(removeHttpMapsAnchor);
251

    
252
		config.setDoPreliminaryRefDetailsWithNames(doPreliminaryRefDetailsWithNames);
253

    
254
//		filter
255
		config.setTaxonTable(taxonTable);
256
		config.setClassificationQuery(classificationQuery);
257
		config.setRelTaxaIdQuery(relPTaxonIdQuery);
258
		config.setNameIdTable(nameIdTable);
259
		config.setReferenceIdTable(referenceIdTable);
260
		config.setAuthorTeamFilter(authorTeamFilter);
261
		config.setAuthorFilter(authorFilter);
262
		config.setFactFilter(factFilter);
263
		config.setRefDetailFilter(refDetailFilter);
264
		config.setCommonNameFilter(commonNameFilter);
265
		config.setOccurrenceFilter(occurrenceFilter);
266
		config.setOccurrenceSourceFilter(occurrenceSourceFilter);
267
		config.setWebMarkerFilter(webMarkerFilter);
268
		config.setUseSingleClassification(useSingleClassification);
269

    
270
		//TDWG codes
271
		config.setSplitTdwgCodes(isSplitTdwgCodes);
272
		config.setUseEmAreaVocabulary(useEmAreaVocabulary);
273

    
274
		config.setCheck(check);
275
		config.setEditor(editor);
276
		config.setRecordsPerTransaction(partitionSize);
277

    
278
		config.setSwitchSpeciesGroup(switchSpeciesGroup);
279

    
280
		// invoke import
281
		CdmDefaultImport<BerlinModelImportConfigurator> bmImport = new CdmDefaultImport<>();
282
		bmImport.invoke(config);
283

    
284
		renameRanks(config, bmImport);
285

    
286
		createFeatureTree(config, bmImport);
287

    
288
		changeCommonNameLabel(config, bmImport);
289

    
290
		createUsersAndRoles(config, bmImport);
291

    
292
		createPreferences(config, bmImport);
293

    
294
		System.out.println("End import from BerlinModel ("+ source.getDatabase() + ")...");
295
	}
296

    
297
	/**
298
     * @param config
299
     * @param bmImport
300
     */
301
    private void createPreferences(BerlinModelImportConfigurator config,
302
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
303

    
304
        if (config.isDoUser() && (config.getCheck().isImport() )){
305
            ICdmRepository app = bmImport.getCdmAppController();
306
            //area voc
307
            CdmPreference areaVocPref = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AvailableDistributionAreaVocabularies, BerlinModelTransformer.uuidVocCaucasusAreas.toString());
308
            areaVocPref.setAllowOverride(false);
309
            app.getPreferenceService().set(areaVocPref);
310

    
311
            //occ status list
312
            String status ="42946bd6-9c22-45ad-a910-7427e8f60bfd;9eb99fe6-59e2-4445-8e6a-478365bd0fa9;c3ee7048-15b7-4be1-b687-9ce9c1a669d6;643cf9d1-a5f1-4622-9837-82ef961e880b;0c54761e-4887-4788-9dfa-7190c88746e3;83eb0aa0-1a45-495a-a3ca-bf6958b74366;aeec2947-2700-4623-8e32-9e3a430569d1;ddeac4f2-d8fa-43b8-ad7e-ca13abdd32c7;310373bf-7df4-4d02-8cb3-bcc7448805fc;5c397f7b-59ef-4c11-a33c-45691ceda91b;925662c1-bb10-459a-8c53-da5a738ac770;61cee840-801e-41d8-bead-015ad866c2f1;e191e89a-a751-4b0c-b883-7f1de70915c9";
313
            CdmPreference statusListPref = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AvailableDistributionAreaVocabularies, status);
314
            statusListPref.setAllowOverride(false);
315
            app.getPreferenceService().set(statusListPref);
316

    
317

    
318
            //distr. editor activated
319
            CdmPreference distrEditorActive = CdmPreference.NewTaxEditorInstance(PreferencePredicate.DistributionEditorActivated, "true");
320
            statusListPref.setAllowOverride(true);
321
            app.getPreferenceService().set(distrEditorActive);
322

    
323
            //idInVoc for areas
324
            CdmPreference distrEditorShowIdInVocForAreas = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowIdInVocabulary, "true");
325
            distrEditorShowIdInVocForAreas.setAllowOverride(true);
326
            app.getPreferenceService().set(distrEditorShowIdInVocForAreas);
327

    
328
            //areas sort order
329
            CdmPreference distrEditorSorted = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AreasSortedByIdInVocabulary, "true");
330
            distrEditorSorted.setAllowOverride(true);
331
            app.getPreferenceService().set(distrEditorSorted);
332

    
333
            //distr. status uses symbol
334
            //?? correct?
335
            CdmPreference distrEditorStatusUseSymbols = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowSymbolForStatus, "false");
336
            distrEditorStatusUseSymbols.setAllowOverride(true);
337
            app.getPreferenceService().set(distrEditorStatusUseSymbols);
338

    
339

    
340
            //media view
341
            CdmPreference showMediaView = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowMediaView, "false");
342
            showMediaView.setAllowOverride(false);
343
            app.getPreferenceService().set(showMediaView);
344
            //multi classification
345
            CdmPreference multiClassification = CdmPreference.NewTaxEditorInstance(PreferencePredicate.DisableMultiClassification, "false");
346
            multiClassification.setAllowOverride(false);
347
            app.getPreferenceService().set(multiClassification);
348
            //taxon node wizard
349
            CdmPreference showTaxonNodeWizard = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowTaxonNodeWizard, "false");
350
            showTaxonNodeWizard.setAllowOverride(false);
351
            app.getPreferenceService().set(showTaxonNodeWizard);
352

    
353
            //import+export
354
            CdmPreference showImportExportMenu = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowImportExportMenu, "false");
355
            showImportExportMenu.setAllowOverride(true);
356
            app.getPreferenceService().set(showImportExportMenu);
357

    
358
            //show specimen
359
            CdmPreference showSpecimen = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowSpecimen, "false");
360
            showSpecimen.setAllowOverride(false);
361
            app.getPreferenceService().set(showSpecimen);
362
        }
363

    
364
    }
365

    
366
    //Rename Ranks (still needed?)
367
    private void renameRanks(BerlinModelImportConfigurator config,
368
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
369

    
370
        if (config.isDoTaxonNames() && (config.getCheck().isImport() )  ){
371
			ICdmRepository app = bmImport.getCdmAppController();
372
			TransactionStatus tx = app.startTransaction();
373
			try {
374
				Rank sectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
375
				Representation repr = sectBot.getRepresentation(Language.ENGLISH());
376
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
377
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
378
				sectBot.setTitleCache(null, false);  //to definitely update the titleCache also
379
				app.getTermService().saveOrUpdate(sectBot);
380

    
381
				Rank subSectBot = (Rank)app.getTermService().find(Rank.SECTION_BOTANY().getUuid());
382
				repr = subSectBot.getRepresentation(Language.ENGLISH());
383
				repr.setAbbreviatedLabel(repr.getAbbreviatedLabel().replace("(bot.)", "").trim());
384
				repr.setLabel(repr.getLabel().replace("(Botany)", "").trim());
385
				subSectBot.setTitleCache(null, false);  //to definitely update the titleCache also
386
				app.getTermService().saveOrUpdate(subSectBot);
387
				app.commitTransaction(tx);
388
			} catch (Exception e) {
389
			    e.printStackTrace();
390
                logger.error("Exception in renameRanks: " + e.getMessage());
391
			}
392
		}
393
    }
394

    
395
    //create feature tree
396
    private void createFeatureTree(BerlinModelImportConfigurator config,
397
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport){
398
	    if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
399
			try {
400
                ICdmRepository app = bmImport.getCdmAppController();
401
                TransactionStatus tx = app.startTransaction();
402

    
403
                //make feature tree
404
                FeatureTree tree = TreeCreator.flatTree(featureTreeUuid, config.getFeatureMap(), featureKeyList);
405
                tree.setTitleCache("Euro+Med Feature Tree", true);
406
                FeatureNode imageNode = FeatureNode.NewInstance(Feature.IMAGE());
407
                tree.getRoot().addChild(imageNode);
408
                FeatureNode distributionNode = FeatureNode.NewInstance(Feature.DISTRIBUTION());
409
                tree.getRoot().addChild(distributionNode, 1);
410
                FeatureNode commonNameNode = FeatureNode.NewInstance(Feature.COMMON_NAME());
411
                tree.getRoot().addChild(commonNameNode, 2);
412
                app.getFeatureTreeService().saveOrUpdate(tree);
413

    
414
                app.commitTransaction(tx);
415
            } catch (Exception e) {
416
                e.printStackTrace();
417
                logger.error("Exception in createFeatureTree: " + e.getMessage());
418
            }
419
		}
420
    }
421

    
422
    //Change common name label
423
    private void changeCommonNameLabel(BerlinModelImportConfigurator config,
424
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
425
	    if (config.isDoFacts() && (config.getCheck().isImport()  )  ){
426
	        try {
427
                ICdmRepository app = bmImport.getCdmAppController();
428
                TransactionStatus tx = app.startTransaction();
429

    
430
                DefinedTermBase<?> commonNameFeature = app.getTermService().find(Feature.COMMON_NAME().getUuid());
431
                commonNameFeature.setLabel("Common Names", Language.ENGLISH());
432
                commonNameFeature.setTitleCache(null, false);  //to definitely update the titleCache also
433
                app.getTermService().saveOrUpdate(commonNameFeature);
434

    
435
                app.commitTransaction(tx);
436
            } catch (Exception e) {
437
                e.printStackTrace();
438
                logger.error("Exception in changeCommonNameLabel: " + e.getMessage());
439
            }
440
	    }
441
    }
442

    
443
    //1. run transmission engine #3979
444
    private void runTransmissionEngine(BerlinModelImportConfigurator config,
445
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
446

    
447
        if (doRunTransmissionEngine && (config.getCheck().isImport()  )  ){
448
            try {
449
                ICdmRepository app = bmImport.getCdmAppController();
450

    
451
                final List<String> term_init_strategy = Arrays.asList(new String []{
452
                        "representations"
453
                });
454

    
455
                UUID uuidSuperAreaLevel = BerlinModelTransformer.uuidEuroMedAreaLevelFirst;
456
                NamedAreaLevel euroMedLevel1 = (NamedAreaLevel)app.getTermService().find(uuidSuperAreaLevel);
457

    
458
                Pager<NamedArea> areaPager = app.getTermService().list(
459
                        euroMedLevel1,
460
                        (NamedAreaType) null,
461
                        null,
462
                        null,
463
                        (List<OrderHint>) null,
464
                        term_init_strategy);
465
                TransmissionEngineDistribution transmissionEngineDistribution = (TransmissionEngineDistribution)app.getBean("transmissionEngineDistribution");
466
                transmissionEngineDistribution.accumulate(
467
                        AggregationMode.byAreasAndRanks,
468
                        areaPager.getRecords(),
469
                        Rank.UNRANKED_INFRASPECIFIC(),   //or do we even want to start from lower (UNKNOWN?)
470
                        Rank.GENUS(),
471
                        null,
472
                        DefaultProgressMonitor.NewInstance());
473
            } catch (Exception e) {
474
                e.printStackTrace();
475
                logger.error("Exception in markAreasAsHidden: " + e.getMessage());
476
            }
477
        }
478
    }
479

    
480
//    //5.Mark areas to be hidden #3979 .5
481
//    private void markAreasAsHidden(BerlinModelImportConfigurator config,
482
//            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
483
//
484
//        if (config.isDoOccurrence() && (config.getCheck().isImport())){
485
//	        try {
486
//                ICdmRepository app = bmImport.getCdmAppController();
487
//                TransactionStatus tx = app.startTransaction();
488
//
489
//                MarkerType hiddenAreaMarkerType = MarkerType.NewInstance("Used to hide distributions for the named areas in publications", "Hidden Area", null);
490
//                hiddenAreaMarkerType.setUuid(BerlinModelTransformer.uuidHiddenArea);
491
//                @SuppressWarnings("unchecked")
492
//                TermVocabulary<MarkerType> vocUserDefinedMarkerTypes = app.getVocabularyService().find(CdmImportBase.uuidUserDefinedMarkerTypeVocabulary);
493
//                if (vocUserDefinedMarkerTypes == null){
494
//                    String message = "Marker type vocabulary could not be found. Hidden areas not added.";
495
//                    logger.error(message);
496
//                    System.out.println(message);
497
//                }else{
498
//                    vocUserDefinedMarkerTypes.addTerm(hiddenAreaMarkerType);
499
//                    app.getVocabularyService().saveOrUpdate(vocUserDefinedMarkerTypes);
500
//
501
//                    //Add hidden area marker to Rs(C) and Rs(N)
502
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs);
503
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_B);
504
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_C);
505
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_E);
506
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_N);
507
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_K);
508
//                    hideArea(app, hiddenAreaMarkerType, BerlinModelTransformer.uuidRs_W);
509
//                 }
510
//                app.commitTransaction(tx);
511
//            } catch (Exception e) {
512
//                e.printStackTrace();
513
//                logger.error("Exception in markAreasAsHidden: " + e.getMessage());
514
//            }
515
//	    }
516
//    }
517
//
518
//    private void hideArea(ICdmRepository app, MarkerType hiddenAreaMarkerType, UUID areaUuid) {
519
//        NamedArea area = (NamedArea)app.getTermService().find(areaUuid);
520
//        area.addMarker(Marker.NewInstance(hiddenAreaMarkerType, true));
521
//        app.getTermService().saveOrUpdate(area);
522
//    }
523

    
524
    //2. import shapefile attributes #3979 .2
525
    private void importShapefile(BerlinModelImportConfigurator config,
526
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
527

    
528
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
529

    
530
	       try {
531
	           UUID areaVocabularyUuid = BerlinModelTransformer.uuidVocEuroMedAreas;
532
               List<String> idSearchFields = Arrays.asList(new String[]{"EMAREA","PARENT"});
533
               String wmsLayerName = "euromed_2013";
534
               Set<UUID> areaUuidSet = null;
535

    
536
               ICdmRepository app = bmImport.getCdmAppController();
537
               IEditGeoService geoService = (IEditGeoService)app.getBean("editGeoService");
538

    
539
               Map<NamedArea, String> resultMap;
540
               try {
541
                   InputStream in = CaucasusEuroMedActivator.class.getResourceAsStream("/euromed/euromed_2013.csv");
542
                   Reader reader = new InputStreamReader(in, "UTF-8");
543

    
544
                   resultMap = geoService.mapShapeFileToNamedAreas(
545
                               reader, idSearchFields , wmsLayerName , areaVocabularyUuid, areaUuidSet);
546
                   Map<String, String> flatResultMap = new HashMap<>(resultMap.size());
547
                   for(NamedArea area : resultMap.keySet()){
548
                       flatResultMap.put(area.getTitleCache() + " [" + area.getUuid() + "]", resultMap.get(area));
549
                   }
550
               } catch (IOException e) {
551
                    String message = "IOException when reading from mapping file or creating result map.";
552
                    logger.error(message);
553
                    System.out.println(message);
554
               }
555
            } catch (Exception e) {
556
                e.printStackTrace();
557
                logger.error("Exception in importShapefile: " + e.getMessage());
558
            }
559
	    }
560
    }
561

    
562
    //4. Create users and assign roles  #3979
563
    private void createUsersAndRoles(BerlinModelImportConfigurator config,
564
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
565

    
566
        try {
567
            if (config.isDoRelTaxa() && (config.getCheck().isImport())){
568
                ICdmRepository app = bmImport.getCdmAppController();
569
                TransactionStatus tx = app.startTransaction();
570

    
571
                //eraabstraube
572
                String eraabstraube = "e.raabstraube";
573
                List<User> users = app.getUserService().listByUsername(eraabstraube, MatchMode.EXACT, null, null, null, null, null);
574
                User userEraabStraube;
575
                if (users.isEmpty()){
576
                    userEraabStraube = User.NewInstance(eraabstraube, eraabstraube);
577
                }else{
578
                    userEraabStraube = users.get(0);
579
                }
580
                if (userEraabStraube.getPerson() == null){
581
                    Person eckhard = Person.NewInstance();
582
                    eckhard.setFamilyName("von Raab-Straube");
583
                    eckhard.setGivenName("Eckhard");
584
                    eckhard.setPrefix("Dr.");
585
                    userEraabStraube.setPerson(eckhard);
586
                }
587
                app.getUserService().saveOrUpdate(userEraabStraube);
588

    
589
                //groups
590
                Group groupEditor = app.getGroupService().load(Group.GROUP_EDITOR_UUID);
591
                groupEditor.addMember(userEraabStraube);
592
                app.getGroupService().saveOrUpdate(groupEditor);
593

    
594
                Group groupProjectManager = app.getGroupService().load(Group.GROUP_PROJECT_MANAGER_UUID);
595
                groupProjectManager.addMember(userEraabStraube);
596
                app.getGroupService().saveOrUpdate(groupProjectManager);
597

    
598
                String[] publishRoles = new String[]{Role.ROLE_PUBLISH.toString()};
599
                Group groupPublisher = checkGroup(app.getGroupService(), Group.GROUP_PUBLISHER_UUID, "Publisher", publishRoles);
600
                groupPublisher.addMember(userEraabStraube);
601
                app.getGroupService().saveOrUpdate(groupPublisher);
602

    
603
                UUID uuidEuroMedPlantBaseGroup = UUID.fromString("91be42ea-ad04-4458-9836-389277e773db");
604
                String[] emPlantBaseRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]"};
605
                Group euroMedPlantbase = checkGroup(app.getGroupService(), uuidEuroMedPlantBaseGroup, "Euro+Med Plantbase", emPlantBaseRoles);
606
                euroMedPlantbase.addMember(userEraabStraube);
607
                app.getGroupService().saveOrUpdate(euroMedPlantbase);
608

    
609
                //cichorieae-editor
610
                String cichorieaeEditor = "cichorieae-editor";
611
                app.getUserService().listByUsername(cichorieaeEditor, MatchMode.EXACT, null, null, null, null, null);
612
                User userCichEditor;
613
                if (users.isEmpty()){
614
                    userCichEditor = User.NewInstance(cichorieaeEditor, cichorieaeEditor);
615
                }else{
616
                    userCichEditor = users.get(0);
617
                }
618
                app.getUserService().saveOrUpdate(userCichEditor);
619

    
620
                //groups
621
                groupEditor.addMember(userCichEditor);
622
                app.getGroupService().saveOrUpdate(groupEditor);
623

    
624
                UUID uuidCichorieaeSubtree = null;
625
                UUID uuidCichorieae = UUID.fromString("63c7dbeb-b9a2-48b8-a75f-e3fe5e161f7c");
626
                Taxon cich = (Taxon)app.getTaxonService().find(uuidCichorieae);
627
                if (cich != null){
628
                    if (!cich.getTaxonNodes().isEmpty()){
629
                        TaxonNode cichNode = cich.getTaxonNodes().iterator().next();
630
                        uuidCichorieaeSubtree = cichNode.getUuid();
631
                    }
632
                }
633

    
634
                String[] cichorieaeRoles = new String[]{};
635
                if (uuidCichorieaeSubtree != null){
636
                    cichorieaeRoles = new String[]{"TAXONNODE.[CREATE,READ,UPDATE,DELETE]{"+uuidCichorieaeSubtree.toString()+"}"};
637
                }else{
638
                    String message = "Cichorieae node could not be found for cichorieae-editor role";
639
                    logger.warn(message);
640
                    System.out.println(message);
641
                }
642
                UUID uuidCichorieaeGroup = UUID.fromString("a630938d-dd4f-48c2-9406-91def487b11e");
643
                String cichorieaeGroupName = "Cichorieae";
644
                Group cichorieaeGroup = checkGroup(app.getGroupService(), uuidCichorieaeGroup, cichorieaeGroupName, cichorieaeRoles);
645
                cichorieaeGroup.addMember(userCichEditor);
646
                app.getGroupService().saveOrUpdate(cichorieaeGroup);
647

    
648
                app.commitTransaction(tx);
649
            }
650
        } catch (Exception e) {
651
            e.printStackTrace();
652
            logger.error("Exception in createUsersAndRoles: " + e.getMessage());
653
        }
654
    }
655

    
656
	/**
657
	  * copied from {@link FirstDataInserter#checkGroup}
658
     */
659
    private Group checkGroup(IGroupService groupService, UUID groupUuid, String groupName, String[] requiredAuthorities) {
660
        Group group = groupService.load(groupUuid);
661
        if(group == null){
662
            group = Group.NewInstance();
663
            group.setUuid(groupUuid);
664
            logger.info("New Group '" + groupName + "' created");
665
        }
666
        group.setName(groupName); // force name
667

    
668
        Set<GrantedAuthority> grantedAuthorities = group.getGrantedAuthorities();
669

    
670
        for(String a : requiredAuthorities){
671
            boolean isMissing = true;
672
            for(GrantedAuthority ga : grantedAuthorities){
673
                if(a.equals(ga.getAuthority())){
674
                    isMissing = false;
675
                    break;
676
                }
677
            }
678
            if(isMissing){
679
                GrantedAuthorityImpl newGa = GrantedAuthorityImpl.NewInstance(a);
680
                group.addGrantedAuthority(newGa);
681
                logger.info("New GrantedAuthority '" + a + "' added  to '" + groupName + "'");
682
            }
683
        }
684
        groupService.saveOrUpdate(group);
685
        logger.info("Check of group  '" + groupName + "' done");
686
        return group;
687
    }
688

    
689

    
690
	/**
691
	 * @param args
692
	 */
693
	public static void main(String[] args) {
694
		CaucasusEuroMedActivator importActivator = new CaucasusEuroMedActivator();
695
		Source source = berlinModelSource;
696
		ICdmDataSource cdmRepository = CdmDestinations.chooseDestination(args) != null ? CdmDestinations.chooseDestination(args) : cdmDestination;
697

    
698
		importActivator.importEm2CDM(source, cdmRepository, hbm2dll);
699
		if (includePesiExport){
700
			//not available from here since E+M was moved to app-import
701
//			PesiExportActivatorEM exportActivator = new PesiExportActivatorEM();
702
//			exportActivator.doExport(cdmRepository);
703
		}
704
		System.exit(0);
705

    
706
	}
707

    
708
}
(5-5/11)