Project

General

Profile

Download (18 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2017 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
package eu.etaxonomy.cdm.dataInserter;
10

    
11
import java.io.IOException;
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.EnumSet;
15
import java.util.HashMap;
16
import java.util.HashSet;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Set;
20
import java.util.UUID;
21

    
22
import org.apache.log4j.Logger;
23
import org.joda.time.DateTime;
24
import org.joda.time.Partial;
25
import org.joda.time.format.DateTimeFormatter;
26
import org.springframework.context.event.ContextRefreshedEvent;
27
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
28
import org.springframework.security.core.GrantedAuthority;
29
import org.springframework.transaction.TransactionStatus;
30

    
31
import com.fasterxml.jackson.core.JsonParseException;
32
import com.fasterxml.jackson.databind.JsonMappingException;
33
import com.fasterxml.jackson.databind.ObjectMapper;
34

    
35
import eu.etaxonomy.cdm.api.application.AbstractDataInserter;
36
import eu.etaxonomy.cdm.api.application.CdmRepository;
37
import eu.etaxonomy.cdm.api.service.pager.Pager;
38
import eu.etaxonomy.cdm.model.agent.AgentBase;
39
import eu.etaxonomy.cdm.model.agent.Institution;
40
import eu.etaxonomy.cdm.model.common.ExtensionType;
41
import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
42
import eu.etaxonomy.cdm.model.common.Group;
43
import eu.etaxonomy.cdm.model.common.TimePeriod;
44
import eu.etaxonomy.cdm.model.name.Registration;
45
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
46
import eu.etaxonomy.cdm.model.name.TaxonName;
47
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
48
import eu.etaxonomy.cdm.model.reference.Reference;
49
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
50
import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmAuthority;
51
import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmPermissionClass;
52
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
53
import eu.etaxonomy.cdm.persistence.query.MatchMode;
54
import eu.etaxonomy.cdm.vaadin.model.registration.KindOfUnitTerms;
55
import eu.etaxonomy.cdm.vaadin.security.RolesAndPermissions;
56

    
57
/**
58
 *
59
 * Can create missing registrations for names which have Extensions of the Type <code>IAPTRegdata.json</code>.
60
 * See https://dev.e-taxonomy.eu/redmine/issues/6621 for further details.
61
 * This feature can be activated by by supplying one of the following jvm command line arguments:
62
 * <ul>
63
 * <li><code>-DregistrationCreate=iapt</code>: create all iapt Registrations if missing</li>
64
 * <li><code>-DregistrationWipeout=iapt</code>: remove all iapt Registrations</li>
65
 * <li><code>-DregistrationWipeout=all</code>: remove all Registrations</li>
66
 * </ul>
67
 * The <code>-DregistrationWipeout</code> commands are executed before the <code>-DregistrationCreate</code> and will not change the name and type designations.
68
 *
69
 * @author a.kohlbecker
70
 * @since May 9, 2017
71
 *
72
 */
73
public class RegistrationRequiredDataInserter extends AbstractDataInserter {
74

    
75
    protected static final String PARAM_NAME_CREATE = "registrationCreate";
76

    
77
    protected static final String PARAM_NAME_WIPEOUT = "registrationWipeout";
78

    
79
    protected static final UUID GROUP_SUBMITTER_UUID = UUID.fromString("c468c6a7-b96c-4206-849d-5a825f806d3e");
80

    
81
    protected static final UUID GROUP_CURATOR_UUID = UUID.fromString("135210d3-3db7-4a81-ab36-240444637d45");
82

    
83
    private static final EnumSet<CRUD> CREATE_READ = EnumSet.of(CRUD.CREATE, CRUD.READ);
84
    private static final EnumSet<CRUD> CREATE_READ_UPDATE_DELETE = EnumSet.of(CRUD.CREATE, CRUD.READ, CRUD.UPDATE, CRUD.DELETE);
85

    
86
    private static final Logger logger = Logger.getLogger(RegistrationRequiredDataInserter.class);
87

    
88
    private ExtensionType extensionTypeIAPTRegData;
89

    
90
    Map<String, Institution> instituteMap = new HashMap<>();
91

    
92
    public static boolean commandsExecuted = false;
93

    
94
    private CdmRepository repo;
95

    
96
    private boolean hasRun = false;
97

    
98
    public void setCdmRepository(CdmRepository repo){
99
      this.repo = repo;
100
    }
101

    
102

    
103
 // ==================== Registration creation ======================= //
104

    
105
    /**
106
     * {@inheritDoc}
107
     */
108
    @Override
109
    public void onApplicationEvent(ContextRefreshedEvent event) {
110

    
111
        if(hasRun){
112
            return;
113
        }
114

    
115
        runAsAuthentication(Role.ROLE_ADMIN);
116

    
117
        insertRequiredData();
118
        executeSuppliedCommands();
119

    
120
        restoreAuthentication();
121

    
122
        hasRun = true;
123
    }
124

    
125
    /**
126
     *
127
     */
128
    private void insertRequiredData() {
129

    
130
        Role roleCuration = RolesAndPermissions.ROLE_CURATION;
131
        if(repo.getGrantedAuthorityService().find(roleCuration.getUuid()) == null){
132
            repo.getGrantedAuthorityService().saveOrUpdate(roleCuration.asNewGrantedAuthority());
133
        }
134

    
135
        Group groupCurator = repo.getGroupService().load(GROUP_CURATOR_UUID, Arrays.asList("grantedAuthorities"));
136
        if(groupCurator == null){
137
            groupCurator = Group.NewInstance();
138
            groupCurator.setUuid(GROUP_CURATOR_UUID);
139
            groupCurator.setName("Curator");
140
        }
141
        assureGroupHas(groupCurator, new CdmAuthority(CdmPermissionClass.REGISTRATION, CREATE_READ_UPDATE_DELETE).toString());
142
        repo.getGroupService().saveOrUpdate(groupCurator);
143

    
144
        Group groupSubmitter = repo.getGroupService().load(GROUP_SUBMITTER_UUID, Arrays.asList("grantedAuthorities"));
145
        if(groupSubmitter == null){
146
            groupSubmitter = Group.NewInstance();
147
            groupSubmitter.setUuid(GROUP_SUBMITTER_UUID);
148
            groupSubmitter.setName("Submitter");
149
        }
150
        assureGroupHas(groupSubmitter, new CdmAuthority(CdmPermissionClass.TAXONNAME, CREATE_READ).toString());
151
        assureGroupHas(groupSubmitter, new CdmAuthority(CdmPermissionClass.TEAMORPERSONBASE, CREATE_READ).toString());
152
        assureGroupHas(groupSubmitter, new CdmAuthority(CdmPermissionClass.REGISTRATION, CREATE_READ).toString());
153
        assureGroupHas(groupSubmitter, new CdmAuthority(CdmPermissionClass.SPECIMENOROBSERVATIONBASE, CREATE_READ).toString());
154
        repo.getGroupService().saveOrUpdate(groupSubmitter);
155

    
156
        if(repo.getTermService().find(KindOfUnitTerms.SPECIMEN().getUuid()) == null){
157
            repo.getTermService().save(KindOfUnitTerms.SPECIMEN());
158
        }
159
        if(repo.getTermService().find(KindOfUnitTerms.PUBLISHED_IMAGE().getUuid()) == null){
160
            repo.getTermService().save(KindOfUnitTerms.PUBLISHED_IMAGE());
161
        }
162
        if(repo.getTermService().find(KindOfUnitTerms.UNPUBLISHED_IMAGE().getUuid()) == null){
163
            repo.getTermService().save(KindOfUnitTerms.UNPUBLISHED_IMAGE());
164
        }
165
        if(repo.getTermService().find(KindOfUnitTerms.CULTURE_METABOLIC_INACTIVE().getUuid()) == null){
166
            repo.getTermService().save(KindOfUnitTerms.CULTURE_METABOLIC_INACTIVE());
167
        }
168

    
169
        // --- remove after release 4.12.0 ------------------------------------------------------
170
        // delete old DerivationEventTypes terms which are no longer used, see #7059
171
        // UUID_PUBLISHED_IMAGE = UUID.fromString("b8cba359-4202-4741-8ed8-4f17ae94b3e3");
172
        // UUID UUID_UNPUBLISHED_IMAGE = UUID.fromString("6cd5681f-0918-4ed6-89a8-bda1480dc890");
173
        // UUID UUID_CULTURE_METABOLIC_INACTIVE = UUID.fromString("eaf1c853-ba8d-4c40-aa0a-56beac96b0d2");
174
        for(UUID uuid : new UUID[]{
175
                UUID.fromString("b8cba359-4202-4741-8ed8-4f17ae94b3e3"),
176
                UUID.fromString("6cd5681f-0918-4ed6-89a8-bda1480dc890"),
177
                UUID.fromString("eaf1c853-ba8d-4c40-aa0a-56beac96b0d2")}){
178
            if(repo.getTermService().find(uuid) != null){
179
                repo.getTermService().delete(uuid);
180
            }
181
        }
182
        // --------------------------------------------------------------------------------------
183

    
184
        repo.getSession().flush();
185

    
186
    }
187

    
188
    private void assureGroupHas(Group group, String authorityString){
189
        boolean authorityExists = false;
190

    
191
        for(GrantedAuthority ga : group.getGrantedAuthorities()){
192
            if((authorityExists = ga.getAuthority().equals(authorityString)) == true){
193
                break;
194
            }
195
        }
196
        if(!authorityExists){
197
            group.addGrantedAuthority(findGrantedAuthority(authorityString));
198
        }
199
    }
200

    
201
    private GrantedAuthorityImpl findGrantedAuthority(String authorityString){
202
        GrantedAuthorityImpl ga = null;
203
        try{
204
            ga = repo.getGrantedAuthorityService().findAuthorityString(authorityString);
205
        } catch (AuthenticationCredentialsNotFoundException e){
206
            e.printStackTrace();
207
        }
208
        if(ga == null){
209
            ga = GrantedAuthorityImpl.NewInstance(authorityString);
210
            repo.getGrantedAuthorityService().save(ga);
211
        }
212
        return ga;
213
    }
214

    
215
    /**
216
     *
217
     */
218

    
219
    private void executeSuppliedCommands() {
220

    
221
        if(commandsExecuted){
222
            // do not run twice
223
            // a second run could take place during initialization of the web context
224
            return;
225
        }
226
        commandsExecuted  = true;
227

    
228
        String wipeoutCmd = System.getProperty(PARAM_NAME_WIPEOUT);
229
        String createCmd = System.getProperty(PARAM_NAME_CREATE);
230

    
231
        // ============ DELETE
232
        if(wipeoutCmd != null && wipeoutCmd.matches("iapt|all")){
233

    
234
            boolean onlyIapt = wipeoutCmd.equals("iapt");
235
            List<UUID> deleteCandidates = new ArrayList<UUID>();
236

    
237
            TransactionStatus tx = repo.startTransaction(true);
238
            List<Registration> allRegs = repo.getRegistrationService().list(null, null, null, null, null);
239
            for(Registration reg : allRegs){
240
                if(onlyIapt){
241
                    try {
242
                        @SuppressWarnings("unchecked")
243
                        Set<String> extensions = reg.getName().getExtensions(getExtensionTypeIAPTRegData());
244
                        deleteCandidates.add(reg.getUuid());
245
                    } catch(NullPointerException e){
246
                        // IGNORE
247
                    }
248
                } else {
249
                    deleteCandidates.add(reg.getUuid());
250
                }
251
            }
252
            repo.commitTransaction(tx);
253
            repo.getRegistrationService().delete(deleteCandidates);
254
        }
255

    
256
        // ============ CREATE
257
        int pageIndex = 0;
258
        if(createCmd != null && createCmd.equals("iapt")){
259

    
260
            DateTimeFormatter dateFormat1 = org.joda.time.format.DateTimeFormat.forPattern("dd.MM.yy").withPivotYear(1950);
261
            DateTimeFormatter dateFormat2 = org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd").withPivotYear(1950);
262

    
263
            TransactionStatus tx = repo.startTransaction(false);
264
            while(true) {
265
                Pager<TaxonName> pager = repo.getNameService().page(null, 1000, pageIndex, null, null);
266
                if(pager.getRecords().isEmpty()){
267
                    break;
268
                }
269
                List<Registration> newRegs = new ArrayList<>(pager.getRecords().size());
270
                for(TaxonName name : pager.getRecords()){
271

    
272
                    Set<String> extensionValues = name.getExtensions(getExtensionTypeIAPTRegData());
273

    
274
                    // there is for sure only one
275
                    if(extensionValues.isEmpty()){
276
                        continue;
277
                    }
278
                    String iaptJson = extensionValues.iterator().next();
279
                    try {
280

    
281
                        IAPTRegData iaptData = new ObjectMapper().readValue(iaptJson, IAPTRegData.class);
282

    
283
                        if(iaptData.getRegId() == null){
284
                            continue;
285
                        }
286

    
287
                        DateTime regDate = null;
288
                        if(iaptData.getDate() != null){
289
                            DateTimeFormatter dateFormat;
290
                            if(iaptData.getDate().matches("\\d{4}-\\d{2}-\\d{2}")){
291
                                dateFormat = dateFormat2;
292
                            } else {
293
                                dateFormat = dateFormat1;
294
                            }
295
                            try {
296
                                regDate = dateFormat.parseDateTime(iaptData.getDate());
297
                                regDate.getYear();
298
                            } catch (Exception e) {
299
                                logger.error("Error parsing date : " + iaptData.getDate(), e);
300
                                continue;
301
                            }
302
                        }
303

    
304
                        Registration reg = Registration.NewInstance();
305
                        reg.setStatus(RegistrationStatus.PUBLISHED);
306
                        reg.setIdentifier("http://phycobank.org/" + iaptData.getRegId());
307
                        reg.setSpecificIdentifier(iaptData.getRegId().toString());
308
                        reg.setInstitution(getInstitution(iaptData.getOffice()));
309

    
310
                        boolean isPhycobankID = false; // Integer.valueOf(reg.getSpecificIdentifier()) >= 100000;
311

    
312
                        Partial youngestDate = null;
313
                        Reference youngestPub = null;
314

    
315
                        // find youngest publication
316

    
317
                        // NOTE:
318
                        // data imported from IAPT does not have typedesignation citations and sometimes no nomref
319

    
320
                        if(isPhycobankID){
321
                            youngestPub = (Reference) name.getNomenclaturalReference();
322
                            youngestDate = partial(youngestPub.getDatePublished());
323

    
324
                            if(name.getTypeDesignations() != null && !name.getTypeDesignations().isEmpty()){
325
                                for(TypeDesignationBase td : name.getTypeDesignations()){
326
                                    if(td.getCitation() == null){
327
                                        continue;
328
                                    }
329
                                    Partial pubdate = partial(td.getCitation().getDatePublished());
330
                                        if(youngestDate.compareTo(pubdate) < 0){
331
                                            youngestDate = pubdate;
332
                                            youngestPub = td.getCitation();
333
                                        }
334
                                }
335
                            }
336
                        }
337

    
338
                        if((isPhycobankID && youngestPub == name.getNomenclaturalReference()) || !isPhycobankID) {
339
                            reg.setName(name);
340
                        } else {
341
                            logger.debug("skipping name published in older referece");
342
                        }
343
                        if(name.getTypeDesignations() != null && !name.getTypeDesignations().isEmpty()){
344
                            // do not add the collection directly to avoid "Found shared references to a collection" problem
345
                            HashSet<TypeDesignationBase> typeDesignations = new HashSet<>(name.getTypeDesignations().size());
346
                            for(TypeDesignationBase td : name.getTypeDesignations()){
347
                                if(td.getCitation() == null && isPhycobankID){
348
                                    logger.error("Missing TypeDesignation Citation in Phycobank data");
349
                                    continue;
350
                                }
351
                                if((isPhycobankID && youngestPub == td.getCitation()) || !isPhycobankID){
352
                                    typeDesignations.add(td);
353
                                } else {
354
                                    logger.debug("skipping typedesignation published in older reference");
355
                                }
356
                            }
357
                            reg.setTypeDesignations(typeDesignations);
358
                        }
359
                        reg.setRegistrationDate(regDate);
360
                        logger.debug("IAPT Registration for " + name.getTitleCache());
361
                        newRegs.add(reg);
362

    
363
                    } catch (JsonParseException e) {
364
                        logger.error("Error parsing IAPTRegData from extension", e);
365
                    } catch (JsonMappingException e) {
366
                        logger.error("Error mapping json from extension to IAPTRegData", e);
367
                    } catch (IOException e) {
368
                        logger.error(e);
369
                    }
370

    
371
                }
372
                repo.getRegistrationService().save(newRegs);
373
                repo.getRegistrationService().getSession().flush();
374
                logger.debug("Registrations saved");
375
                pageIndex++;
376
            }
377
            repo.commitTransaction(tx);
378
        }
379
    }
380

    
381

    
382
    /**
383
     * @param datePublished
384
     * @return
385
     */
386
    private Partial partial(TimePeriod datePublished) {
387
        if(datePublished != null){
388
            if(datePublished.getEnd() != null){
389
                return datePublished.getEnd();
390
            } else {
391
                return datePublished.getStart();
392
            }
393
        }
394
        return null;
395
    }
396

    
397

    
398
    /**
399
     * @param office
400
     * @return
401
     */
402
    private Institution getInstitution(String office) {
403
        Institution institution;
404
        if(instituteMap.containsKey(office)){
405
            institution = instituteMap.get(office);
406
        } else {
407

    
408
            Pager<AgentBase> pager = repo.getAgentService().findByTitle(Institution.class, office, MatchMode.EXACT, null, null, null, null, null);
409
            if(!pager.getRecords().isEmpty()){
410
                institution =  (Institution) pager.getRecords().get(0);
411
            } else {
412
                Institution institute = (Institution) repo.getAgentService().save(Institution.NewNamedInstance(office));
413
                institution = institute;
414
            }
415
            instituteMap.put(office, institution);
416
        }
417
        return institution;
418
    }
419

    
420

    
421
    private ExtensionType getExtensionTypeIAPTRegData() {
422
        if(extensionTypeIAPTRegData == null){
423
            extensionTypeIAPTRegData = (ExtensionType) repo.getTermService().load(UUID.fromString("9be1bfe3-6ba0-4560-af15-86971ab96e09"));
424
        }
425
        return extensionTypeIAPTRegData;
426
    }
427

    
428

    
429

    
430
}
(2-2/2)