Project

General

Profile

Download (33.1 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 EuroMedActivator {
78
	private static final Logger logger = Logger.getLogger(EuroMedActivator.class);
79

    
80
	//database validation status (create, update, validate ...)
81
	static DbSchemaValidation hbm2dll = DbSchemaValidation.CREATE;
82
//  static final Source berlinModelSource = BerlinModelSources.euroMed_Pub2();
83
	static final Source berlinModelSource = BerlinModelSources.euroMed_BGBM42();
84
//	static final Source berlinModelSource = BerlinModelSources.euroMed_PESI3();
85
//
86
    static final ICdmDataSource cdmDestination = CdmDestinations.localH2();
87
//  static final ICdmDataSource cdmDestination = CdmDestinations.cdm_local_euromed();
88
//    static final ICdmDataSource cdmDestination = CdmDestinations.cdm_local_euromed2();
89
//	static final ICdmDataSource cdmDestination = CdmDestinations.cdm_test_euroMed();
90
//  static final ICdmDataSource cdmDestination = CdmDestinations.cdm_production_euromed();
91

    
92
    //check - import
93
    static final CHECK check = CHECK.CHECK_ONLY;
94

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

    
106
    //taxa
107
    static final boolean doTaxa = true;
108
    static final boolean doFacts = true;
109
    static final boolean doRelTaxa = true;
110
    static final boolean doOccurrences = true;
111
    static final boolean doOccurrenceSources = true;
112
    static final boolean doCommonNames = true;  //currently takes very long
113

    
114
    static final boolean doNamedAreas = true;
115

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

    
119

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

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

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

    
127
    boolean doPreliminaryRefDetailsWithNames = true;
128

    
129
    boolean logNotMatchingOldNames = false;
130
    boolean logMatchingNotExportedOldNames = false;  //true
131
    boolean checkOldNameIsSynonym = false;
132
    boolean includeMANsForOldNameCheck = true;
133

    
134
	static final boolean includePesiExport = false;
135

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

    
143
	// set to zero for unlimited nameFacts
144
	static final int maximumNumberOfNameFacts = 0;
145

    
146
	static final int partitionSize = 2500;
147

    
148

    
149
	//editor - import
150
	static final EDITOR editor = EDITOR.EDITOR_AS_EDITOR;
151

    
152
	//NomenclaturalCode
153
	static final NomenclaturalCode nomenclaturalCode = NomenclaturalCode.ICNAFP;
154

    
155
	//ignore null
156
	static final boolean ignoreNull = false;
157

    
158
	static final boolean switchSpeciesGroup = true;
159

    
160
	static boolean useClassification = true;
161

    
162
	static boolean isSplitTdwgCodes = false;
163
	static boolean useEmAreaVocabulary = true;
164

    
165
	private final boolean removeHttpMapsAnchor = true;
166

    
167

    
168
	static final String infrGenericRankAbbrev = "[unranked]";
169
	static final String infrSpecificRankAbbrev = "[unranked]";
170

    
171
	static boolean useLastScrutinyAsSec = true;
172
	static boolean warnForDifferingSynonymReference = false;
173

    
174

    
175
	static String taxonTable = "v_cdm_exp_taxaAll";
176
	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;
177
	static String relPTaxonIdQuery = " SELECT r.RelPTaxonId "
178
					+ " FROM RelPTaxon AS r "
179
					+ "   INNER JOIN v_cdm_exp_taxaDirect AS a ON r.PTNameFk2 = a.PTNameFk AND r.PTRefFk2 = a.PTRefFk "
180
					+ "   INNER JOIN PTaxon As pt1 ON pt1.PTNameFk = r.PTNameFk1 AND pt1.PTRefFk = r.PTRefFk1 "
181
					+ " 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 Bethalaceae is still imported
182
					+ "     AND NOT (pt1.PTRefFk = 8000000 AND pt1.publishFlag = 0) ";
183
	static String nameIdTable = " v_cdm_exp_namesAll ";
184
	static String referenceIdTable = " v_cdm_exp_refAll ";
185
	static String refDetailFilter =  " RefDetailID IN (SELECT RefDetailID FROM v_cdm_exp_RefDetail) ";
186
	static String factFilter = " factId IN ( SELECT factId FROM v_cdm_exp_factsAll WHERE FactCategoryFk NOT IN (12, 13, 14, 249, 251))";
187
	static String occurrenceFilter = " occurrenceId IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
188
	static String occurrenceSourceFilter = " occurrenceFk IN ( SELECT occurrenceId FROM v_cdm_exp_occurrenceAll )";
189
	static String commonNameFilter = " commonNameId IN ( SELECT commonNameId FROM v_cdm_exp_commonNamesAll )";
190
	static String webMarkerFilter = " TableNameFk <> 500 OR ( RIdentifierFk IN (SELECT RIdentifier FROM v_cdm_exp_taxaAll)) ";
191
	static String authorTeamFilter =  " authorTeamId IN (SELECT drvTab.authorTeamId FROM (SELECT authorTeamId FROM v_cdm_exp_authorTeamsAll) as drvTab) ";
192
	static String authorFilter = " authorId IN (SELECT drvTab.authorId FROM (SELECT authorId FROM v_cdm_exp_authorsAll) as drvTab) ";
193

    
194

    
195

    
196
// **************** ALL *********************
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.setDoFacts(doFacts ^ invers);
222
		config.setDoOccurrence(doOccurrences ^ invers);
223
		config.setDoOccurrenceSources(doOccurrenceSources ^ invers);
224
        config.setDoCommonNames(doCommonNames ^ invers);
225
        config.setDoNamedAreas(doNamedAreas ^ invers);
226

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

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

    
233
		config.setLogNotMatchingOldNames(logNotMatchingOldNames);
234
		config.setLogMatchingNotExportedOldNames(logMatchingNotExportedOldNames);
235
		config.setCheckOldNameIsSynonym(checkOldNameIsSynonym);
236
		config.setIncludeMANsForOldNameCheck(includeMANsForOldNameCheck);
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
        runTransmissionEngine(config, bmImport);
293

    
294
        importShapefile(config, bmImport);
295

    
296
        createPreferences(config, bmImport);
297

    
298
//        markAreasAsHidden(config, bmImport);  //has been moved to BM occurrence import
299

    
300
		System.out.println("End import from BerlinModel ("+ source.getDatabase() + ")...");
301
	}
302

    
303
    private void createPreferences(BerlinModelImportConfigurator config,
304
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
305

    
306
        if (config.isDoUser() && (config.getCheck().isImport() )){
307
            ICdmRepository app = bmImport.getCdmAppController();
308

    
309
            //area vocs
310
            CdmPreference preference = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AvailableDistributionAreaVocabularies, BerlinModelTransformer.uuidVocCaucasusAreas.toString()+";" + BerlinModelTransformer.uuidVocEuroMedAreas.toString());
311
            preference.setAllowOverride(false);
312
            app.getPreferenceService().set(preference);
313

    
314
            //occ status list
315
            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";
316
            CdmPreference statusListPref = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AvailableDistributionAreaVocabularies, status);
317
            statusListPref.setAllowOverride(false);
318
            app.getPreferenceService().set(statusListPref);
319

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

    
325
//            //idInVoc for areas
326
//            CdmPreference distrEditorShowIdInVocForAreas = CdmPreference.NewTaxEditorInstance(PreferencePredicate.Sho.ShowIdInVocabulary, "true");
327
//            distrEditorShowIdInVocForAreas.setAllowOverride(true);
328
//            app.getPreferenceService().set(distrEditorShowIdInVocForAreas);
329
//
330
//            //areas sort order
331
//            //?? correct?
332
//            CdmPreference distrEditorSorted = CdmPreference.NewTaxEditorInstance(PreferencePredicate.AreasSortedByIdInVocabulary, "true");
333
//            distrEditorSorted.setAllowOverride(true);
334
//            app.getPreferenceService().set(distrEditorSorted);
335
//
336
//            //distr. status uses symbol
337
//            //?? correct?
338
//            CdmPreference distrEditorStatusUseSymbols = CdmPreference.NewTaxEditorInstance(PreferencePredicate.ShowSymbolForStatus, "false");
339
//            distrEditorStatusUseSymbols.setAllowOverride(true);
340
//            app.getPreferenceService().set(distrEditorStatusUseSymbols);
341

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

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

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

    
365
        }
366

    
367
    }
368

    
369
    //Rename Ranks (still needed?)
370
    private void renameRanks(BerlinModelImportConfigurator config,
371
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
372

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

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

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

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

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

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

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

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

    
446
    //1. run transmission engine #3979
447
    private void runTransmissionEngine(BerlinModelImportConfigurator config,
448
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
449

    
450
        if (doRunTransmissionEngine && (config.getCheck().isImport()  )  ){
451
            try {
452
                ICdmRepository app = bmImport.getCdmAppController();
453

    
454
                final List<String> term_init_strategy = Arrays.asList(new String []{
455
                        "representations"
456
                });
457

    
458
                UUID uuidSuperAreaLevel = BerlinModelTransformer.uuidEuroMedAreaLevelFirst;
459
                NamedAreaLevel euroMedLevel1 = (NamedAreaLevel)app.getTermService().find(uuidSuperAreaLevel);
460

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

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

    
527
    //2. import shapefile attributes #3979 .2
528
    private void importShapefile(BerlinModelImportConfigurator config,
529
            CdmDefaultImport<BerlinModelImportConfigurator> bmImport) {
530

    
531
        if (config.isDoOccurrence() && (config.getCheck().isImport())){
532

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

    
539
               ICdmRepository app = bmImport.getCdmAppController();
540
               IEditGeoService geoService = (IEditGeoService)app.getBean("editGeoService");
541

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

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

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

    
569
        try {
570
            if (config.isDoRelTaxa() && (config.getCheck().isImport())){
571
                ICdmRepository app = bmImport.getCdmAppController();
572
                TransactionStatus tx = app.startTransaction();
573

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

    
592
                //groups
593
                Group groupEditor = app.getGroupService().load(Group.GROUP_EDITOR_UUID);
594
                groupEditor.addMember(userEraabStraube);
595
                app.getGroupService().saveOrUpdate(groupEditor);
596

    
597
                Group groupProjectManager = app.getGroupService().load(Group.GROUP_PROJECT_MANAGER_UUID);
598
                groupProjectManager.addMember(userEraabStraube);
599
                app.getGroupService().saveOrUpdate(groupProjectManager);
600

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

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

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

    
623
                //groups
624
                groupEditor.addMember(userCichEditor);
625
                app.getGroupService().saveOrUpdate(groupEditor);
626

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

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

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

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

    
671
        Set<GrantedAuthority> grantedAuthorities = group.getGrantedAuthorities();
672

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

    
692

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

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

    
709
	}
710

    
711
}
(6-6/11)