Project

General

Profile

Download (9.19 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.HashMap;
14
import java.util.HashSet;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
import java.util.UUID;
19

    
20
import org.apache.log4j.Logger;
21
import org.joda.time.DateTime;
22
import org.joda.time.format.DateTimeFormatter;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.beans.factory.annotation.Qualifier;
25
import org.springframework.context.ApplicationListener;
26
import org.springframework.context.event.ContextRefreshedEvent;
27
import org.springframework.transaction.TransactionStatus;
28
import org.springframework.transaction.annotation.Transactional;
29

    
30
import com.fasterxml.jackson.core.JsonParseException;
31
import com.fasterxml.jackson.databind.JsonMappingException;
32
import com.fasterxml.jackson.databind.ObjectMapper;
33
import com.vaadin.spring.annotation.SpringComponent;
34

    
35
import eu.etaxonomy.cdm.api.application.CdmRepository;
36
import eu.etaxonomy.cdm.api.service.pager.Pager;
37
import eu.etaxonomy.cdm.model.agent.AgentBase;
38
import eu.etaxonomy.cdm.model.agent.Institution;
39
import eu.etaxonomy.cdm.model.common.ExtensionType;
40
import eu.etaxonomy.cdm.model.name.Registration;
41
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
42
import eu.etaxonomy.cdm.model.name.TaxonName;
43
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
44
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
45
import eu.etaxonomy.cdm.persistence.query.MatchMode;
46
import eu.etaxonomy.cdm.vaadin.security.RolesAndPermissions;
47

    
48
/**
49
 * @author a.kohlbecker
50
 * @since May 9, 2017
51
 *
52
 */
53
@SpringComponent
54
@Transactional(readOnly=true)
55
public class RegistrationRequiredDataInserter implements ApplicationListener<ContextRefreshedEvent>{
56

    
57
    protected static final String PARAM_NAME_CREATE = "registrationCreate";
58

    
59
    protected static final String PARAM_NAME_WIPEOUT = "registrationWipeout";
60

    
61
    private static final Logger logger = Logger.getLogger(RegistrationRequiredDataInserter.class);
62

    
63
    private ExtensionType extensionTypeIAPTRegData;
64

    
65
    Map<String, Institution> instituteMap = new HashMap<>();
66

    
67
    public static boolean commandsExecuted = false;
68

    
69
    @Autowired
70
    @Qualifier("cdmRepository")
71
    private CdmRepository repo;
72

    
73
 // ==================== Registration creation ======================= //
74

    
75
    /**
76
     * {@inheritDoc}
77
     */
78
    @Override
79
    public void onApplicationEvent(ContextRefreshedEvent event) {
80
        insertRequiredData();
81
        executeSuppliedCommands();
82
    }
83

    
84
    /**
85
 *
86
 */
87
private void insertRequiredData() {
88
    Role roleCuration = RolesAndPermissions.ROLE_CURATION;
89
    if(repo.getGrantedAuthorityService().find(roleCuration.getUuid()) == null){
90
        repo.getGrantedAuthorityService().saveOrUpdate(roleCuration.asNewGrantedAuthority());
91
        repo.getGrantedAuthorityService().getSession().flush();
92
    }
93

    
94
}
95

    
96
    /**
97
     *
98
     */
99

    
100
    private void executeSuppliedCommands() {
101

    
102
        if(commandsExecuted){
103
            // do not run twice
104
            // a second run could take place during initialization of the web context
105
            return;
106
        }
107
        commandsExecuted  = true;
108

    
109
        String wipeoutCmd = System.getProperty(PARAM_NAME_WIPEOUT);
110
        String createCmd = System.getProperty(PARAM_NAME_CREATE);
111

    
112
        // ============ DELETE
113
        if(wipeoutCmd != null && wipeoutCmd.matches("iapt|all")){
114

    
115
            boolean onlyIapt = wipeoutCmd.equals("iapt");
116
            List<UUID> deleteCandidates = new ArrayList<UUID>();
117

    
118
            TransactionStatus tx = repo.startTransaction(true);
119
            List<Registration> allRegs = repo.getRegistrationService().list(null, null, null, null, null);
120
            for(Registration reg : allRegs){
121
                if(onlyIapt){
122
                    try {
123
                        @SuppressWarnings("unchecked")
124
                        Set<String> extensions = reg.getName().getExtensions(getExtensionTypeIAPTRegData());
125
                        deleteCandidates.add(reg.getUuid());
126
                    } catch(NullPointerException e){
127
                        // IGNORE
128
                    }
129
                } else {
130
                    deleteCandidates.add(reg.getUuid());
131
                }
132
            }
133
            repo.commitTransaction(tx);
134
            repo.getRegistrationService().delete(deleteCandidates);
135
        }
136

    
137
        // ============ CREATE
138
        int pageIndex = 0;
139
        if(createCmd != null && createCmd.equals("iapt")){
140

    
141
            DateTimeFormatter dateFormat = org.joda.time.format.DateTimeFormat.forPattern("dd.MM.yy").withPivotYear(1950);
142

    
143
            TransactionStatus tx = repo.startTransaction(false);
144
            while(true) {
145
                Pager<TaxonName> pager = repo.getNameService().page(null, 1000, pageIndex, null, null);
146
                if(pager.getRecords().isEmpty()){
147
                    break;
148
                }
149
                List<Registration> newRegs = new ArrayList<>(pager.getRecords().size());
150
                for(TaxonName name : pager.getRecords()){
151

    
152
                    Set<String> extensionValues = name.getExtensions(getExtensionTypeIAPTRegData());
153

    
154
                    // there is for sure only one
155
                    if(extensionValues.isEmpty()){
156
                        continue;
157
                    }
158
                    String iaptJson = extensionValues.iterator().next();
159
                    try {
160

    
161
                        IAPTRegData iaptData = new ObjectMapper().readValue(iaptJson, IAPTRegData.class);
162

    
163
                        if(iaptData.getRegId() == null){
164
                            continue;
165
                        }
166

    
167
                        DateTime regDate = null;
168
                        if(iaptData.getDate() != null){
169
                            try {
170
                                regDate = dateFormat.parseDateTime(iaptData.getDate());
171
                                regDate.getYear();
172
                            } catch (Exception e) {
173
                                logger.error("Error parsing date: " + iaptData.getDate(), e);
174
                                continue;
175
                            }
176
                        }
177

    
178
                        Registration reg = Registration.NewInstance();
179
                        reg.setStatus(RegistrationStatus.PUBLISHED);
180
                        reg.setIdentifier("http://phycobank/" + iaptData.getRegId());
181
                        reg.setSpecificIdentifier(iaptData.getRegId().toString());
182
                        reg.setInstitution(getInstitution(iaptData.getOffice()));
183
                        reg.setName(name);
184
                        if(name.getTypeDesignations() != null && !name.getTypeDesignations().isEmpty()){
185
                            // do not add the collection directly to avoid "Found shared references to a collection" problem
186
                            HashSet<TypeDesignationBase> typeDesignations = new HashSet<>(name.getTypeDesignations().size());
187
                            typeDesignations.addAll(name.getTypeDesignations());
188
                            reg.setTypeDesignations(typeDesignations);
189
                        }
190
                        reg.setRegistrationDate(regDate);
191
                        logger.debug("IAPT Registraion for " + name.getTitleCache());
192
                        newRegs.add(reg);
193

    
194
                    } catch (JsonParseException e) {
195
                        logger.error("Error parsing IAPTRegData from extension", e);
196
                    } catch (JsonMappingException e) {
197
                        logger.error("Error mapping json from extension to IAPTRegData", e);
198
                    } catch (IOException e) {
199
                        logger.error(e);
200
                    }
201

    
202
                }
203
                repo.getRegistrationService().save(newRegs);
204
                repo.getRegistrationService().getSession().flush();
205
                logger.debug("Registrations saved");
206
                pageIndex++;
207
            }
208
            repo.commitTransaction(tx);
209
        }
210
    }
211

    
212

    
213
    /**
214
     * @param office
215
     * @return
216
     */
217
    private Institution getInstitution(String office) {
218
        Institution institution;
219
        if(instituteMap.containsKey(office)){
220
            institution = instituteMap.get(office);
221
        } else {
222

    
223
            Pager<AgentBase> pager = repo.getAgentService().findByTitle(Institution.class, office, MatchMode.EXACT, null, null, null, null, null);
224
            if(!pager.getRecords().isEmpty()){
225
                institution =  (Institution) pager.getRecords().get(0);
226
            } else {
227
                Institution institute = (Institution) repo.getAgentService().save(Institution.NewNamedInstance(office));
228
                institution = institute;
229
            }
230
            instituteMap.put(office, institution);
231
        }
232
        return institution;
233
    }
234

    
235

    
236
    private ExtensionType getExtensionTypeIAPTRegData() {
237
        if(extensionTypeIAPTRegData == null){
238
            extensionTypeIAPTRegData = (ExtensionType) repo.getTermService().load(UUID.fromString("9be1bfe3-6ba0-4560-af15-86971ab96e09"));
239
        }
240
        return extensionTypeIAPTRegData;
241
    }
242

    
243

    
244

    
245
}
(2-2/2)