forked from DSpace/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 61
/
ResearcherProfileServiceImpl.java
419 lines (326 loc) · 14.9 KB
/
ResearcherProfileServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.profile;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static org.dspace.content.authority.Choices.CF_ACCEPTED;
import static org.dspace.core.Constants.READ;
import static org.dspace.core.Constants.WRITE;
import static org.dspace.eperson.Group.ANONYMOUS;
import java.io.IOException;
import java.net.URI;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.dspace.app.exception.ResourceAlreadyExistsException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.content.MetadataValue;
import org.dspace.content.WorkspaceItem;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.WorkspaceItemService;
import org.dspace.core.Context;
import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.DiscoverResult;
import org.dspace.discovery.IndexableObject;
import org.dspace.discovery.SearchService;
import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.indexobject.IndexableCollection;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.service.GroupService;
import org.dspace.orcid.service.OrcidSynchronizationService;
import org.dspace.profile.service.AfterResearcherProfileCreationAction;
import org.dspace.profile.service.ResearcherProfileService;
import org.dspace.services.ConfigurationService;
import org.dspace.util.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.Assert;
/**
* Implementation of {@link ResearcherProfileService}.
*
* @author Luca Giamminonni (luca.giamminonni at 4science.it)
*
*/
public class ResearcherProfileServiceImpl implements ResearcherProfileService {
private static Logger log = LoggerFactory.getLogger(ResearcherProfileServiceImpl.class);
@Autowired
private ItemService itemService;
@Autowired
private WorkspaceItemService workspaceItemService;
@Autowired
private InstallItemService installItemService;
@Autowired
private ConfigurationService configurationService;
@Autowired
private CollectionService collectionService;
@Autowired
private SearchService searchService;
@Autowired
private GroupService groupService;
@Autowired
private AuthorizeService authorizeService;
@Autowired
private OrcidSynchronizationService orcidSynchronizationService;
@Autowired(required = false)
private List<AfterResearcherProfileCreationAction> afterCreationActions;
@Autowired(required = false)
@Qualifier("sharedWorkspaceAuthorMetadataFields")
private List<String> sharedWorkspaceAuthorMetadataFields;
@PostConstruct
public void postConstruct() {
if (afterCreationActions == null) {
afterCreationActions = Collections.emptyList();
}
}
@Override
public ResearcherProfile findById(Context context, UUID id) throws SQLException, AuthorizeException {
Assert.notNull(id, "An id must be provided to find a researcher profile");
Item profileItem = findResearcherProfileItemById(context, id);
if (profileItem == null) {
return null;
}
return new ResearcherProfile(profileItem);
}
@Override
public ResearcherProfile createAndReturn(Context context, EPerson ePerson)
throws AuthorizeException, SQLException, SearchServiceException {
Item profileItem = findResearcherProfileItemById(context, ePerson.getID());
if (profileItem != null) {
throw new ResourceAlreadyExistsException("A profile is already linked to the provided User");
}
Collection collection = findProfileCollection(context)
.orElseThrow(() -> new IllegalStateException("No collection found for researcher profiles"));
context.turnOffAuthorisationSystem();
Item item = createProfileItem(context, ePerson, collection);
context.restoreAuthSystemState();
ResearcherProfile researcherProfile = new ResearcherProfile(item);
for (AfterResearcherProfileCreationAction afterCreationAction : afterCreationActions) {
afterCreationAction.perform(context, researcherProfile, ePerson);
}
return researcherProfile;
}
@Override
public void deleteById(Context context, UUID id) throws SQLException, AuthorizeException {
Assert.notNull(id, "An id must be provided to find a researcher profile");
Item profileItem = findResearcherProfileItemById(context, id);
if (profileItem == null) {
return;
}
if (isHardDeleteEnabled()) {
deleteItem(context, profileItem);
} else {
removeOwnerMetadata(context, profileItem);
orcidSynchronizationService.unlinkProfile(context, profileItem);
}
}
@Override
public void changeVisibility(Context context, ResearcherProfile profile, boolean visible)
throws AuthorizeException, SQLException {
if (profile.isVisible() == visible) {
return;
}
Item item = profile.getItem();
Group anonymous = groupService.findByName(context, ANONYMOUS);
if (visible) {
authorizeService.addPolicy(context, item, READ, anonymous);
} else {
authorizeService.removeGroupPolicies(context, item, anonymous);
}
}
@Override
public ResearcherProfile claim(Context context, EPerson ePerson, URI uri)
throws SQLException, AuthorizeException, SearchServiceException {
Item profileItem = findResearcherProfileItemById(context, ePerson.getID());
if (profileItem != null) {
throw new ResourceAlreadyExistsException("A profile is already linked to the provided User");
}
Item item = findItemByURI(context, uri)
.orElseThrow(() -> new IllegalArgumentException("No item found by URI " + uri));
if (!item.isArchived() || item.isWithdrawn()) {
throw new IllegalArgumentException(
"Only archived items can be claimed to create a researcher profile. Item ID: " + item.getID());
}
if (!hasProfileType(item)) {
throw new IllegalArgumentException("The provided item has not a profile type. Item ID: " + item.getID());
}
String existingOwner = itemService.getMetadataFirstValue(item, "dspace", "object", "owner", Item.ANY);
if (StringUtils.isNotBlank(existingOwner)) {
throw new IllegalArgumentException("Item with provided uri has already an owner - ID: " + existingOwner);
}
context.turnOffAuthorisationSystem();
itemService.addMetadata(context, item, "dspace", "object", "owner", null,
ePerson.getName(), ePerson.getID().toString(), CF_ACCEPTED);
context.restoreAuthSystemState();
return new ResearcherProfile(item);
}
@Override
public boolean hasProfileType(Item item) {
String profileType = getProfileType();
if (StringUtils.isBlank(profileType)) {
return false;
}
return profileType.equals(itemService.getEntityTypeLabel(item));
}
@Override
public boolean isAuthorOf(Context context, EPerson ePerson, Item item) {
try {
if (CollectionUtils.isEmpty(sharedWorkspaceAuthorMetadataFields) || Objects.isNull(ePerson)) {
return false;
}
ResearcherProfile researcherProfile = findById(context, ePerson.getID());
if (researcherProfile == null) {
return false;
}
String profileItemId = researcherProfile.getItem().getID().toString();
return sharedWorkspaceAuthorMetadataFields.stream()
.flatMap(field -> itemService.getMetadataByMetadataString(item, field).stream())
.anyMatch(metadataValue -> profileItemId.equals(metadataValue.getAuthority()));
} catch (SQLException | AuthorizeException e) {
throw new RuntimeException(e);
}
}
@Override
public String getProfileType() {
return configurationService.getProperty("researcher-profile.entity-type", "Person");
}
private Optional<Item> findItemByURI(final Context context, final URI uri) throws SQLException {
String path = uri.getPath();
UUID uuid = UUIDUtils.fromString(path.substring(path.lastIndexOf("/") + 1));
return ofNullable(itemService.find(context, uuid));
}
/**
* Search for an profile item owned by an eperson with the given id.
*/
private Item findResearcherProfileItemById(Context context, UUID id) throws SQLException, AuthorizeException {
String profileType = getProfileType();
Iterator<Item> items = itemService.findByAuthorityValue(context, "dspace", "object", "owner", id.toString());
while (items.hasNext()) {
Item item = items.next();
String entityType = itemService.getEntityTypeLabel(item);
if (profileType.equals(entityType)) {
return item;
}
}
return null;
}
/**
* Returns a Profile collection based on a configuration or searching for a
* collection of researcher profile type.
*/
private Optional<Collection> findProfileCollection(Context context) throws SQLException, SearchServiceException {
return findConfiguredProfileCollection(context)
.or(() -> findFirstCollectionByProfileEntityType(context));
}
/**
* Create a new profile item for the given ePerson in the provided collection.
*/
private Item createProfileItem(Context context, EPerson ePerson, Collection collection)
throws AuthorizeException, SQLException {
String id = ePerson.getID().toString();
String fullName = ePerson.getFullName();
WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, true);
Item item = workspaceItem.getItem();
itemService.addMetadata(context, item, "dc", "title", null, null, fullName);
itemService.addMetadata(context, item, "person", "email", null, null, ePerson.getEmail());
itemService.addMetadata(context, item, "dspace", "object", "owner", null, fullName, id, CF_ACCEPTED);
item = installItemService.installItem(context, workspaceItem);
context.uncacheEntity(workspaceItem);
if (isNewProfileNotVisibleByDefault()) {
Group anonymous = groupService.findByName(context, ANONYMOUS);
authorizeService.removeGroupPolicies(context, item, anonymous);
}
itemService.addResourcePolicy(context, item, READ, ePerson);
if (isAdditionOfWritePolicyOnProfileEnabled()) {
itemService.addResourcePolicy(context, item, WRITE, ePerson);
}
return reloadItem(context, item);
}
private Optional<Collection> findConfiguredProfileCollection(Context context) throws SQLException {
UUID uuid = UUIDUtils.fromString(configurationService.getProperty("researcher-profile.collection.uuid"));
if (uuid == null) {
return Optional.empty();
}
Collection collection = collectionService.find(context, uuid);
if (collection == null) {
return Optional.empty();
}
if (isNotProfileCollection(collection)) {
log.warn("The configured researcher-profile.collection.uuid "
+ "has an invalid entity type, expected " + getProfileType());
return Optional.empty();
}
return of(collection);
}
@SuppressWarnings("rawtypes")
private Optional<Collection> findFirstCollectionByProfileEntityType(Context context) {
String profileType = getProfileType();
DiscoverQuery discoverQuery = new DiscoverQuery();
discoverQuery.setDSpaceObjectFilter(IndexableCollection.TYPE);
discoverQuery.addFilterQueries("dspace.entity.type:" + profileType);
DiscoverResult discoverResult = search(context, discoverQuery);
List<IndexableObject> indexableObjects = discoverResult.getIndexableObjects();
if (CollectionUtils.isEmpty(indexableObjects)) {
return empty();
}
return ofNullable((Collection) indexableObjects.get(0).getIndexedObject());
}
private boolean isHardDeleteEnabled() {
return configurationService.getBooleanProperty("researcher-profile.hard-delete.enabled");
}
private boolean isAdditionOfWritePolicyOnProfileEnabled() {
return configurationService.getBooleanProperty("researcher-profile.add-write-policy");
}
private boolean isNewProfileNotVisibleByDefault() {
return !configurationService.getBooleanProperty("researcher-profile.set-new-profile-visible");
}
private boolean isNotProfileCollection(Collection collection) {
String entityType = collectionService.getMetadataFirstValue(collection, "dspace", "entity", "type", Item.ANY);
return entityType == null || !entityType.equals(getProfileType());
}
private void removeOwnerMetadata(Context context, Item profileItem) throws SQLException {
List<MetadataValue> metadata = itemService.getMetadata(profileItem, "dspace", "object", "owner", Item.ANY);
itemService.removeMetadataValues(context, profileItem, metadata);
}
private Item reloadItem(Context context, Item item) throws SQLException {
context.uncacheEntity(item);
return context.reloadEntity(item);
}
private void deleteItem(Context context, Item profileItem) throws SQLException, AuthorizeException {
try {
context.turnOffAuthorisationSystem();
itemService.delete(context, profileItem);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
context.restoreAuthSystemState();
}
}
private DiscoverResult search(Context context, DiscoverQuery discoverQuery) {
try {
return searchService.search(context, discoverQuery);
} catch (SearchServiceException e) {
throw new RuntimeException(e);
}
}
}