Project

General

Profile

Download (9.25 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.Extension;
40
import eu.etaxonomy.cdm.model.common.ExtensionType;
41
import eu.etaxonomy.cdm.model.name.Registration;
42
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
43
import eu.etaxonomy.cdm.model.name.TaxonNameBase;
44
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
45
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
46
import eu.etaxonomy.cdm.persistence.query.MatchMode;
47
import eu.etaxonomy.cdm.vaadin.security.RolesAndPermissions;
48

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

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

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

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

    
64
    private ExtensionType extensionTypeIAPTRegData;
65

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

    
68
    public static boolean commandsExecuted = false;
69

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

    
74
 // ==================== Registration creation ======================= //
75

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

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

    
95
}
96

    
97
    /**
98
     *
99
     */
100

    
101
    private void executeSuppliedCommands() {
102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
213

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

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

    
236

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

    
244

    
245

    
246
}
(2-2/2)