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.GrantedAuthorityImpl;
47
import eu.etaxonomy.cdm.model.common.Group;
48
import eu.etaxonomy.cdm.model.common.Language;
49
import eu.etaxonomy.cdm.model.common.User;
50
import eu.etaxonomy.cdm.model.description.Feature;
51
import eu.etaxonomy.cdm.model.location.NamedArea;
52
import eu.etaxonomy.cdm.model.location.NamedAreaLevel;
53
import eu.etaxonomy.cdm.model.location.NamedAreaType;
54
import eu.etaxonomy.cdm.model.metadata.CdmPreference;
55
import eu.etaxonomy.cdm.model.metadata.PreferencePredicate;
56
import eu.etaxonomy.cdm.model.name.NomenclaturalCode;
57
import eu.etaxonomy.cdm.model.name.Rank;
58
import eu.etaxonomy.cdm.model.taxon.Taxon;
59
import eu.etaxonomy.cdm.model.taxon.TaxonNode;
60
import eu.etaxonomy.cdm.model.term.DefinedTermBase;
61
import eu.etaxonomy.cdm.model.term.FeatureNode;
62
import eu.etaxonomy.cdm.model.term.FeatureTree;
63
import eu.etaxonomy.cdm.model.term.Representation;
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
    //Rename Ranks (still needed?)
366
    private void renameRanks(BerlinModelImportConfigurator config,
367
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
368

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
688

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

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

    
705
	}
706

    
707
}
(5-5/11)