-
Notifications
You must be signed in to change notification settings - Fork 29
/
DocumentRepository.java
1530 lines (1431 loc) · 67.7 KB
/
DocumentRepository.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
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
/*
* Copyright (C) 2000 - 2022 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.contribution.attachment.repository;
import org.apache.commons.io.FileUtils;
import org.silverpeas.core.ResourceReference;
import org.silverpeas.core.annotation.Repository;
import org.silverpeas.core.cache.model.SimpleCache;
import org.silverpeas.core.contribution.attachment.model.*;
import org.silverpeas.core.contribution.attachment.util.SimpleDocumentList;
import org.silverpeas.core.i18n.I18NHelper;
import org.silverpeas.core.io.media.image.ImageTool;
import org.silverpeas.core.io.media.image.option.OrientationOption;
import org.silverpeas.core.jcr.JCRSession;
import org.silverpeas.core.persistence.jcr.util.NodeIterable;
import org.silverpeas.core.persistence.jcr.util.PropertyIterable;
import org.silverpeas.core.util.DateUtil;
import org.silverpeas.core.util.Pair;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.file.FileRepositoryManager;
import org.silverpeas.core.util.file.FileUtil;
import org.silverpeas.core.util.logging.SilverLogger;
import javax.jcr.*;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.qom.*;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.*;
import static java.util.Optional.*;
import static javax.jcr.nodetype.NodeType.MIX_VERSIONABLE;
import static org.silverpeas.core.cache.service.CacheServiceProvider.getThreadCacheService;
import static org.silverpeas.core.contribution.attachment.util.AttachmentSettings.YOUNGEST_TO_OLDEST_MANUAL_REORDER_THRESHOLD;
import static org.silverpeas.core.contribution.attachment.util.AttachmentSettings.listFromYoungestToOldestAdd;
import static org.silverpeas.core.i18n.I18NHelper.DEFAULT_LANGUAGE;
import static org.silverpeas.core.jcr.util.SilverpeasProperty.*;
/**
* Repository of documents attached to some contributions in Silverpeas. This repository abstracts
* and wraps the use of the JCR by providing an API to work with {@link SimpleDocument} objects. It
* is a low-level technical class.
* @author ehugonnet
*/
@Repository
public class DocumentRepository {
private static final String SIMPLE_DOCUMENT_ALIAS = "SimpleDocuments";
final DocumentConverter converter;
public DocumentRepository() {
this(new DocumentConverter());
}
protected DocumentRepository(final DocumentConverter converter) {
this.converter = converter;
}
private void prepareComponentAttachments(String instanceId, String folder)
throws RepositoryException {
try (JCRSession session = JCRSession.openSystemSession()) {
prepareComponentAttachments(session, instanceId, folder);
session.save();
}
}
protected Node prepareComponentAttachments(Session session, String instanceId, String folder)
throws RepositoryException {
Node targetInstanceNode = converter.getFolder(session.getRootNode(), instanceId);
return converter.getFolder(targetInstanceNode, folder);
}
/**
* Creates the specified document attached to a contribution in Silverpeas. The contribution has
* to be referred by the {@link SimpleDocument#getForeignId()} identifier.
* @param session a session in the JCR
* @param document the document to create in the JCR
* @return the unique identifier of the document
* @throws RepositoryException if the creation in the JCR failed.
*/
public SimpleDocumentPK createDocument(Session session, SimpleDocument document)
throws RepositoryException {
if (0 >= document.getOrder()) {
getMinMaxOrderIndexes(session, document.getInstanceId(), document.getForeignId(),
document.getDocumentType()).ifPresent(i -> {
final Integer minOrderIndex = i.getFirst();
if (listFromYoungestToOldestAdd() &&
minOrderIndex > YOUNGEST_TO_OLDEST_MANUAL_REORDER_THRESHOLD) {
document.setOrder(minOrderIndex - 1);
} else {
document.setOrder(i.getSecond() + 1);
}
});
}
Node docsNode = prepareComponentAttachments(session, document.getInstanceId(),
document.getFolder());
Node documentNode = docsNode.addNode(document.computeNodeName(), SLV_SIMPLE_DOCUMENT);
document.setUpdatedBy(document.getCreatedBy());
document.setLastUpdateDate(document.getCreationDate());
converter.fillNode(document, documentNode);
if (document.isVersioned()) {
documentNode.addMixin(MIX_VERSIONABLE);
}
document.setId(documentNode.getIdentifier());
document.setOldSilverpeasId(documentNode.getProperty(SLV_PROPERTY_OLD_ID).getLong());
return document.getPk();
}
/**
* Moves the document to another attached contribution.
* @param session a session in the JCR
* @param document an exising document in the JCR to move from its actual contribution to another
* one.
* @param destination a reference to another contribution in Silverpeas. This contribution can be
* within another component instance.
* @return the new identifier of the moved document.
* @throws RepositoryException if an error occurs while moving the document in the JCR.
*/
public SimpleDocumentPK moveDocument(Session session, SimpleDocument document,
ResourceReference destination) throws RepositoryException {
SimpleDocument targetDoc = new SimpleDocument();
SimpleDocumentPK pk = new SimpleDocumentPK(null, destination.getComponentInstanceId());
pk.setOldSilverpeasId(document.getOldSilverpeasId());
targetDoc.setPK(pk);
targetDoc.setDocumentType(document.getDocumentType());
targetDoc.setNodeName(document.getNodeName());
prepareComponentAttachments(session, destination.getComponentInstanceId(),
document.getFolder());
session.save();
Node originDocumentNode = session.getNodeByIdentifier(document.getPk().getId());
if (!originDocumentNode.getPath().equals(targetDoc.getFullJcrPath())) {
session.getWorkspace().move(originDocumentNode.getPath(), targetDoc.getFullJcrPath());
}
VersionManager versionManager = session.getWorkspace().getVersionManager();
Node targetDocumentNode = session.getNode(targetDoc.getFullJcrPath());
boolean mustCheckInVersion = true;
if (converter.isVersionedMaster(targetDocumentNode)) {
if (!targetDocumentNode.isCheckedOut()) {
versionManager.checkout(targetDocumentNode.getPath());
} else {
mustCheckInVersion = false;
}
}
converter.addStringProperty(targetDocumentNode, SLV_PROPERTY_FOREIGN_KEY,
destination.getLocalId());
converter.addStringProperty(targetDocumentNode, SLV_PROPERTY_INSTANCEID,
destination.getComponentInstanceId());
if (converter.isVersionedMaster(targetDocumentNode) && targetDocumentNode.isCheckedOut()) {
session.save();
if (mustCheckInVersion) {
versionManager.checkin(targetDocumentNode.getPath());
}
}
pk.setId(targetDocumentNode.getIdentifier());
return pk;
}
/**
* Copies the document to another contribution. The operation duplicates the document and attaches
* it to the other contribution.
* @param session the session in the JCR.
* @param document the document to copy.
* @param destination the reference to the other contribution. The contribution can be in another
* component instance.
* @return the identifier of the copied document.
* @throws RepositoryException if an error occurs while copying the document in the JCR.
*/
public SimpleDocumentPK copyDocument(Session session, SimpleDocument document,
ResourceReference destination) throws RepositoryException {
prepareComponentAttachments(destination.getComponentInstanceId(), document.getFolder());
SimpleDocumentPK pk = new SimpleDocumentPK(null, destination.getComponentInstanceId());
SimpleDocument targetDoc;
if (document.isVersioned() && document.getDocumentType() == DocumentType.attachment) {
targetDoc = new HistorisedDocument();
} else {
targetDoc = new SimpleDocument();
}
targetDoc.setNodeName(null);
targetDoc.setPK(pk);
targetDoc.setDocumentType(document.getDocumentType());
targetDoc.setForeignId(destination.getLocalId());
targetDoc.computeNodeName();
Node originDocumentNode = session.getNodeByIdentifier(document.getPk().getId());
session.getWorkspace().copy(originDocumentNode.getPath(), targetDoc.getFullJcrPath());
Node copy = session.getNode(targetDoc.getFullJcrPath());
copy.setProperty(SLV_PROPERTY_OLD_ID, targetDoc.getOldSilverpeasId());
copy.setProperty(SLV_PROPERTY_FOREIGN_KEY, destination.getLocalId());
copy.setProperty(SLV_PROPERTY_INSTANCEID, destination.getComponentInstanceId());
// The reservation is not copied.
targetDoc = converter.fillDocument(copy, null);
targetDoc.release();
converter.fillNode(targetDoc, copy);
return targetDoc.getPk();
}
/**
* Copies the versioned document to another contribution in Silverpeas. The operation duplicates
* the document and all of its versions, and attaches them to the other contribution.
* @param session a session in the JCR
* @param document the document with all of its versions to copy
* @param destination the reference to the other contribution. It can be in another component
* instance.
* @return the identifier of the copied historized document.
* @throws RepositoryException if an error occurs while copying the document and all of its
* versions in the repository.
*/
public SimpleDocumentPK copyDocument(Session session, HistorisedDocument document,
ResourceReference destination) throws RepositoryException {
try {
prepareComponentAttachments(destination.getComponentInstanceId(), document.getFolder());
List<SimpleDocument> history = new ArrayList<>(document.getHistory());
Collections.reverse(history);
history.add(document);
SimpleDocumentPK pk = new SimpleDocumentPK(null, destination.getComponentInstanceId());
SimpleDocument targetDoc = new HistorisedDocument(history.remove(0));
FirstVersionManager.computeIfAbsent(new DocumentVersion(targetDoc));
targetDoc.setNodeName(null);
targetDoc.setPK(pk);
targetDoc.setDocumentType(document.getDocumentType());
targetDoc.setForeignId(destination.getLocalId());
targetDoc.setUpdatedBy(null);
targetDoc.computeNodeName();
pk = createDocument(session, targetDoc);
if (I18NHelper.isI18nContentEnabled()) {
addAttachmentInSupportedLanguages(session, document, targetDoc);
}
checkin(session, targetDoc, false);
VersionManager versionManager = session.getWorkspace().getVersionManager();
String previousVersion = targetDoc.getVersion();
for (SimpleDocument doc : history) {
SimpleDocument docToConsider = searchDocumentWithUpdatedContent(session, doc);
HistorisedDocument targetHistorizedDoc = new HistorisedDocument(docToConsider);
targetHistorizedDoc.setPK(pk);
targetHistorizedDoc.setForeignId(destination.getLocalId());
targetHistorizedDoc.setNodeName(targetDoc.getNodeName());
// The reservation is not copied.
targetHistorizedDoc.release();
Node masterDocumentNode = session.getNodeByIdentifier(pk.getId());
if (!previousVersion.equals(docToConsider.getVersion())) {
// In this case, a functional version is performed, so the common tools are used
checkout(session, targetDoc, docToConsider.getUpdatedBy());
converter.fillNode(targetHistorizedDoc, masterDocumentNode);
checkin(session, targetHistorizedDoc, false);
previousVersion = targetHistorizedDoc.getVersion();
} else {
// In this case, the version is a technical one (setOrder for example) and technical
// tools are used
versionManager.checkout(masterDocumentNode.getPath());
converter.fillNode(targetHistorizedDoc, masterDocumentNode);
session.save();
versionManager.checkin(masterDocumentNode.getPath());
}
}
return pk;
} finally {
FirstVersionManager.clear();
}
}
private SimpleDocument searchDocumentWithUpdatedContent(final Session session,
final SimpleDocument doc) throws RepositoryException {
SimpleDocument updated = doc;
if (I18NHelper.isI18nContentEnabled()) {
// One language content is aimed by a version. So the first step here is to search the
// language content updated.
Set<String> checkedLanguages = new HashSet<>();
checkedLanguages.add(doc.getLanguage());
for (String language : I18NHelper.getAllSupportedLanguages()) {
if (!checkedLanguages.contains(language)) {
SimpleDocument temp = findDocumentById(session, doc.getPk(), language);
if (temp != null && !checkedLanguages.contains(temp.getLanguage()) &&
temp.getLastUpdateDate().after(doc.getLastUpdateDate())) {
updated = temp;
}
checkedLanguages.add(language);
}
}
}
return updated;
}
private void addAttachmentInSupportedLanguages(final Session session,
final HistorisedDocument document, final SimpleDocument targetDoc)
throws RepositoryException {
// The first version can have several language contents.
Set<String> checkedLanguages = new HashSet<>();
checkedLanguages.add(targetDoc.getLanguage());
for (String language : I18NHelper.getAllSupportedLanguages()) {
if (!checkedLanguages.contains(language)) {
HistorisedDocument temp = (HistorisedDocument) findDocumentById(session, document.getPk(),
language);
List<SimpleDocumentVersion> versions = temp.getHistory();
if (!versions.isEmpty()) {
SimpleDocumentVersion firstVersion = versions.get(versions.size() - 1);
if (!checkedLanguages.contains(firstVersion.getLanguage())) {
addContent(session, targetDoc.getPk(), firstVersion.getAttachment());
}
}
checkedLanguages.add(language);
}
}
}
/**
* Updates the documents in the JCR. The specified document contains the new data with which the
* document in the JCR has to be updated. The document in the JCR is referred by the unique
* identifier of the specified document.
* @param session a session in the JCR
* @param document the document to update
* @param updateLastModifiedData a flag indicating if the modification date and the last modifier
* has to be explicitly done.
* @throws RepositoryException if the update in the JCR fails.
*/
public void updateDocument(Session session, SimpleDocument document,
final boolean updateLastModifiedData) throws RepositoryException {
Node documentNode = session.getNodeByIdentifier(document.getPk().getId());
if (updateLastModifiedData) {
if (StringUtil.isDefined(document.getEditedBy())) {
document.setUpdatedBy(document.getEditedBy());
}
document.setLastUpdateDate(new Date());
}
converter.fillNode(document, documentNode);
}
/**
* Saves the optional slv:forbiddenDownloadForRoles document property (a mixin). This saving works
* with versionable documents without changing the major and minor version. This property is
* transverse between all versions.
* @param session a session in the JCR
* @param document the document for which download has to be forbidden for some user roles.
* @throws RepositoryException if an error occurs while saving the mixin.
*/
public void saveForbiddenDownloadForRoles(Session session, SimpleDocument document)
throws RepositoryException {
acceptOnMasterVersionWithoutChangingFunctionalVersion(session, document,
d -> converter.setForbiddenDownloadForRolesOptionalNodeProperty(document, d));
}
/**
* Saves the optional slv:displayableAsContent simple document property (a mixin). This saving
* works with versionable documents without changing the major and minor version. This property is
* transverse between all versions.
* @param session a session in the JCR
* @param document the document for which the content can be automatically displayed.
* @throws RepositoryException if an error occurs while saving the mixin.
*/
public void saveDisplayableAsContent(Session session, SimpleDocument document)
throws RepositoryException {
acceptOnMasterVersionWithoutChangingFunctionalVersion(session, document,
d -> converter.setDisplayableAsContentOptionalNodeProperty(document, d));
}
/**
* Saves the optional slv:editableSimultaneously simple document property (a mixin). This saving
* works with versionable documents without changing the major and minor version. This property is
* transverse between all versions.
* @param session a session in the JCR
* @param document the document for which the simultaneous edition can be done.
* @throws RepositoryException if an error occurs while saving the mixin.
*/
public void saveEditableSimultaneously(Session session, SimpleDocument document)
throws RepositoryException {
acceptOnMasterVersionWithoutChangingFunctionalVersion(session, document,
d -> converter.setEditableSimultaneouslyOptionalNodeProperty(document, d));
}
/**
* Adds the document's clone id to the document even if it is locked. This saving works with
* versionable documents without changing the major and minor version. This property is transverse
* between all versions.
* @param session the JCR session.
* @param original the original document to be cloned.
* @param clone the cone of the original document.
* @throws RepositoryException if an error occurs while setting the clone identifier to the
* document in the JCR.
*/
public void setClone(Session session, SimpleDocument original, SimpleDocument clone)
throws RepositoryException {
acceptWithoutChangingFunctionalVersion(session, clone,
d -> d.setProperty(SLV_PROPERTY_CLONE, original.getId()));
}
/**
* Update the document order. This is a unique operation since the order property is not
* versionable. This saving works with versionable documents without changing the major and minor
* version. This property is transverse between all versions.
*/
public void setOrder(Session session, SimpleDocument document) throws RepositoryException {
acceptWithoutChangingFunctionalVersion(session, document,
d -> d.setProperty(SLV_PROPERTY_ORDER, document.getOrder()));
}
/**
* Centralization of a simple update. This saving works with versionable documents without
* changing the major and minor version. This property is transverse between all versions.
* @param session the current session.
* @param document the aimed document which will be updated on master version.
* @param consumer the consumer of a checked documentNode.
* @throws RepositoryException on JCR error.
*/
private void acceptOnMasterVersionWithoutChangingFunctionalVersion(Session session,
SimpleDocument document, RepositoryConsumer<Node> consumer) throws RepositoryException {
acceptWithoutChangingFunctionalVersion(session, document.getVersionMaster(), consumer);
}
/**
* Centralization of the mechanism to update a property
* @param session the current session.
* @param document the aimed document without taking care of the version.
* @param consumer the consumer of a checked documentNode.
* @throws RepositoryException on JCR error.
*/
private void acceptWithoutChangingFunctionalVersion(Session session, SimpleDocument document,
RepositoryConsumer<Node> consumer) throws RepositoryException {
Node documentNode = session.getNodeByIdentifier(document.getPk().getId());
boolean checkedIn = !documentNode.isCheckedOut();
if (checkedIn) {
session.getWorkspace().getVersionManager().checkout(documentNode.getPath());
}
consumer.accept(documentNode);
if (checkedIn) {
session.save();
session.getWorkspace().getVersionManager().checkin(documentNode.getPath());
}
}
/**
* Deletes the document in the JCR referred by the specified identifier.
* @param session a session in the JCR.
* @param documentPk the unique identifier of the document to delete.
* @throws RepositoryException if the deletion of the document in the JCR fails.
*/
public void deleteDocument(Session session, SimpleDocumentPK documentPk)
throws RepositoryException {
try {
final Node documentNode = session.getNodeByIdentifier(documentPk.getId());
final String documentNodeName = documentNode.getName();
deleteDocumentNode(documentNode);
deleteContent(documentPk.getInstanceId(), documentNodeName);
} catch (ItemNotFoundException e) {
SilverLogger.getLogger(this).silent(e);
}
}
/**
* Change the management of versions of the document if it is locked. If the document is currently
* with version management, then the whole versions history is removed and the document becomes a
* simple document with no more version history. If the document isn't versioned then a new public
* version is created and the document becomes a document with a version history management.
* @param session a session in the JCR
* @param documentPk the id of the document.
* @param comment the comment of the user about the first version in the case the versioning is
* enabled.
* @throws RepositoryException if the version management switch fails
* @throws IOException if an error occurs while accessing the filesystem to create or remove
* versions of the related document
*/
public SimpleDocumentPK changeVersionState(Session session, SimpleDocumentPK documentPk,
String comment) throws RepositoryException, IOException {
try {
Node documentNode = session.getNodeByIdentifier(documentPk.getId());
boolean versionedNode =
documentNode.getParent() instanceof Version || converter.isVersionedMaster(documentNode);
Node parent = documentNode.getParent();
if (parent instanceof Version) {
Version selectedVersion = (Version) parent;
VersionManager versionManager = documentNode.getSession()
.getWorkspace()
.getVersionManager();
versionManager.restore(selectedVersion, true);
documentNode = session.getNodeByIdentifier(
selectedVersion.getContainingHistory().getVersionableIdentifier());
}
if (!documentNode.isCheckedOut()) {
checkoutNode(documentNode, null);
}
if (StringUtil.isDefined(comment)) {
documentNode.setProperty(SLV_PROPERTY_COMMENT, comment);
}
final SimpleDocument origin = converter.fillDocument(documentNode, DEFAULT_LANGUAGE);
if (versionedNode) {
VersionHistory history = session.getWorkspace()
.getVersionManager()
.getVersionHistory(documentNode.getPath());
documentNode.removeMixin(MIX_VERSIONABLE);
documentNode.setProperty(SLV_PROPERTY_VERSIONED, false);
documentNode.setProperty(SLV_PROPERTY_MAJOR, 0);
documentNode.setProperty(SLV_PROPERTY_MINOR, 0);
session.save();
removeHistory(history);
final SimpleDocument target = converter.fillDocument(documentNode, DEFAULT_LANGUAGE);
moveMultilangContent(origin, target);
File currentDocumentDir = new File(
target.getDirectoryPath(DEFAULT_LANGUAGE)).getParentFile();
final Optional<File[]> files = ofNullable(currentDocumentDir.getParentFile().listFiles());
final File[] safeContents = files.orElseGet(() -> {
SilverLogger.getLogger(this)
.warn(
"During version state removing, attempting to delete {0} which does not exist " +
"whereas JCR is having a reference on it",
currentDocumentDir.getParentFile().toString());
return new File[0];
});
for (File versionDirectory : safeContents) {
if (!versionDirectory.equals(currentDocumentDir)) {
FileUtils.deleteDirectory(versionDirectory);
}
}
} else {
documentNode.setProperty(SLV_PROPERTY_VERSIONED, true);
documentNode.setProperty(SLV_PROPERTY_MAJOR, 1);
documentNode.setProperty(SLV_PROPERTY_MINOR, 0);
documentNode.addMixin(MIX_VERSIONABLE);
final SimpleDocument target = converter.fillDocument(documentNode, DEFAULT_LANGUAGE);
VersionManager versionManager = documentNode.getSession()
.getWorkspace()
.getVersionManager();
session.save();
versionManager.checkin(documentNode.getPath());
moveMultilangContent(origin, target);
}
return new SimpleDocumentPK(documentNode.getIdentifier(), documentPk);
} catch (ItemNotFoundException e) {
return documentPk;
}
}
private void deleteDocumentNode(Node documentNode) throws RepositoryException {
if (null != documentNode) {
Session session = documentNode.getSession();
VersionHistory history = converter.isVersionedMaster(documentNode) ?
documentNode.getSession()
.getWorkspace()
.getVersionManager()
.getVersionHistory(documentNode.getPath()) :
null;
documentNode.remove();
session.save();
if (history != null) {
removeHistory(history);
}
}
}
/**
* Finds the document referred by the specified identifier and written in the given language. The
* document can be proposed in different languages, in this case the language parameter indicates
* the version of the document to find.
* @param session the session in the JCR.
* @param documentPk the unique identifier of the document;
* @param lang the language in which the document to find is written.
* @return the document or null if no such document exists.
* @throws RepositoryException if an error occurs while looking for the document.
*/
public SimpleDocument findDocumentById(Session session, SimpleDocumentPK documentPk, String lang)
throws RepositoryException {
SimpleDocument document = null;
try {
Node documentNode = session.getNodeByIdentifier(documentPk.getId());
document = converter.convertNode(documentNode, lang);
} catch (ItemNotFoundException e) {
SilverLogger.getLogger(this).silent(e);
}
return document;
}
/**
* Finds the document referred by its old unique identifier and in the given language. In old days
* of the management of the documents in Silverpeas, the documents were stored in a database, and
* they were uniquely identified by an identifier crafted by this database. After their transition
* to the JCR, a new schema of unique identifier has been applied to them and a need to maintain a
* map between old identifier and new one for older documents was required.
* @param session the session in the JCR.
* @param instanceId the unique instance of the component in which the document is managed.
* @param oldSilverpeasId the old unique identifier of the document.
* @param versioned a boolean indicating if the document is or not versioned.
* @param lang the language in which the document is written.
* @return the document or null if no such document exists.
* @throws RepositoryException if an error occurs while looking for the document.
*/
public SimpleDocument findDocumentByOldSilverpeasId(Session session, String instanceId,
long oldSilverpeasId, boolean versioned, String lang) throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
DescendantNode descendantNodeConstraint = factory.descendantNode(SIMPLE_DOCUMENT_ALIAS,
session.getRootNode().getPath() + instanceId);
Comparison oldSilverpeasIdComparison = getComparison(factory, SLV_PROPERTY_OLD_ID,
QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO,
session.getValueFactory().createValue(oldSilverpeasId));
Comparison versionedComparison = getComparison(factory, SLV_PROPERTY_VERSIONED,
QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO,
session.getValueFactory().createValue(versioned));
QueryObjectModel query = factory.createQuery(source, factory.and(descendantNodeConstraint,
factory.and(oldSilverpeasIdComparison, versionedComparison)), null, null);
QueryResult result = query.execute();
NodeIterator iter = result.getNodes();
if (iter.hasNext()) {
return converter.convertNode(iter.nextNode(), lang);
}
return null;
}
/**
* The last document in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @param documentType the type of document.
* @return the last document in an instance with the specified foreignId.
* @throws RepositoryException if an error occurs while accessing the JCR
*/
@SuppressWarnings("SameParameterValue")
SimpleDocument findLast(Session session, String instanceId, String foreignId,
final DocumentType documentType) throws RepositoryException {
final NodeIterator iter = selectDocumentsByForeignIdAndType(session, instanceId, foreignId,
documentType);
while (iter.hasNext()) {
final Node node = iter.nextNode();
if (!iter.hasNext()) {
return converter.convertNode(node, DEFAULT_LANGUAGE);
}
}
return null;
}
/**
* Get the minimum and maximum order indexes of attachments linked to a resource for a given
* type.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @param documentType the type of document.
* @return optional min and max order indexes of documents for the specified foreignId and type.
* Optional is empty when it exists no document for the foreign key and the type.
* @throws RepositoryException in case of JCR repository problem.
*/
Optional<Pair<Integer, Integer>> getMinMaxOrderIndexes(Session session, String instanceId,
String foreignId, final DocumentType documentType) throws RepositoryException {
final NodeIterator iter = selectDocumentsByForeignIdAndType(session, instanceId, foreignId,
documentType);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
while (iter.hasNext()) {
final Node node = iter.nextNode();
if (node.hasProperty(SLV_PROPERTY_ORDER)) {
final int currentOrder = (int) node.getProperty(SLV_PROPERTY_ORDER).getLong();
min = Math.min(min, currentOrder);
max = Math.max(max, currentOrder);
}
}
return min == Integer.MAX_VALUE ? empty() : of(Pair.of(min, max));
}
/**
* Search all the documents of type attachment in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public SimpleDocumentList<SimpleDocument> listDocumentsByForeignId(Session session,
String instanceId, String foreignId, String language) throws RepositoryException {
NodeIterator iter = selectDocumentsByForeignIdAndType(session, instanceId, foreignId,
DocumentType.attachment);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents of any type in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public SimpleDocumentList<SimpleDocument> listAllDocumentsByForeignId(Session session,
String instanceId, String foreignId, String language) throws RepositoryException {
NodeIterator iter = selectDocumentsByForeignId(session, instanceId, foreignId);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @param type the type of required documents.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public SimpleDocumentList<SimpleDocument> listDocumentsByForeignIdAndType(Session session,
String instanceId, String foreignId, DocumentType type, String language)
throws RepositoryException {
NodeIterator iter = selectDocumentsByForeignIdAndType(session, instanceId, foreignId, type);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance with the specified type.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param type the type of required documents.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public List<SimpleDocument> listDocumentsByComponentIdAndType(Session session, String instanceId,
DocumentType type, String language) throws RepositoryException {
NodeIterator iter = selectDocumentsByComponentIdAndType(session, instanceId, type);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents related to the component instance identified by the specified
* identifier.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public List<SimpleDocument> listAllDocumentsByComponentId(Session session, String instanceId,
String language) throws RepositoryException {
NodeIterator iter = selectAllDocumentsByComponentId(session, instanceId);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance with the specified owner.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param owner the id of the user owning the document.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
public List<SimpleDocument> listComponentDocumentsByOwner(Session session, String instanceId,
String owner, String language) throws RepositoryException {
NodeIterator iter = selectDocumentsByOwnerIdAndComponentId(session, instanceId, owner);
return converter.convertNodeIterator(iter, language);
}
public List<SimpleDocument> listDocumentsLockedByUser(Session session, String usedId,
String language) throws RepositoryException {
NodeIterator iter = selectAllDocumentsByOwnerId(session, usedId);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents of the specified type in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
NodeIterator selectDocumentsByForeignIdAndType(Session session, String instanceId,
String foreignId, DocumentType type) throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
ChildNode childNodeConstraint = factory.childNode(SIMPLE_DOCUMENT_ALIAS,
session.getRootNode().getPath() + instanceId + '/' + type.getFolderName());
return getNodeIteratorByProperty(factory, source, childNodeConstraint, SLV_PROPERTY_FOREIGN_KEY,
session.getValueFactory().createValue(foreignId));
}
private static Comparison getComparison(final QueryObjectModelFactory factory,
final String slvProperty, final String jcrOperatorEqualTo, final Value session)
throws RepositoryException {
return factory.comparison(factory.propertyValue(SIMPLE_DOCUMENT_ALIAS, slvProperty),
jcrOperatorEqualTo, factory.literal(session));
}
/**
* Search all the documents of any type in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param foreignId the id of the container owning the documents.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs
*/
NodeIterator selectDocumentsByForeignId(Session session, String instanceId, String foreignId)
throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
DescendantNode descendantNodeConstraint = factory.descendantNode(SIMPLE_DOCUMENT_ALIAS,
session.getRootNode().getPath() + instanceId + '/');
return getNodeIteratorByProperty(factory, source, descendantNodeConstraint,
SLV_PROPERTY_FOREIGN_KEY, session.getValueFactory().createValue(foreignId));
}
/**
* Search all the documents of the specified type in an instance with the specified foreignId.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @param type the type of document.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
NodeIterator selectDocumentsByComponentIdAndType(Session session, String instanceId,
DocumentType type) throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
ChildNode childNodeConstraint = factory.childNode(SIMPLE_DOCUMENT_ALIAS,
session.getRootNode().getPath() + instanceId + '/' + type.getFolderName());
Ordering order = factory.ascending(
factory.propertyValue(SIMPLE_DOCUMENT_ALIAS, SLV_PROPERTY_ORDER));
QueryObjectModel query = factory.createQuery(source, childNodeConstraint, new Ordering[]{order},
null);
QueryResult result = query.execute();
return result.getNodes();
}
/**
* Search all the documents related to the component instance identified by the specified
* identifier.
* @param session the current JCR session.
* @param instanceId the component id containing the documents.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
NodeIterator selectAllDocumentsByComponentId(Session session, String instanceId)
throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
DescendantNode childNodeConstraint = factory.descendantNode(SIMPLE_DOCUMENT_ALIAS,
session.getRootNode().getPath() + instanceId);
Ordering order = factory.ascending(
factory.propertyValue(SIMPLE_DOCUMENT_ALIAS, SLV_PROPERTY_ORDER));
QueryObjectModel query = factory.createQuery(source, childNodeConstraint, new Ordering[]{order},
null);
QueryResult result = query.execute();
return result.getNodes();
}
/**
* Search all the documents in an instance which are expiring at the specified date.
* @param session the current JCR session.
* @param expiryDate the date when the document reservation should expire.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
public List<SimpleDocument> listExpiringDocuments(Session session, Date expiryDate,
String language) throws RepositoryException {
NodeIterator iter = selectExpiringDocuments(session, DateUtil.getBeginOfDay(expiryDate));
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance which are locked at the alert date.
* @param session the current JCR session.
* @param alertDate the date when the document reservation should send an alert.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
public List<SimpleDocument> listDocumentsRequiringWarning(Session session, Date alertDate,
String language) throws RepositoryException {
NodeIterator iter = selectWarningDocuments(session, DateUtil.getBeginOfDay(alertDate));
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance expiring at the specified date.
* @param session the current JCR session.
* @param expiryDate the date when the document reservation should expire.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
NodeIterator selectExpiringDocuments(Session session, Date expiryDate)
throws RepositoryException {
return getNodeIteratorByDateProperty(session, SLV_PROPERTY_EXPIRY_DATE, expiryDate);
}
private NodeIterator getNodeIteratorByDateProperty(final Session session,
final String slvPropertyDate, final Date date) throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Calendar calendarDate = Calendar.getInstance();
calendarDate.setTime(DateUtil.getBeginOfDay(date));
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
return getNodeIteratorByProperty(factory, source, slvPropertyDate,
session.getValueFactory().createValue(calendarDate));
}
private NodeIterator getNodeIteratorByProperty(final QueryObjectModelFactory factory,
final Selector source, final Constraint anotherConstraint, final String slvProperty,
final Value value) throws RepositoryException {
Comparison comparison = getComparison(factory, slvProperty,
QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO, value);
Ordering order = factory.ascending(
factory.propertyValue(SIMPLE_DOCUMENT_ALIAS, SLV_PROPERTY_ORDER));
Constraint constraint =
anotherConstraint == null ? comparison : factory.and(anotherConstraint, comparison);
QueryObjectModel query = factory.createQuery(source, constraint, new Ordering[]{order}, null);
QueryResult result = query.execute();
return result.getNodes();
}
private NodeIterator getNodeIteratorByProperty(final QueryObjectModelFactory factory,
final Selector source, final String slvProperty, final Value value)
throws RepositoryException {
return getNodeIteratorByProperty(factory, source, null, slvProperty, value);
}
/**
* Search all the documents in an instance requiring to be unlocked at the specified date.
* @param session the current JCR session.
* @param expiryDate the date when the document reservation should expire.
* @param language the language in which the documents are required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
public List<SimpleDocument> listDocumentsToUnlock(Session session, Date expiryDate,
String language) throws RepositoryException {
NodeIterator iter = selectDocumentsRequiringUnlocking(session, expiryDate);
return converter.convertNodeIterator(iter, language);
}
/**
* Search all the documents in an instance requiring to be unlocked at the specified date.
* @param session the current JCR session.
* @param expiryDate the date when the document reservation should expire.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR
*/
NodeIterator selectDocumentsRequiringUnlocking(Session session, Date expiryDate)
throws RepositoryException {
QueryManager manager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory factory = manager.getQOMFactory();
Calendar expiry = Calendar.getInstance();
expiry.setTime(DateUtil.getBeginOfDay(expiryDate));
Selector source = factory.selector(SLV_SIMPLE_DOCUMENT, SIMPLE_DOCUMENT_ALIAS);
Comparison expiryDateComparison = getComparison(factory, SLV_PROPERTY_EXPIRY_DATE,
QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN,
session.getValueFactory().createValue(expiry));
Ordering order = factory.ascending(
factory.propertyValue(SIMPLE_DOCUMENT_ALIAS, SLV_PROPERTY_ORDER));
QueryObjectModel query = factory.createQuery(source, expiryDateComparison, new Ordering[]{order},
null);
QueryResult result = query.execute();
return result.getNodes();
}
/**
* Search all the documents in an instance in a warning state at the specified date.
* @param session the current JCR session.
* @param alertDate the date when a warning is required.
* @return an ordered list of the documents.
* @throws RepositoryException if an error occurs with the JCR