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.HashMap;
|
15
|
import java.util.HashSet;
|
16
|
import java.util.List;
|
17
|
import java.util.Map;
|
18
|
import java.util.Set;
|
19
|
import java.util.UUID;
|
20
|
|
21
|
import org.apache.log4j.Logger;
|
22
|
import org.joda.time.DateTime;
|
23
|
import org.joda.time.format.DateTimeFormatter;
|
24
|
import org.springframework.context.ApplicationListener;
|
25
|
import org.springframework.context.event.ContextRefreshedEvent;
|
26
|
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
27
|
import org.springframework.security.core.GrantedAuthority;
|
28
|
import org.springframework.transaction.TransactionStatus;
|
29
|
|
30
|
import com.fasterxml.jackson.core.JsonParseException;
|
31
|
import com.fasterxml.jackson.databind.JsonMappingException;
|
32
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
33
|
|
34
|
import eu.etaxonomy.cdm.api.application.CdmRepository;
|
35
|
import eu.etaxonomy.cdm.api.application.RunAsAuthenticator;
|
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.common.GrantedAuthorityImpl;
|
41
|
import eu.etaxonomy.cdm.model.common.Group;
|
42
|
import eu.etaxonomy.cdm.model.name.Registration;
|
43
|
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
|
44
|
import eu.etaxonomy.cdm.model.name.TaxonName;
|
45
|
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
|
46
|
import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
|
47
|
import eu.etaxonomy.cdm.persistence.query.MatchMode;
|
48
|
import eu.etaxonomy.cdm.vaadin.model.registration.DerivationEventTypes;
|
49
|
import eu.etaxonomy.cdm.vaadin.security.RolesAndPermissions;
|
50
|
|
51
|
/**
|
52
|
* @author a.kohlbecker
|
53
|
* @since May 9, 2017
|
54
|
*
|
55
|
*/
|
56
|
public class RegistrationRequiredDataInserter extends RunAsAuthenticator 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
|
// protected static final UUID GROUP_SUBMITTER_UUID = UUID.fromString("c468c6a7-b96c-4206-849d-5a825f806d3e");
|
63
|
|
64
|
protected static final UUID GROUP_CURATOR_UUID = UUID.fromString("135210d3-3db7-4a81-ab36-240444637d45");
|
65
|
|
66
|
private static final Logger logger = Logger.getLogger(RegistrationRequiredDataInserter.class);
|
67
|
|
68
|
private ExtensionType extensionTypeIAPTRegData;
|
69
|
|
70
|
Map<String, Institution> instituteMap = new HashMap<>();
|
71
|
|
72
|
public static boolean commandsExecuted = false;
|
73
|
|
74
|
private CdmRepository repo;
|
75
|
|
76
|
private boolean hasRun = false;
|
77
|
|
78
|
public void setCdmRepository(CdmRepository repo){
|
79
|
this.repo = repo;
|
80
|
}
|
81
|
|
82
|
|
83
|
// ==================== Registration creation ======================= //
|
84
|
|
85
|
/**
|
86
|
* {@inheritDoc}
|
87
|
*/
|
88
|
@Override
|
89
|
public void onApplicationEvent(ContextRefreshedEvent event) {
|
90
|
|
91
|
if(hasRun){
|
92
|
return;
|
93
|
}
|
94
|
|
95
|
runAsAuthentication(Role.ROLE_ADMIN);
|
96
|
|
97
|
insertRequiredData();
|
98
|
executeSuppliedCommands();
|
99
|
|
100
|
restoreAuthentication();
|
101
|
|
102
|
hasRun = true;
|
103
|
}
|
104
|
|
105
|
/**
|
106
|
*
|
107
|
*/
|
108
|
private void insertRequiredData() {
|
109
|
|
110
|
Role roleCuration = RolesAndPermissions.ROLE_CURATION;
|
111
|
if(repo.getGrantedAuthorityService().find(roleCuration.getUuid()) == null){
|
112
|
repo.getGrantedAuthorityService().saveOrUpdate(roleCuration.asNewGrantedAuthority());
|
113
|
}
|
114
|
|
115
|
Group groupCurator = repo.getGroupService().load(GROUP_CURATOR_UUID, Arrays.asList("grantedAuthorities"));
|
116
|
if(groupCurator == null){
|
117
|
groupCurator = Group.NewInstance();
|
118
|
groupCurator.setUuid(GROUP_CURATOR_UUID);
|
119
|
groupCurator.setName("Curator");
|
120
|
}
|
121
|
assureGroupHas(groupCurator, "REGISTRATION[CREATE,READ,UPDATE,DELETE]");
|
122
|
repo.getGroupService().saveOrUpdate(groupCurator);
|
123
|
|
124
|
Group groupEditor = repo.getGroupService().load(Group.groupEditorUuid, Arrays.asList("grantedAuthorities"));
|
125
|
assureGroupHas(groupEditor, "REGISTRATION[CREATE,READ]");
|
126
|
repo.getGroupService().saveOrUpdate(groupEditor);
|
127
|
|
128
|
if(repo.getTermService().find(DerivationEventTypes.PUBLISHED_IMAGE().getUuid()) == null){
|
129
|
repo.getTermService().save(DerivationEventTypes.PUBLISHED_IMAGE());
|
130
|
}
|
131
|
if(repo.getTermService().find(DerivationEventTypes.UNPUBLISHED_IMAGE().getUuid()) == null){
|
132
|
repo.getTermService().save(DerivationEventTypes.UNPUBLISHED_IMAGE());
|
133
|
}
|
134
|
if(repo.getTermService().find(DerivationEventTypes.CULTURE_METABOLIC_INACTIVE().getUuid()) == null){
|
135
|
repo.getTermService().save(DerivationEventTypes.CULTURE_METABOLIC_INACTIVE());
|
136
|
}
|
137
|
repo.getSession().flush();
|
138
|
|
139
|
}
|
140
|
|
141
|
private void assureGroupHas(Group group, String authorityString){
|
142
|
boolean authorityExists = false;
|
143
|
|
144
|
for(GrantedAuthority ga : group.getGrantedAuthorities()){
|
145
|
if((authorityExists = ga.getAuthority().equals(authorityString)) == true){
|
146
|
break;
|
147
|
}
|
148
|
}
|
149
|
if(!authorityExists){
|
150
|
group.addGrantedAuthority(findGrantedAuthority(authorityString));
|
151
|
}
|
152
|
}
|
153
|
|
154
|
private GrantedAuthorityImpl findGrantedAuthority(String authorityString){
|
155
|
GrantedAuthorityImpl ga = null;
|
156
|
try{
|
157
|
ga = repo.getGrantedAuthorityService().findAuthorityString(authorityString);
|
158
|
} catch (AuthenticationCredentialsNotFoundException e){
|
159
|
e.printStackTrace();
|
160
|
}
|
161
|
if(ga == null){
|
162
|
ga = GrantedAuthorityImpl.NewInstance(authorityString);
|
163
|
repo.getGrantedAuthorityService().save(ga);
|
164
|
}
|
165
|
return ga;
|
166
|
}
|
167
|
|
168
|
/**
|
169
|
*
|
170
|
*/
|
171
|
|
172
|
private void executeSuppliedCommands() {
|
173
|
|
174
|
if(commandsExecuted){
|
175
|
// do not run twice
|
176
|
// a second run could take place during initialization of the web context
|
177
|
return;
|
178
|
}
|
179
|
commandsExecuted = true;
|
180
|
|
181
|
String wipeoutCmd = System.getProperty(PARAM_NAME_WIPEOUT);
|
182
|
String createCmd = System.getProperty(PARAM_NAME_CREATE);
|
183
|
|
184
|
// ============ DELETE
|
185
|
if(wipeoutCmd != null && wipeoutCmd.matches("iapt|all")){
|
186
|
|
187
|
boolean onlyIapt = wipeoutCmd.equals("iapt");
|
188
|
List<UUID> deleteCandidates = new ArrayList<UUID>();
|
189
|
|
190
|
TransactionStatus tx = repo.startTransaction(true);
|
191
|
List<Registration> allRegs = repo.getRegistrationService().list(null, null, null, null, null);
|
192
|
for(Registration reg : allRegs){
|
193
|
if(onlyIapt){
|
194
|
try {
|
195
|
@SuppressWarnings("unchecked")
|
196
|
Set<String> extensions = reg.getName().getExtensions(getExtensionTypeIAPTRegData());
|
197
|
deleteCandidates.add(reg.getUuid());
|
198
|
} catch(NullPointerException e){
|
199
|
// IGNORE
|
200
|
}
|
201
|
} else {
|
202
|
deleteCandidates.add(reg.getUuid());
|
203
|
}
|
204
|
}
|
205
|
repo.commitTransaction(tx);
|
206
|
repo.getRegistrationService().delete(deleteCandidates);
|
207
|
}
|
208
|
|
209
|
// ============ CREATE
|
210
|
int pageIndex = 0;
|
211
|
if(createCmd != null && createCmd.equals("iapt")){
|
212
|
|
213
|
DateTimeFormatter dateFormat = org.joda.time.format.DateTimeFormat.forPattern("dd.MM.yy").withPivotYear(1950);
|
214
|
|
215
|
TransactionStatus tx = repo.startTransaction(false);
|
216
|
while(true) {
|
217
|
Pager<TaxonName> pager = repo.getNameService().page(null, 1000, pageIndex, null, null);
|
218
|
if(pager.getRecords().isEmpty()){
|
219
|
break;
|
220
|
}
|
221
|
List<Registration> newRegs = new ArrayList<>(pager.getRecords().size());
|
222
|
for(TaxonName name : pager.getRecords()){
|
223
|
|
224
|
Set<String> extensionValues = name.getExtensions(getExtensionTypeIAPTRegData());
|
225
|
|
226
|
// there is for sure only one
|
227
|
if(extensionValues.isEmpty()){
|
228
|
continue;
|
229
|
}
|
230
|
String iaptJson = extensionValues.iterator().next();
|
231
|
try {
|
232
|
|
233
|
IAPTRegData iaptData = new ObjectMapper().readValue(iaptJson, IAPTRegData.class);
|
234
|
|
235
|
if(iaptData.getRegId() == null){
|
236
|
continue;
|
237
|
}
|
238
|
|
239
|
DateTime regDate = null;
|
240
|
if(iaptData.getDate() != null){
|
241
|
try {
|
242
|
regDate = dateFormat.parseDateTime(iaptData.getDate());
|
243
|
regDate.getYear();
|
244
|
} catch (Exception e) {
|
245
|
logger.error("Error parsing date: " + iaptData.getDate(), e);
|
246
|
continue;
|
247
|
}
|
248
|
}
|
249
|
|
250
|
Registration reg = Registration.NewInstance();
|
251
|
reg.setStatus(RegistrationStatus.PUBLISHED);
|
252
|
reg.setIdentifier("http://phycobank/" + iaptData.getRegId());
|
253
|
reg.setSpecificIdentifier(iaptData.getRegId().toString());
|
254
|
reg.setInstitution(getInstitution(iaptData.getOffice()));
|
255
|
reg.setName(name);
|
256
|
if(name.getTypeDesignations() != null && !name.getTypeDesignations().isEmpty()){
|
257
|
// do not add the collection directly to avoid "Found shared references to a collection" problem
|
258
|
HashSet<TypeDesignationBase> typeDesignations = new HashSet<>(name.getTypeDesignations().size());
|
259
|
typeDesignations.addAll(name.getTypeDesignations());
|
260
|
reg.setTypeDesignations(typeDesignations);
|
261
|
}
|
262
|
reg.setRegistrationDate(regDate);
|
263
|
logger.debug("IAPT Registraion for " + name.getTitleCache());
|
264
|
newRegs.add(reg);
|
265
|
|
266
|
} catch (JsonParseException e) {
|
267
|
logger.error("Error parsing IAPTRegData from extension", e);
|
268
|
} catch (JsonMappingException e) {
|
269
|
logger.error("Error mapping json from extension to IAPTRegData", e);
|
270
|
} catch (IOException e) {
|
271
|
logger.error(e);
|
272
|
}
|
273
|
|
274
|
}
|
275
|
repo.getRegistrationService().save(newRegs);
|
276
|
repo.getRegistrationService().getSession().flush();
|
277
|
logger.debug("Registrations saved");
|
278
|
pageIndex++;
|
279
|
}
|
280
|
repo.commitTransaction(tx);
|
281
|
}
|
282
|
}
|
283
|
|
284
|
|
285
|
/**
|
286
|
* @param office
|
287
|
* @return
|
288
|
*/
|
289
|
private Institution getInstitution(String office) {
|
290
|
Institution institution;
|
291
|
if(instituteMap.containsKey(office)){
|
292
|
institution = instituteMap.get(office);
|
293
|
} else {
|
294
|
|
295
|
Pager<AgentBase> pager = repo.getAgentService().findByTitle(Institution.class, office, MatchMode.EXACT, null, null, null, null, null);
|
296
|
if(!pager.getRecords().isEmpty()){
|
297
|
institution = (Institution) pager.getRecords().get(0);
|
298
|
} else {
|
299
|
Institution institute = (Institution) repo.getAgentService().save(Institution.NewNamedInstance(office));
|
300
|
institution = institute;
|
301
|
}
|
302
|
instituteMap.put(office, institution);
|
303
|
}
|
304
|
return institution;
|
305
|
}
|
306
|
|
307
|
|
308
|
private ExtensionType getExtensionTypeIAPTRegData() {
|
309
|
if(extensionTypeIAPTRegData == null){
|
310
|
extensionTypeIAPTRegData = (ExtensionType) repo.getTermService().load(UUID.fromString("9be1bfe3-6ba0-4560-af15-86971ab96e09"));
|
311
|
}
|
312
|
return extensionTypeIAPTRegData;
|
313
|
}
|
314
|
|
315
|
|
316
|
|
317
|
}
|