forked from DSpace/DSpace
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathItemServiceImpl.java
More file actions
2414 lines (2045 loc) · 101 KB
/
ItemServiceImpl.java
File metadata and controls
2414 lines (2045 loc) · 101 KB
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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.content;
import static org.dspace.authority.service.AuthorityValueService.AUTHORITY_CLEANUP_BUSINESS_MODE;
import static org.dspace.authority.service.AuthorityValueService.AUTHORITY_CLEANUP_CLEAN_ALL_MODE;
import static org.dspace.authority.service.AuthorityValueService.AUTHORITY_CLEANUP_PROPERTY_PREFIX;
import static org.dspace.authority.service.AuthorityValueService.REFERENCE;
import static org.dspace.authority.service.AuthorityValueService.SPLIT;
import static org.dspace.content.authority.Choices.CF_UNSET;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.app.metrics.service.CrisMetricsService;
import org.dspace.app.requestitem.RequestItem;
import org.dspace.app.requestitem.service.RequestItemService;
import org.dspace.app.util.AuthorizeUtil;
import org.dspace.authority.service.impl.ItemSearcherByMetadata;
import org.dspace.authorize.AuthorizeConfiguration;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.ResourcePolicy;
import org.dspace.authorize.service.AuthorizeService;
import org.dspace.authorize.service.ResourcePolicyService;
import org.dspace.content.authority.Choices;
import org.dspace.content.dao.ItemDAO;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.BitstreamFormatService;
import org.dspace.content.service.BitstreamService;
import org.dspace.content.service.BundleService;
import org.dspace.content.service.CollectionService;
import org.dspace.content.service.CommunityService;
import org.dspace.content.service.EntityTypeService;
import org.dspace.content.service.InstallItemService;
import org.dspace.content.service.ItemService;
import org.dspace.content.service.MetadataSchemaService;
import org.dspace.content.service.RelationshipService;
import org.dspace.content.service.WorkspaceItemService;
import org.dspace.content.template.TemplateItemValueService;
import org.dspace.content.virtual.VirtualMetadataPopulator;
import org.dspace.content.vo.MetadataValueVO;
import org.dspace.contentreport.QueryPredicate;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogHelper;
import org.dspace.core.exception.SQLRuntimeException;
import org.dspace.discovery.DiscoverQuery;
import org.dspace.discovery.DiscoverResult;
import org.dspace.discovery.DiscoverResultItemIterator;
import org.dspace.discovery.SearchService;
import org.dspace.discovery.SearchServiceException;
import org.dspace.discovery.indexobject.IndexableItem;
import org.dspace.discovery.indexobject.IndexableWorkflowItem;
import org.dspace.discovery.indexobject.IndexableWorkspaceItem;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.Group;
import org.dspace.eperson.service.GroupService;
import org.dspace.eperson.service.SubscribeService;
import org.dspace.event.Event;
import org.dspace.harvest.HarvestedItem;
import org.dspace.harvest.service.HarvestedItemService;
import org.dspace.identifier.DOI;
import org.dspace.identifier.IdentifierException;
import org.dspace.identifier.service.DOIService;
import org.dspace.identifier.service.IdentifierService;
import org.dspace.layout.CrisLayoutBox;
import org.dspace.layout.CrisLayoutField;
import org.dspace.layout.CrisLayoutFieldBitstream;
import org.dspace.layout.CrisLayoutTab;
import org.dspace.layout.service.CrisLayoutTabService;
import org.dspace.orcid.OrcidHistory;
import org.dspace.orcid.OrcidQueue;
import org.dspace.orcid.OrcidToken;
import org.dspace.orcid.model.OrcidEntityType;
import org.dspace.orcid.service.OrcidHistoryService;
import org.dspace.orcid.service.OrcidQueueService;
import org.dspace.orcid.service.OrcidSynchronizationService;
import org.dspace.orcid.service.OrcidTokenService;
import org.dspace.profile.service.ResearcherProfileService;
import org.dspace.qaevent.dao.QAEventsDAO;
import org.dspace.services.ConfigurationService;
import org.dspace.versioning.Version;
import org.dspace.versioning.VersionHistory;
import org.dspace.versioning.service.VersionHistoryService;
import org.dspace.versioning.service.VersioningService;
import org.dspace.workflow.WorkflowItemService;
import org.dspace.workflow.factory.WorkflowServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Service implementation for the Item object.
* This class is responsible for all business logic calls for the Item object and is autowired by spring.
* This class should never be accessed directly.
*
* @author kevinvandevelde at atmire.com
*/
public class ItemServiceImpl extends DSpaceObjectServiceImpl<Item> implements ItemService {
/**
* log4j category
*/
private static final Logger log = org.apache.logging.log4j.LogManager.getLogger();
@Autowired(required = true)
protected ItemDAO itemDAO;
@Autowired(required = true)
protected CommunityService communityService;
@Autowired(required = true)
protected GroupService groupService;
@Autowired(required = true)
protected AuthorizeService authorizeService;
@Autowired(required = true)
protected BundleService bundleService;
@Autowired(required = true)
protected BitstreamFormatService bitstreamFormatService;
@Autowired(required = true)
protected MetadataSchemaService metadataSchemaService;
@Autowired(required = true)
protected BitstreamService bitstreamService;
@Autowired(required = true)
protected InstallItemService installItemService;
@Autowired(required = true)
protected SearchService searchService;
@Autowired(required = true)
protected ResourcePolicyService resourcePolicyService;
@Autowired(required = true)
protected CollectionService collectionService;
@Autowired(required = true)
protected IdentifierService identifierService;
@Autowired(required = true)
protected DOIService doiService;
@Autowired(required = true)
protected VersioningService versioningService;
@Autowired(required = true)
protected HarvestedItemService harvestedItemService;
@Autowired(required = true)
protected ConfigurationService configurationService;
@Autowired(required = true)
protected WorkspaceItemService workspaceItemService;
@Autowired(required = true)
protected WorkflowItemService workflowItemService;
@Autowired
private TemplateItemValueService templateItemValueService;
@Autowired(required = true)
protected RelationshipService relationshipService;
@Autowired(required = true)
protected VirtualMetadataPopulator virtualMetadataPopulator;
@Autowired(required = true)
private RelationshipMetadataService relationshipMetadataService;
@Autowired(required = true)
private EntityTypeService entityTypeService;
@Autowired
private OrcidTokenService orcidTokenService;
@Autowired(required = true)
private OrcidHistoryService orcidHistoryService;
@Autowired(required = true)
private OrcidQueueService orcidQueueService;
@Autowired(required = true)
private OrcidSynchronizationService orcidSynchronizationService;
@Autowired
private CrisLayoutTabService crisLayoutTabService;
@Autowired(required = true)
protected SubscribeService subscribeService;
@Autowired(required = true)
protected CrisMetricsService crisMetricsService;
@Autowired(required = true)
private ResearcherProfileService researcherProfileService;
@Autowired(required = true)
private RequestItemService requestItemService;
@Autowired
private VersionHistoryService versionHistoryService;
@Autowired
private List<ItemSearcherByMetadata> itemSearcherByMetadata;
@Autowired
private QAEventsDAO qaEventsDao;
protected ItemServiceImpl() {
}
@Override
public Thumbnail getThumbnail(Context context, Item item, boolean requireOriginal) throws SQLException {
// Search the thumbnail using the configuration
Thumbnail thumbnail = thumbnailLayoutTabConfigurationStrategy(context, item, requireOriginal);
if (thumbnail != null) {
return thumbnail;
}
return null;
}
/**
* @param context
* @param item
* @throws SQLException
*/
private Thumbnail thumbnailLayoutTabConfigurationStrategy(Context context, Item item, boolean requireOriginal)
throws SQLException {
List<CrisLayoutTab> crisLayoutTabs = crisLayoutTabService.findByItem(context, String.valueOf(item.getID()));
List<CrisLayoutField> thumbFields = getThumbnailFields(crisLayoutTabs);
if (CollectionUtils.isEmpty(thumbFields)) {
// If no thumbnail is retrieved by the first strategy
// then use the fallback strategy
Bitstream thumbBitstream = null;
List<Bundle> originalBundles = getBundles(item, "ORIGINAL");
Bitstream primaryBitstream = null;
if (CollectionUtils.isNotEmpty(originalBundles)) {
primaryBitstream = originalBundles.get(0).getPrimaryBitstream();
}
if (primaryBitstream == null) {
if (requireOriginal) {
primaryBitstream = bitstreamService.getFirstBitstream(item, "ORIGINAL");
}
thumbBitstream = bitstreamService.getFirstBitstream(item, "THUMBNAIL");
}
if (primaryBitstream != null) {
thumbBitstream = bitstreamService.getThumbnail(context, primaryBitstream);
if (thumbBitstream == null) {
thumbBitstream = bitstreamService.getFirstBitstream(item, "THUMBNAIL");
if (!bitstreamService.isValidThumbnail(context, thumbBitstream)) {
thumbBitstream = null;
}
}
}
if (thumbBitstream != null) {
return new Thumbnail(thumbBitstream, primaryBitstream);
}
}
return retrieveThumbnailFromFields(context, item, thumbFields);
}
/**
* @param context
* @param item
* @param thumbFields
* @return Thumbnail
* @throws SQLException
*/
private Thumbnail retrieveThumbnailFromFields(Context context, Item item,
List<CrisLayoutField> thumbFields) throws SQLException {
for (CrisLayoutField thumbField : thumbFields) {
if (!(thumbField instanceof CrisLayoutFieldBitstream)) {
continue;
}
CrisLayoutFieldBitstream thumbFieldBitstream = (CrisLayoutFieldBitstream)thumbField;
String bundle = thumbFieldBitstream.getBundle();
MetadataField metadata = thumbFieldBitstream.getMetadataField();
String value = thumbFieldBitstream.getMetadataValue();
Thumbnail thumbnail = retrieveThumbnail(context, item, bundle, metadata, value);
if (thumbnail != null) {
return thumbnail;
}
}
return null;
}
/**
* @param crisLayoutTabs
* @return List<CrisLayoutField>
*/
private List<CrisLayoutField> getThumbnailFields(List<CrisLayoutTab> crisLayoutTabs) {
List<CrisLayoutField> thumbFields = new LinkedList<>();
for (CrisLayoutTab tab : crisLayoutTabs) {
for (CrisLayoutBox box : tab.getBoxes()) {
thumbFields.addAll(box.getLayoutFields().stream()
.filter(field -> field.getRendering() != null && field.getRendering().equals("thumbnail"))
.collect(Collectors.toList()));
}
}
return thumbFields;
}
/**
* @param context
* @param item
* @param bundle
* @param value
* @throws SQLException
* @return Bitstream
*/
private Thumbnail retrieveThumbnail(Context context, Item item, String bundle,
MetadataField metadataField, String value) throws SQLException {
List<Bundle> bundles = getBundles(item, bundle);
if (CollectionUtils.isNotEmpty(bundles)) {
Optional<Bitstream> primaryBitstream = bundles.get(0).getBitstreams().stream().filter(bitstream -> {
return bitstream.getMetadata().stream().anyMatch(metadataValue -> {
if (metadataField != null) {
return metadataValue.getMetadataField().getID().equals(metadataField.getID())
&& metadataValue.getValue() != null
&& metadataValue.getValue().equalsIgnoreCase(value);
} else {
return true;
}
});
}).findFirst();
if (primaryBitstream.isEmpty()) {
return null;
}
Bitstream thumbBitstream = bitstreamService.getThumbnail(context, primaryBitstream.get());
// If the thumbnail is not available return the non thumbnail bitstream
// retrieved in the previous steps
if (thumbBitstream != null) {
return new Thumbnail(thumbBitstream, primaryBitstream.get());
} else {
return new Thumbnail(primaryBitstream.get(), primaryBitstream.get());
}
}
return null;
}
@Override
public Item find(Context context, UUID id) throws SQLException {
Item item = itemDAO.findByID(context, Item.class, id);
if (item == null) {
if (log.isDebugEnabled()) {
log.debug(LogHelper.getHeader(context, "find_item", "not_found,item_id=" + id));
}
return null;
}
// not null, return item
if (log.isDebugEnabled()) {
log.debug(LogHelper.getHeader(context, "find_item", "item_id=" + id));
}
return item;
}
@Override
public Item create(Context context, WorkspaceItem workspaceItem) throws SQLException, AuthorizeException {
return create(context, workspaceItem, null);
}
@Override
public Item create(Context context, WorkspaceItem workspaceItem,
UUID uuid) throws SQLException, AuthorizeException {
Collection collection = workspaceItem.getCollection();
authorizeService.authorizeAction(context, collection, Constants.ADD);
if (workspaceItem.getItem() != null) {
throw new IllegalArgumentException(
"Attempting to create an item for a workspace item that already contains an item");
}
Item item = createItem(context, uuid);
workspaceItem.setItem(item);
log.info(LogHelper.getHeader(context, "create_item", "item_id=" + item.getID()));
return item;
}
@Override
public Item createTemplateItem(Context context, Collection collection) throws SQLException, AuthorizeException {
if (collection == null || collection.getTemplateItem() != null) {
throw new IllegalArgumentException("Collection is null or already contains template item.");
}
AuthorizeUtil.authorizeManageTemplateItem(context, collection);
if (collection.getTemplateItem() == null) {
Item template = createItem(context);
collection.setTemplateItem(template);
template.setTemplateItemOf(collection);
log.info(LogHelper.getHeader(context, "create_template_item",
"collection_id=" + collection.getID() + ",template_item_id="
+ template.getID()));
return template;
}
return collection.getTemplateItem();
}
@Override
public void populateWithTemplateItemMetadata(Context context, Collection collection, boolean template, Item item)
throws SQLException {
Item templateItem = collection.getTemplateItem();
Optional<MetadataValue> colEntityType = getDSpaceEntityType(collection);
Optional<MetadataValue> templateItemEntityType = getDSpaceEntityType(templateItem);
if (colEntityType.isPresent() && templateItemEntityType.isPresent() &&
!StringUtils.equals(colEntityType.get().getValue(), templateItemEntityType.get().getValue())) {
throw new IllegalStateException("The template item has entity type : (" +
templateItemEntityType.get().getValue() + ") different than collection entity type : " +
colEntityType.get().getValue());
}
if (colEntityType.isPresent() && templateItemEntityType.isEmpty()) {
MetadataValue original = colEntityType.get();
MetadataField metadataField = original.getMetadataField();
MetadataSchema metadataSchema = metadataField.getMetadataSchema();
// NOTE: dspace.entity.type = <blank> does not make sense
// the collection entity type is by default blank when a collection is first created
if (StringUtils.isNotBlank(original.getValue())) {
addMetadata(context, item, metadataSchema.getName(), metadataField.getElement(),
metadataField.getQualifier(), original.getLanguage(), original.getValue());
}
}
if (template && (templateItem != null)) {
List<MetadataValue> md = getMetadata(templateItem, Item.ANY, Item.ANY, Item.ANY, Item.ANY);
for (MetadataValue aMd : md) {
MetadataField metadataField = aMd.getMetadataField();
MetadataSchema metadataSchema = metadataField.getMetadataSchema();
List<MetadataValueVO> metadataValueFromTemplateList = templateItemValueService.value(context, item,
templateItem, aMd);
for (MetadataValueVO metadataValueFromTemplate : metadataValueFromTemplateList) {
addMetadata(context, item, metadataSchema.getName(), metadataField.getElement(),
metadataField.getQualifier(), aMd.getLanguage(),
metadataValueFromTemplate.getValue(), metadataValueFromTemplate.getAuthority(),
metadataValueFromTemplate.getConfidence());
}
}
}
}
private Optional<MetadataValue> getDSpaceEntityType(DSpaceObject dSpaceObject) {
return Objects.nonNull(dSpaceObject) ? dSpaceObject.getMetadata()
.stream()
.filter(x -> x.getMetadataField().toString('.')
.equalsIgnoreCase("dspace.entity.type"))
.findFirst()
: Optional.empty();
}
@Override
public Iterator<Item> findAll(Context context) throws SQLException {
return itemDAO.findAll(context, true);
}
@Override
public Iterator<Item> findAll(Context context, Integer limit, Integer offset) throws SQLException {
return itemDAO.findAll(context, true, limit, offset);
}
@Override
public Iterator<Item> findAllUnfiltered(Context context) throws SQLException {
return itemDAO.findAll(context, true, true);
}
@Override
public Iterator<Item> findAllRegularItems(Context context) throws SQLException {
return itemDAO.findAllRegularItems(context);
}
@Override
public Iterator<Item> findBySubmitter(Context context, EPerson eperson) throws SQLException {
return itemDAO.findBySubmitter(context, eperson);
}
@Override
public Iterator<Item> findBySubmitter(Context context, EPerson eperson, boolean retrieveAllItems)
throws SQLException {
return itemDAO.findBySubmitter(context, eperson, retrieveAllItems);
}
@Override
public Iterator<Item> findBySubmitterDateSorted(Context context, EPerson eperson, Integer limit)
throws SQLException {
MetadataField metadataField = metadataFieldService
.findByElement(context, MetadataSchemaEnum.DC.getName(), "date", "accessioned");
if (metadataField == null) {
throw new IllegalArgumentException(
"Required metadata field '" +
MetadataSchemaEnum.DC.getName() + ".date.accessioned' doesn't exist!");
}
return itemDAO.findBySubmitter(context, eperson, metadataField, limit);
}
@Override
public Iterator<Item> findByCollection(Context context, Collection collection) throws SQLException {
return findByCollection(context, collection, null, null);
}
@Override
public Iterator<Item> findByCollection(Context context, Collection collection, Integer limit, Integer offset)
throws SQLException {
return itemDAO.findArchivedByCollection(context, collection, limit, offset);
}
@Override
public Iterator<Item> findByCollectionMapping(Context context, Collection collection, Integer limit, Integer offset)
throws SQLException {
return itemDAO.findArchivedByCollectionExcludingOwning(context, collection, limit, offset);
}
@Override
public int countByCollectionMapping(Context context, Collection collection) throws SQLException {
return itemDAO.countArchivedByCollectionExcludingOwning(context, collection);
}
@Override
public Iterator<Item> findAllByCollection(Context context, Collection collection) throws SQLException {
return itemDAO.findAllByCollection(context, collection);
}
@Override
public Iterator<Item> findAllByCollection(Context context, Collection collection, Integer limit, Integer offset)
throws SQLException {
return itemDAO.findAllByCollection(context, collection, limit, offset);
}
@Override
public Iterator<Item> findInArchiveOrWithdrawnDiscoverableModifiedSince(Context context, Date since)
throws SQLException {
return itemDAO.findAll(context, true, true, true, since);
}
@Override
public Iterator<Item> findInArchiveOrWithdrawnNonDiscoverableModifiedSince(Context context, Date since)
throws SQLException {
return itemDAO.findAll(context, true, true, false, since);
}
@Override
public void updateLastModified(Context context, Item item) throws SQLException, AuthorizeException {
item.setLastModified(new Date());
update(context, item);
//Also fire a modified event since the item HAS been modified
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(), null, getIdentifiers(context, item)));
}
@Override
public void updateLastModifiedDate(Context context, Item item, Date lastModifiedDate)
throws SQLException, AuthorizeException {
if (!canEdit(context, item)) {
authorizeService.authorizeAction(context, item, Constants.WRITE);
}
log.info(LogHelper.getHeader(context, "update_item", "item_id="
+ item.getID()));
super.update(context, item);
// Set sequence IDs for bitstreams in Item. To guarantee uniqueness,
// sequence IDs are assigned in sequential order (starting with 1)
int sequence = 0;
List<Bundle> bunds = item.getBundles();
// find the highest current sequence number
for (Bundle bund : bunds) {
List<Bitstream> streams = bund.getBitstreams();
for (Bitstream bitstream : streams) {
if (bitstream.getSequenceID() > sequence) {
sequence = bitstream.getSequenceID();
}
}
}
// start sequencing bitstreams without sequence IDs
sequence++;
for (Bundle bund : bunds) {
List<Bitstream> streams = bund.getBitstreams();
for (Bitstream stream : streams) {
if (stream.getSequenceID() < 0) {
stream.setSequenceID(sequence);
sequence++;
bitstreamService.update(context, stream);
// modified = true;
}
}
}
if (item.isMetadataModified() || item.isModified()) {
item.setLastModified(lastModifiedDate);
// Set the last modified date
itemDAO.save(context, item);
if (item.isMetadataModified()) {
context.addEvent(new Event(Event.MODIFY_METADATA, item.getType(), item.getID(), item.getDetails(),
getIdentifiers(context, item)));
}
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(),
null, getIdentifiers(context, item)));
item.clearModified();
item.clearDetails();
}
//Also fire a modified event since the item HAS been modified
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(), null, getIdentifiers(context, item)));
}
@Override
public boolean isIn(Item item, Collection collection) throws SQLException {
List<Collection> collections = item.getCollections();
return collections != null && collections.contains(collection);
}
@Override
public List<Community> getCommunities(Context context, Item item) throws SQLException {
List<Community> result = new ArrayList<>();
List<Collection> collections = item.getCollections();
for (Collection collection : collections) {
result.addAll(communityService.getAllParents(context, collection));
}
return result;
}
@Override
public List<Bundle> getBundles(Item item, String name) throws SQLException {
List<Bundle> matchingBundles = new ArrayList<>();
// now only keep bundles with matching names
List<Bundle> bunds = item.getBundles();
for (Bundle bund : bunds) {
if (name.equals(bund.getName())) {
matchingBundles.add(bund);
}
}
return matchingBundles;
}
@Override
public void addBundle(Context context, Item item, Bundle bundle) throws SQLException, AuthorizeException {
// Check authorisation
authorizeService.authorizeAction(context, item, Constants.ADD);
log.info(LogHelper.getHeader(context, "add_bundle", "item_id="
+ item.getID() + ",bundle_id=" + bundle.getID()));
// Check it's not already there
if (item.getBundles().contains(bundle)) {
// Bundle is already there; no change
return;
}
// now add authorization policies from owning item
// hmm, not very "multiple-inclusion" friendly
authorizeService.inheritPolicies(context, item, bundle);
// Add the bundle to in-memory list
item.addBundle(bundle);
bundle.addItem(item);
context.addEvent(new Event(Event.ADD, Constants.ITEM, item.getID(),
Constants.BUNDLE, bundle.getID(), bundle.getName(),
getIdentifiers(context, item)));
}
@Override
public void removeBundle(Context context, Item item, Bundle bundle)
throws SQLException, AuthorizeException, IOException {
// Check authorisation
authorizeService.authorizeAction(context, item, Constants.REMOVE);
log.info(LogHelper.getHeader(context, "remove_bundle", "item_id="
+ item.getID() + ",bundle_id=" + bundle.getID()));
context.addEvent(new Event(Event.REMOVE, Constants.ITEM, item.getID(),
Constants.BUNDLE, bundle.getID(), bundle.getName(), getIdentifiers(context, item)));
bundleService.delete(context, bundle);
}
@Override
public Bitstream createSingleBitstream(Context context, InputStream is, Item item, String name)
throws AuthorizeException, IOException, SQLException {
// Authorisation is checked by methods below
// Create a bundle
Bundle bnd = bundleService.create(context, item, name);
Bitstream bitstream = bitstreamService.create(context, bnd, is);
addBundle(context, item, bnd);
// FIXME: Create permissions for new bundle + bitstream
return bitstream;
}
@Override
public Bitstream createSingleBitstream(Context context, InputStream is, Item item)
throws AuthorizeException, IOException, SQLException {
return createSingleBitstream(context, is, item, "ORIGINAL");
}
@Override
public List<Bitstream> getNonInternalBitstreams(Context context, Item item) throws SQLException {
List<Bitstream> bitstreamList = new ArrayList<>();
// Go through the bundles and bitstreams picking out ones which aren't
// of internal formats
List<Bundle> bunds = item.getBundles();
for (Bundle bund : bunds) {
List<Bitstream> bitstreams = bund.getBitstreams();
for (Bitstream bitstream : bitstreams) {
if (!bitstream.getFormat(context).isInternal()) {
// Bitstream is not of an internal format
bitstreamList.add(bitstream);
}
}
}
return bitstreamList;
}
protected Item createItem(Context context) throws SQLException, AuthorizeException {
return createItem(context, null);
}
protected Item createItem(Context context, UUID uuid) throws SQLException, AuthorizeException {
Item item;
if (uuid != null) {
item = itemDAO.create(context, new Item(uuid));
} else {
item = itemDAO.create(context, new Item());
}
// set discoverable to true (default)
item.setDiscoverable(true);
// Call update to give the item a last modified date. OK this isn't
// amazingly efficient but creates don't happen that often.
context.turnOffAuthorisationSystem();
update(context, item);
context.restoreAuthSystemState();
context.addEvent(new Event(Event.CREATE, Constants.ITEM, item.getID(),
null, getIdentifiers(context, item)));
log.info(LogHelper.getHeader(context, "create_item", "item_id=" + item.getID()));
return item;
}
@Override
public void removeDSpaceLicense(Context context, Item item) throws SQLException, AuthorizeException, IOException {
// get all bundles with name "LICENSE" (these are the DSpace license
// bundles)
List<Bundle> bunds = getBundles(item, "LICENSE");
for (Bundle bund : bunds) {
// FIXME: probably serious troubles with Authorizations
// fix by telling system not to check authorization?
removeBundle(context, item, bund);
}
}
@Override
public void removeLicenses(Context context, Item item) throws SQLException, AuthorizeException, IOException {
// Find the License format
BitstreamFormat bf = bitstreamFormatService.findByShortDescription(context, "License");
int licensetype = bf.getID();
// search through bundles, looking for bitstream type license
List<Bundle> bunds = item.getBundles();
for (Bundle bund : bunds) {
boolean removethisbundle = false;
List<Bitstream> bits = bund.getBitstreams();
for (Bitstream bit : bits) {
BitstreamFormat bft = bit.getFormat(context);
if (bft.getID() == licensetype) {
removethisbundle = true;
}
}
// probably serious troubles with Authorizations
// fix by telling system not to check authorization?
if (removethisbundle) {
removeBundle(context, item, bund);
}
}
}
@Override
public void update(Context context, Item item) throws SQLException, AuthorizeException {
// Check authorisation
// only do write authorization if user is not an editor
if (!canEdit(context, item)) {
authorizeService.authorizeAction(context, item, Constants.WRITE);
}
log.info(LogHelper.getHeader(context, "update_item", "item_id="
+ item.getID()));
super.update(context, item);
// Set sequence IDs for bitstreams in Item. To guarantee uniqueness,
// sequence IDs are assigned in sequential order (starting with 1)
int sequence = 0;
List<Bundle> bunds = item.getBundles();
// find the highest current sequence number
for (Bundle bund : bunds) {
List<Bitstream> streams = bund.getBitstreams();
for (Bitstream bitstream : streams) {
if (bitstream.getSequenceID() > sequence) {
sequence = bitstream.getSequenceID();
}
}
}
// start sequencing bitstreams without sequence IDs
sequence++;
for (Bundle bund : bunds) {
List<Bitstream> streams = bund.getBitstreams();
for (Bitstream stream : streams) {
if (stream.getSequenceID() < 0) {
stream.setSequenceID(sequence);
sequence++;
bitstreamService.update(context, stream);
// modified = true;
}
}
}
if (item.isMetadataModified() || item.isModified()) {
// Set the last modified date
item.setLastModified(new Date());
itemDAO.save(context, item);
if (item.isMetadataModified()) {
context.addEvent(new Event(Event.MODIFY_METADATA, item.getType(), item.getID(), item.getDetails(),
getIdentifiers(context, item)));
}
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(),
null, getIdentifiers(context, item)));
item.clearModified();
item.clearDetails();
}
}
@Override
public void withdraw(Context context, Item item) throws SQLException, AuthorizeException {
// Check permission. User either has to have REMOVE on owning collection
// or be COLLECTION_EDITOR of owning collection
AuthorizeUtil.authorizeWithdrawItem(context, item);
String timestamp = DCDate.getCurrent().toString();
// Add suitable provenance - includes user, date, collections +
// bitstream checksums
EPerson e = context.getCurrentUser();
// Build some provenance data while we're at it.
StringBuilder prov = new StringBuilder();
prov.append("Item withdrawn by ").append(e.getFullName()).append(" (")
.append(e.getEmail()).append(") on ").append(timestamp).append("\n")
.append("Item was in collections:\n");
List<Collection> colls = item.getCollections();
for (Collection coll : colls) {
prov.append(coll.getName()).append(" (ID: ").append(coll.getID()).append(")\n");
}
// Set withdrawn flag. timestamp will be set; last_modified in update()
item.setWithdrawn(true);
// in_archive flag is now false
item.setArchived(false);
prov.append(installItemService.getBitstreamProvenanceMessage(context, item));
addMetadata(context, item, MetadataSchemaEnum.DC.getName(), "description", "provenance", "en", prov.toString());
// Update item in DB
update(context, item);
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(),
"WITHDRAW", getIdentifiers(context, item)));
// switch all READ authorization policies to WITHDRAWN_READ
authorizeService.switchPoliciesAction(context, item, Constants.READ, Constants.WITHDRAWN_READ);
for (Bundle bnd : item.getBundles()) {
authorizeService.switchPoliciesAction(context, bnd, Constants.READ, Constants.WITHDRAWN_READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.READ, Constants.WITHDRAWN_READ);
}
}
// Write log
log.info(LogHelper.getHeader(context, "withdraw_item", "user="
+ e.getEmail() + ",item_id=" + item.getID()));
}
@Override
public void reinstate(Context context, Item item) throws SQLException, AuthorizeException {
// check authorization
AuthorizeUtil.authorizeReinstateItem(context, item);
String timestamp = DCDate.getCurrent().toString();
// Check permission. User must have ADD on all collections.
// Build some provenance data while we're at it.
List<Collection> colls = item.getCollections();
// Add suitable provenance - includes user, date, collections +
// bitstream checksums
EPerson e = context.getCurrentUser();
StringBuilder prov = new StringBuilder();
prov.append("Item reinstated by ").append(e.getFullName()).append(" (")
.append(e.getEmail()).append(") on ").append(timestamp).append("\n")
.append("Item was in collections:\n");
for (Collection coll : colls) {
prov.append(coll.getName()).append(" (ID: ").append(coll.getID()).append(")\n");
}
// Clear withdrawn flag
item.setWithdrawn(false);
// in_archive flag is now true
item.setArchived(true);
// Add suitable provenance - includes user, date, collections +
// bitstream checksums
prov.append(installItemService.getBitstreamProvenanceMessage(context, item));
addMetadata(context, item, MetadataSchemaEnum.DC.getName(), "description", "provenance", "en", prov.toString());
// Update item in DB
update(context, item);
context.addEvent(new Event(Event.MODIFY, Constants.ITEM, item.getID(),
"REINSTATE", getIdentifiers(context, item)));
// restore all WITHDRAWN_READ authorization policies back to READ
for (Bundle bnd : item.getBundles()) {
authorizeService.switchPoliciesAction(context, bnd, Constants.WITHDRAWN_READ, Constants.READ);
for (Bitstream bs : bnd.getBitstreams()) {
authorizeService.switchPoliciesAction(context, bs, Constants.WITHDRAWN_READ, Constants.READ);
}
}
// check if the item was withdrawn before the fix DS-3097
if (authorizeService.getPoliciesActionFilter(context, item, Constants.WITHDRAWN_READ).size() != 0) {
authorizeService.switchPoliciesAction(context, item, Constants.WITHDRAWN_READ, Constants.READ);
} else {
// authorization policies
if (colls.size() > 0) {
// remove the item's policies and replace them with
// the defaults from the collection
adjustItemPolicies(context, item, item.getOwningCollection());
}
}
// Write log
log.info(LogHelper.getHeader(context, "reinstate_item", "user="
+ e.getEmail() + ",item_id=" + item.getID()));