/
JcrVersionManager.java
1943 lines (1625 loc) · 91 KB
/
JcrVersionManager.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
/*
* ModeShape (http://www.modeshape.org)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* ModeShape is free software. Unless otherwise indicated, all code in ModeShape
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* ModeShape 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.modeshape.jcr;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.MergeException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.version.OnParentVersionAction;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import org.modeshape.common.annotation.NotThreadSafe;
import org.modeshape.common.i18n.I18n;
import org.modeshape.common.text.Jsr283Encoder;
import org.modeshape.common.text.TextEncoder;
import org.modeshape.common.util.CheckArg;
import org.modeshape.common.util.Logger;
import org.modeshape.graph.ExecutionContext;
import org.modeshape.graph.Graph;
import org.modeshape.graph.Graph.Batch;
import org.modeshape.graph.Location;
import org.modeshape.graph.property.DateTime;
import org.modeshape.graph.property.DateTimeFactory;
import org.modeshape.graph.property.Name;
import org.modeshape.graph.property.NameFactory;
import org.modeshape.graph.property.Path;
import org.modeshape.graph.property.Path.Segment;
import org.modeshape.graph.property.PathFactory;
import org.modeshape.graph.property.PropertyFactory;
import org.modeshape.graph.property.Reference;
import org.modeshape.graph.property.ValueFactories;
import org.modeshape.graph.property.ValueFactory;
import org.modeshape.graph.session.GraphSession.Node;
import org.modeshape.graph.session.GraphSession.PropertyInfo;
import org.modeshape.jcr.JcrRepository.Option;
import org.modeshape.jcr.JcrRepository.VersionHistoryOption;
import org.modeshape.jcr.SessionCache.JcrNodePayload;
import org.modeshape.jcr.SessionCache.JcrPropertyPayload;
import org.modeshape.jcr.SessionCache.NodeEditor;
/**
* Local implementation of version management code, comparable to an implementation of the JSR-283 {@code VersionManager}
* interface. Valid instances of this class can be obtained by calling {@link JcrWorkspace#versionManager()}.
*/
final class JcrVersionManager implements VersionManager {
private static final Logger LOGGER = Logger.getLogger(JcrVersionManager.class);
private static final TextEncoder NODE_ENCODER = new Jsr283Encoder();
static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/**
* Property names from nt:frozenNode that should never be copied directly to a node when the frozen node is restored.
*/
static final Set<Name> IGNORED_PROP_NAMES_FOR_RESTORE = Collections.unmodifiableSet(new HashSet<Name>(
Arrays.asList(new Name[] {
JcrLexicon.FROZEN_PRIMARY_TYPE,
JcrLexicon.FROZEN_MIXIN_TYPES,
JcrLexicon.FROZEN_UUID,
JcrLexicon.PRIMARY_TYPE,
JcrLexicon.MIXIN_TYPES,
JcrLexicon.UUID})));
private final JcrSession session;
protected final Path versionStoragePath;
private final PathAlgorithm hiearchicalPathAlgorithm;
private final PathAlgorithm flatPathAlgorithm;
private final PathAlgorithm versionHistoryPathAlgorithm;
public JcrVersionManager( JcrSession session ) {
super();
this.session = session;
versionStoragePath = absolutePath(JcrLexicon.SYSTEM, JcrLexicon.VERSION_STORAGE);
String storageFormat = session.repository().getOptions().get(Option.VERSION_HISTORY_STRUCTURE);
if (storageFormat != null) storageFormat = storageFormat.trim().toLowerCase();
ExecutionContext context = session.getExecutionContext();
boolean isHier = VersionHistoryOption.HIERARCHICAL.equals(storageFormat);
hiearchicalPathAlgorithm = new HiearchicalPathAlgorithm(versionStoragePath, context);
flatPathAlgorithm = new FlatPathAlgorithm(versionStoragePath, context);
versionHistoryPathAlgorithm = isHier ? hiearchicalPathAlgorithm : flatPathAlgorithm;
}
ExecutionContext context() {
return session.getExecutionContext();
}
private ValueFactories factories() {
return context().getValueFactories();
}
UUID uuid( Object ob ) {
return factories().getUuidFactory().create(ob);
}
Name name( String s ) {
return factories().getNameFactory().create(s);
}
Name name( Object ob ) {
return factories().getNameFactory().create(ob);
}
final Path path( Path root,
Name child ) {
return factories().getPathFactory().create(root, child);
}
Path path( Path root,
Path.Segment childSegment ) {
return factories().getPathFactory().create(root, childSegment);
}
private Path absolutePath( Name... absolutePathSegments ) {
return factories().getPathFactory().createAbsolutePath(absolutePathSegments);
}
DateTime dateTime( Calendar cal ) {
return factories().getDateFactory().create(cal);
}
private PropertyFactory propertyFactory() {
return context().getPropertyFactory();
}
SessionCache cache() {
return session.cache();
}
private JcrRepository repository() {
return session.repository();
}
JcrSession session() {
return session;
}
JcrWorkspace workspace() {
return session.workspace();
}
/**
* Return the path to the nt:versionHistory node for the node with the supplied UUID.
* <p>
* This method uses one of two algorithms.
* <ul>
* <li>The flat algorithm just returns the path <code>/jcr:system/jcr:versionStorage/<UUID></code>. For example, given the
* UUID <code>fae2b929-c5ef-4ce5-9fa1-514779ca0ae3</code>, the returned path would be
* <code>/jcr:system/jcr:versionStorage/fae2b929-c5ef-4ce5-9fa1-514779ca0ae3</code>.</li>
* <li>The hierarchical algorithm breaks the UUID string into 5 parts (where the first 4 parts each consist of two characters
* in the string representation) and returns the path
* <code>/jcr:system/jcr:versionStorage/<part1>/<part2>/<part3>/<part4>/<part5></code>, where
* <code>part1</code> consists of the 1st and 2nd characters of the UUID string, <code>part2</code> consists of the 3rd and
* 4th characters of the UUID string, <code>part3</code> consists of the 5th and 6th characters of the UUID string,
* <code>part4</code> consists of the 7th and 8th characters of the UUID string, and <code>part5</code> consists of the 10th
* and remaining characters. (Note the 9th character is a '-' and is not used.) For example, given the UUID
* <code>fae2b929-c5ef-4ce5-9fa1-514779ca0ae3</code>, the returned path would be
* <code>/jcr:system/jcr:versionStorage/fa/e2/b9/29/c5ef-4ce5-9fa1-514779ca0ae3</code>.</li>
* </ul>
* </p>
*
* @param uuid the value of the {@code jcr:uuid} property (as a UUID) for the node for which the version history should be
* returned
* @return the path to the version history node that corresponds to the node with the given UUID. This does not guarantee that
* a node exists at the returned path. In fact, if the node with the given UUID is not versionable (i.e.,
* {@code node.getUUID().equals(uuid.toString()) && !node.isNodeType("mix:versionable")}), there will most likely not
* be a node at the path returned by this method.
*/
Path versionHistoryPathFor( UUID uuid ) {
return versionHistoryPathAlgorithm.versionHistoryPathFor(uuid);
}
Path[] versionHistoryPathsTo( Path historyPath ) {
int numIntermediatePaths = historyPath.size() - versionStoragePath.size() - 1;
if (numIntermediatePaths <= 0) return null;
Path[] paths = new Path[numIntermediatePaths];
Path path = historyPath.getParent();
for (int i = numIntermediatePaths - 1; i >= 0; --i) {
paths[i] = path;
path = path.getParent();
}
return paths;
}
/**
* Returns the version history (if one exists) for the given node.
*
* @param node the node for which the history should be returned
* @return the version history for the node
* @throws ItemNotFoundException if there is no version history for the given UUID
* @throws RepositoryException if any other error occurs accessing the repository
* @see AbstractJcrNode#getVersionHistory()
*/
JcrVersionHistoryNode getVersionHistory( AbstractJcrNode node ) throws RepositoryException {
session.checkLive();
checkVersionable(node);
Location historyLocation = Location.create(versionHistoryPathFor(node.uuid()));
try {
return (JcrVersionHistoryNode)cache().findJcrNode(historyLocation);
} catch (ItemNotFoundException infe) {
if (versionHistoryPathAlgorithm != flatPathAlgorithm) {
// Next try the flat structure, in case the version history was already created and the structure was changed ...
try {
Location flatHistoryLocation = Location.create(versionHistoryPathFor(node.uuid()));
return (JcrVersionHistoryNode)cache().findJcrNode(flatHistoryLocation);
} catch (ItemNotFoundException nested) {
// Ignore and continue ...
}
}
initializeVersionHistoryFor(node);
// This will throw an ItemNotFoundException if the history node still doesn't exist
JcrVersionHistoryNode historyNode = (JcrVersionHistoryNode)cache().findJcrNode(historyLocation);
LOGGER.warn(JcrI18n.repairedVersionStorage, historyLocation);
return historyNode;
}
}
/**
* Returns the node definition for the given node
*
* @param node the node for which the definition should be returned
* @return the active node definition for the given node
* @throws RepositoryException if an error occurs accessing the repository
* @see JcrNodeTypeManager#getNodeDefinition(NodeDefinitionId)
*/
JcrNodeDefinition nodeDefinitionFor( Node<JcrNodePayload, JcrPropertyPayload> node ) throws RepositoryException {
NodeDefinitionId nodeDefnId = node.getPayload().getDefinitionId();
return session().nodeTypeManager().getNodeDefinition(nodeDefnId);
}
/**
* Checks in the given node, creating (and returning) a new {@link Version}.
*
* @param node the node to be checked in
* @return the {@link Version} object created as a result of this checkin
* @throws RepositoryException if an error occurs during the checkin. See {@link javax.jcr.Node#checkin()} for a full
* description of the possible error conditions.
*/
JcrVersionNode checkin( AbstractJcrNode node ) throws RepositoryException {
session.checkLive();
checkVersionable(node);
if (node.isNew() || node.isModified()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowed.text());
}
// Check this separately since it throws a different type of exception
if (node.isLocked() && !node.holdsLock()) {
throw new LockException(JcrI18n.lockTokenNotHeld.text(node.getPath()));
}
if (node.getProperty(JcrLexicon.MERGE_FAILED) != null) {
throw new VersionException(JcrI18n.pendingMergeConflicts.text(node.getPath()));
}
Property isCheckedOut = node.getProperty(JcrLexicon.IS_CHECKED_OUT);
if (!isCheckedOut.getBoolean()) {
return node.getBaseVersion();
}
Name primaryTypeName = node.getPrimaryTypeName();
List<Name> mixinTypeNames = node.getMixinTypeNames();
UUID jcrUuid = node.uuid();
UUID versionUuid = UUID.randomUUID();
AbstractJcrNode historyNode = getVersionHistory(node);
Path historyPath = historyNode.path();
Graph systemGraph = repository().createSystemGraph(context());
Graph.Batch systemBatch = systemGraph.batch();
DateTime now = context().getValueFactories().getDateFactory().create();
Path versionPath = path(historyPath, name(NODE_ENCODER.encode(now.getString())));
AbstractJcrProperty predecessorsProp = node.getProperty(JcrLexicon.PREDECESSORS);
systemBatch.create(versionPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.VERSION)
.and(JcrLexicon.CREATED, now)
.and(JcrLexicon.UUID, versionUuid)
.and(predecessorsProp.property())
.and();
Path frozenVersionPath = path(versionPath, JcrLexicon.FROZEN_NODE);
systemBatch.create(frozenVersionPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FROZEN_NODE)
.and(JcrLexicon.FROZEN_UUID, jcrUuid)
.and(JcrLexicon.FROZEN_PRIMARY_TYPE, primaryTypeName)
.and(JcrLexicon.FROZEN_MIXIN_TYPES, mixinTypeNames)
.and(versionedPropertiesFor(node))
.and();
int onParentVersion = node.getDefinition().getOnParentVersion();
for (NodeIterator childNodes = node.getNodes(); childNodes.hasNext();) {
AbstractJcrNode childNode = (AbstractJcrNode)childNodes.nextNode();
versionNodeAt(childNode, frozenVersionPath, systemBatch, onParentVersion);
}
PropertyFactory propFactory = propertyFactory();
for (Object ob : predecessorsProp.property()) {
UUID predUuid = uuid(ob);
org.modeshape.graph.property.Property successorsProp = systemGraph.getNodeAt(predUuid)
.getProperty(JcrLexicon.SUCCESSORS);
List<Object> newSuccessors = new LinkedList<Object>();
boolean alreadySuccessor = false;
if (successorsProp != null) {
for (Object successor : successorsProp) {
newSuccessors.add(successor);
if (uuid(successor).equals(predUuid)) alreadySuccessor = true;
}
}
if (!alreadySuccessor) {
newSuccessors.add(versionUuid);
org.modeshape.graph.property.Property newSuccessorsProp = propFactory.create(JcrLexicon.SUCCESSORS,
newSuccessors.toArray());
systemBatch.set(newSuccessorsProp).on(predUuid).and();
}
}
systemBatch.execute();
historyNode.refresh(false);
AbstractJcrNode newVersion = cache().findJcrNode(Location.create(versionUuid));
NodeEditor editor = node.editor();
editor.setProperty(JcrLexicon.PREDECESSORS,
node.valuesFrom(PropertyType.REFERENCE, EMPTY_OBJECT_ARRAY),
PropertyType.REFERENCE,
false);
editor.setProperty(JcrLexicon.BASE_VERSION, node.valueFrom(newVersion), false, false);
editor.setProperty(JcrLexicon.IS_CHECKED_OUT, node.valueFrom(PropertyType.BOOLEAN, false), false, false);
node.save();
return (JcrVersionNode)newVersion;
}
/**
* Create a version record for the given node under the given parent path with the given batch.
*
* @param node the node for which the frozen version record should be created
* @param verisonedParentPath the parent for the frozen version record for this node
* @param batch the batch with which the frozen version should be created
* @param onParentVersionAction the {@link OnParentVersionAction} of the node whose {@link #checkin} resulted in this node
* being versioned
* @throws RepositoryException if an error occurs accessing the repository
*/
@SuppressWarnings( "fallthrough" )
private void versionNodeAt( AbstractJcrNode node,
Path verisonedParentPath,
Graph.Batch batch,
int onParentVersionAction ) throws RepositoryException {
Path childPath = path(verisonedParentPath, node.path().getLastSegment());
Name primaryTypeName = node.getPrimaryTypeName();
List<Name> mixinTypeNames = node.getMixinTypeNames();
UUID uuid = UUID.randomUUID();
if (node.isReferenceable()) uuid = node.uuid();
switch (onParentVersionAction) {
case OnParentVersionAction.ABORT:
throw new VersionException(JcrI18n.cannotCheckinNodeWithAbortChildNode.text(node.getName(), node.getParent()
.getName()));
case OnParentVersionAction.VERSION:
if (node.isNodeType(JcrMixLexicon.VERSIONABLE)) {
JcrVersionHistoryNode history = node.getVersionHistory();
UUID historyUuid = history.uuid();
batch.create(childPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.VERSIONED_CHILD)
.with(JcrLexicon.CHILD_VERSION_HISTORY, historyUuid)
.and();
break;
}
// Otherwise, treat it as a copy, as per 8.2.11.2 in the 1.0.1 Spec
case OnParentVersionAction.COPY:
batch.create(childPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FROZEN_NODE)
.and(JcrLexicon.FROZEN_PRIMARY_TYPE, primaryTypeName)
.and(JcrLexicon.FROZEN_MIXIN_TYPES, mixinTypeNames)
.and(JcrLexicon.FROZEN_UUID, uuid)
.and(versionedPropertiesFor(node))
.and();
break;
case OnParentVersionAction.INITIALIZE:
case OnParentVersionAction.COMPUTE:
case OnParentVersionAction.IGNORE:
// Do nothing for these. No built-in types require initialize or compute for child nodes.
return;
default:
throw new IllegalStateException("Unexpected value: " + onParentVersionAction);
}
for (NodeIterator childNodes = node.getNodes(); childNodes.hasNext();) {
AbstractJcrNode childNode = (AbstractJcrNode)childNodes.nextNode();
versionNodeAt(childNode, childPath, batch, onParentVersionAction);
}
}
/**
* @param node the node for which the properties should be versioned
* @return the versioned properties for {@code node} (i.e., the properties to add the the frozen version of {@code node}
* @throws RepositoryException if an error occurs accessing the repository
*/
private Collection<org.modeshape.graph.property.Property> versionedPropertiesFor( AbstractJcrNode node )
throws RepositoryException {
Collection<org.modeshape.graph.property.Property> props = new LinkedList<org.modeshape.graph.property.Property>();
// Have to add this directly as it's not returned by AbstractJcrNode.getProperties
AbstractJcrProperty multiValuedProperties = node.getProperty(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES);
if (multiValuedProperties != null) props.add(multiValuedProperties.property());
for (PropertyIterator iter = node.getProperties(); iter.hasNext();) {
AbstractJcrProperty property = (AbstractJcrProperty)iter.nextProperty();
org.modeshape.graph.property.Property prop = property.property();
PropertyDefinitionId propDefnId = property.propertyInfo().getPayload().getPropertyDefinitionId();
JcrPropertyDefinition propDefn = cache().nodeTypes().getPropertyDefinition(propDefnId);
switch (propDefn.getOnParentVersion()) {
case OnParentVersionAction.ABORT:
I18n msg = JcrI18n.cannotCheckinNodeWithAbortProperty;
throw new VersionException(msg.text(property.getName(), node.getName()));
case OnParentVersionAction.COPY:
case OnParentVersionAction.VERSION:
props.add(prop);
break;
case OnParentVersionAction.INITIALIZE:
case OnParentVersionAction.COMPUTE:
case OnParentVersionAction.IGNORE:
// Do nothing for these
}
}
return props;
}
/**
* Checks out the given node, updating version-related properties on the node as needed.
*
* @param node the node to be checked out
* @throws LockException if a lock prevents the node from being checked out
* @throws RepositoryException if an error occurs during the checkout. See {@link javax.jcr.Node#checkout()} for a full
* description of the possible error conditions.
*/
void checkout( AbstractJcrNode node ) throws LockException, RepositoryException {
session.checkLive();
checkVersionable(node);
// Check this separately since it throws a different type of exception
if (node.isLocked() && !node.holdsLock()) {
throw new LockException(JcrI18n.lockTokenNotHeld.text(node.getPath()));
}
/*
* This happens when we've added mix:versionable, but not saved it to create the base
* version (and the rest of the version storage graph). See MODE-704.
*/
if (!node.hasProperty(JcrLexicon.BASE_VERSION)) {
return;
}
// Checking out an already checked-out node is supposed to return silently
if (node.getProperty(JcrLexicon.IS_CHECKED_OUT).getBoolean()) {
return;
}
PropertyFactory propFactory = propertyFactory();
PropertyInfo<JcrPropertyPayload> mvProp = node.nodeInfo().getProperty(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES);
org.modeshape.graph.property.Property multiValuedProps = mvProp != null ? mvProp.getProperty() : null;
if (multiValuedProps == null) {
multiValuedProps = propFactory.create(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES, JcrLexicon.PREDECESSORS);
} else if (!Arrays.<Object>asList(multiValuedProps.getValues()).contains(JcrLexicon.PREDECESSORS)) {
List<Object> values = new LinkedList<Object>();
for (Object value : multiValuedProps) {
values.add(value);
}
values.add(JcrLexicon.PREDECESSORS);
multiValuedProps = propFactory.create(ModeShapeIntLexicon.MULTI_VALUED_PROPERTIES, values);
}
ValueFactory<Reference> refFactory = context().getValueFactories().getReferenceFactory();
Object[] newPreds = new Object[] {refFactory.create(node.getBaseVersion().uuid())};
org.modeshape.graph.property.Property isCheckedOut = propFactory.create(JcrLexicon.IS_CHECKED_OUT, true);
org.modeshape.graph.property.Property predecessors = propFactory.create(JcrLexicon.PREDECESSORS, newPreds);
Graph graph = workspace().graph();
Location location = Location.create(node.uuid());
graph.set(isCheckedOut, predecessors, multiValuedProps).on(location).and();
cache().refreshProperties(location);
}
/**
* See {@link javax.jcr.Workspace#restore(Version[], boolean)} for details of this operation.
*
* @param versions the versions to be restored
* @param removeExisting if UUID conflicts resulting from this restore should cause the conflicting node to be removed or an
* exception to be thrown and the operation to fail
* @throws RepositoryException if an error occurs accessing the repository
* @see javax.jcr.Workspace#restore(Version[], boolean)
*/
@Override
public void restore( Version[] versions,
boolean removeExisting ) throws RepositoryException {
session.checkLive();
if (session.hasPendingChanges()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowed.text());
}
Map<Version, AbstractJcrNode> existingVersions = new HashMap<Version, AbstractJcrNode>(versions.length);
Set<Path> versionRootPaths = new HashSet<Path>(versions.length);
List<Version> nonExistingVersions = new ArrayList<Version>(versions.length);
for (int i = 0; i < versions.length; i++) {
VersionHistory history = versions[i].getContainingHistory();
if (history.getRootVersion().isSame(versions[i])) {
throw new VersionException(JcrI18n.cannotRestoreRootVersion.text(versions[i].getPath()));
}
try {
AbstractJcrNode existingNode = session.getNodeByIdentifier(history.getVersionableIdentifier());
existingVersions.put(versions[i], existingNode);
versionRootPaths.add(existingNode.path());
} catch (ItemNotFoundException infe) {
nonExistingVersions.add(versions[i]);
}
}
if (existingVersions.isEmpty()) {
throw new VersionException(JcrI18n.noExistingVersionForRestore.text());
}
RestoreCommand op = new RestoreCommand(existingVersions, versionRootPaths, nonExistingVersions, null, removeExisting);
op.execute();
session.save();
}
/**
* Restores the given version to the given path.
*
* @param path the path at which the version should be restored; may not be null
* @param version the version to restore; may not be null
* @param labelToRestore the label that was used to identify the version; may be null
* @param removeExisting if UUID conflicts resulting from this restore should cause the conflicting node to be removed or an
* exception to be thrown and the operation to fail
* @throws RepositoryException if an error occurs accessing the repository
* @see javax.jcr.Node#restore(Version, String, boolean)
* @see javax.jcr.Node#restoreByLabel(String, boolean)
*/
void restore( Path path,
Version version,
String labelToRestore,
boolean removeExisting ) throws RepositoryException {
session.checkLive();
if (session().hasPendingChanges()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowed.text());
}
// Ensure that the parent node exists - this will throw a PNFE if no node exists at that path
AbstractJcrNode parentNode = cache().findJcrNode(null, path.getParent());
AbstractJcrNode existingNode = null;
AbstractJcrNode nodeToCheckLock;
JcrVersionNode jcrVersion = (JcrVersionNode)version;
try {
existingNode = cache().findJcrNode(null, path);
nodeToCheckLock = existingNode;
// These checks only make sense if there is an existing node
JcrVersionHistoryNode versionHistory = existingNode.getVersionHistory();
if (!versionHistory.isSame(jcrVersion.getParent())) {
throw new VersionException(JcrI18n.invalidVersion.text(version.getPath(), versionHistory.getPath()));
}
if (!versionHistory.isSame(existingNode.getVersionHistory())) {
throw new VersionException(JcrI18n.invalidVersion.text(version.getPath(), existingNode.getVersionHistory()
.getPath()));
}
if (jcrVersion.isSame(versionHistory.getRootVersion())) {
throw new VersionException(JcrI18n.cannotRestoreRootVersion.text(existingNode.getPath()));
}
} catch (ItemNotFoundException pnfe) {
// This is allowable, but the node needs to be checked out
if (!parentNode.isCheckedOut()) {
String parentPath = path.getString(context().getNamespaceRegistry());
throw new VersionException(JcrI18n.nodeIsCheckedIn.text(parentPath));
}
AbstractJcrNode sourceNode = frozenNodeFor(version);
Name primaryTypeName = name(sourceNode.getProperty(JcrLexicon.FROZEN_PRIMARY_TYPE).property().getFirstValue());
AbstractJcrProperty uuidProp = sourceNode.getProperty(JcrLexicon.FROZEN_UUID);
UUID desiredUuid = uuid(uuidProp.property().getFirstValue());
existingNode = parentNode.editor().createChild(path.getLastSegment().getName(), desiredUuid, primaryTypeName);
nodeToCheckLock = parentNode;
}
if (nodeToCheckLock.isLocked() && !nodeToCheckLock.holdsLock()) {
throw new LockException(JcrI18n.lockTokenNotHeld.text(nodeToCheckLock.getPath()));
}
RestoreCommand op = new RestoreCommand(Collections.singletonMap(version, existingNode),
Collections.singleton(existingNode.path()), Collections.<Version>emptySet(),
labelToRestore, removeExisting);
op.execute();
NodeEditor editor = existingNode.editor();
editor.setProperty(JcrLexicon.IS_CHECKED_OUT, existingNode.valueFrom(PropertyType.BOOLEAN, false), false, false);
editor.setProperty(JcrLexicon.BASE_VERSION, existingNode.valueFrom(jcrVersion), false, false);
session().save();
}
/**
* @param version the version for which the frozen node should be returned
* @return the frozen node for the given version
* @throws RepositoryException if an error occurs accessing the repository
*/
AbstractJcrNode frozenNodeFor( Version version ) throws RepositoryException {
return ((AbstractJcrNode)version).getNode(JcrLexicon.FROZEN_NODE);
}
void doneMerge( AbstractJcrNode targetNode,
Version version ) throws RepositoryException {
session.checkLive();
checkVersionable(targetNode);
if (targetNode.isNew() || targetNode.isModified()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowedForNode.text());
}
if (!targetNode.isNodeType(JcrMixLexicon.VERSIONABLE)) {
throw new VersionException(JcrI18n.requiresVersionable.text());
}
AbstractJcrProperty prop = targetNode.getProperty(JcrLexicon.PREDECESSORS);
JcrValue[] values = (JcrValue[])prop.getValues();
JcrValue[] newValues = new JcrValue[values.length + 1];
System.arraycopy(values, 0, newValues, 0, values.length);
newValues[values.length] = targetNode.valueFrom(version);
targetNode.editor().setProperty(JcrLexicon.PREDECESSORS, newValues, PropertyType.REFERENCE, false);
removeVersionFromMergeFailedProperty(targetNode, version);
targetNode.save();
}
void cancelMerge( AbstractJcrNode targetNode,
Version version ) throws RepositoryException {
session.checkLive();
checkVersionable(targetNode);
if (targetNode.isNew() || targetNode.isModified()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowedForNode.text());
}
if (!targetNode.isNodeType(JcrMixLexicon.VERSIONABLE)) {
throw new UnsupportedRepositoryOperationException(JcrI18n.requiresVersionable.text());
}
removeVersionFromMergeFailedProperty(targetNode, version);
targetNode.save();
}
@SuppressWarnings( "deprecation" )
private void removeVersionFromMergeFailedProperty( AbstractJcrNode targetNode,
Version version ) throws RepositoryException {
if (!targetNode.hasProperty(JcrLexicon.MERGE_FAILED)) {
throw new VersionException(JcrI18n.versionNotInMergeFailed.text(version.getName(), targetNode.getPath()));
}
AbstractJcrProperty prop = targetNode.getProperty(JcrLexicon.MERGE_FAILED);
Value[] values = prop.getValues();
String uuidString = version.getUUID();
int matchIndex = -1;
for (int i = 0; i < values.length; i++) {
if (uuidString.equals(values[i].getString())) {
matchIndex = i;
break;
}
}
if (matchIndex == -1) {
throw new VersionException(JcrI18n.versionNotInMergeFailed.text(version.getName(), targetNode.getPath()));
}
if (values.length == 1) {
prop.remove();
} else {
Value[] newValues = new JcrValue[values.length - 2];
if (matchIndex == 0) {
System.arraycopy(values, 1, newValues, 0, values.length - 1);
} else if (matchIndex == values.length - 1) {
System.arraycopy(values, 0, newValues, 0, values.length - 2);
} else {
System.arraycopy(values, 0, newValues, 0, matchIndex);
System.arraycopy(values, matchIndex + 1, newValues, matchIndex, values.length - matchIndex - 1);
}
prop.setValue(newValues);
}
}
NodeIterator merge( AbstractJcrNode targetNode,
String srcWorkspace,
boolean bestEffort,
boolean isShallow ) throws RepositoryException {
session.checkLive();
if (session().hasPendingChanges()) {
throw new InvalidItemStateException(JcrI18n.noPendingChangesAllowed.text());
}
try {
targetNode.correspondingNodePath(srcWorkspace);
} catch (ItemNotFoundException infe) {
// return immediately if no corresponding node exists in that workspace
return new JcrChildNodeIterator(Collections.<AbstractJcrNode>emptySet(), 0);
}
JcrSession sourceSession = session().with(srcWorkspace);
MergeCommand op = new MergeCommand(targetNode, sourceSession, bestEffort, isShallow);
op.execute();
session.save();
return op.getFailures();
}
/**
* Restores the given property onto the node managed by the given editor
*
* @param property the property to restore; may not be null
* @param editor the {@link NodeEditor editor} for the node that is to be modified; may not be null
* @throws RepositoryException if an error occurs while accessing the repository or setting the property
*/
void restoreProperty( AbstractJcrProperty property,
NodeEditor editor ) throws RepositoryException {
Name propName = property.name();
editor.removeProperty(propName);
if (property.isMultiple()) {
JcrValue[] values = (JcrValue[])property.getValues();
editor.setProperty(propName, values, property.getType(), false);
} else {
JcrValue value = (JcrValue)property.getValue();
editor.setProperty(propName, value, false, false);
}
}
void initializeVersionHistoryFor( AbstractJcrNode node ) throws RepositoryException {
initializeVersionHistoryFor(node, null);
}
void initializeVersionHistoryFor( AbstractJcrNode node,
UUID originalVersionUuid ) throws RepositoryException {
Batch batch = session().createBatch();
initializeVersionHistoryFor(batch, node.nodeInfo(), originalVersionUuid, true);
batch.execute();
}
void initializeVersionHistoryFor( Graph.Batch batch,
Node<JcrNodePayload, JcrPropertyPayload> node,
UUID originalVersionUuid,
boolean forceWrite ) throws RepositoryException {
if (!cache().isVersionable(node)) return;
/*
* Determine if the node has already had its version history initialized based on whether the protected property
* jcr:isCheckedOut exists.
*/
boolean initialized = node.getProperty(JcrLexicon.IS_CHECKED_OUT) != null;
if (!forceWrite && initialized) return;
UUID historyUuid = UUID.randomUUID();
UUID versionUuid = UUID.randomUUID();
List<UUID> existingPredecessors = new ArrayList<UUID>();
versionUuid = initializeVersionStorageFor(node, historyUuid, originalVersionUuid, versionUuid, existingPredecessors);
ValueFactory<Reference> refFactory = context().getValueFactories().getReferenceFactory();
Object[] predecessorRefs = new Object[existingPredecessors.size()];
if (!existingPredecessors.isEmpty()) {
int i = 0;
for (UUID existingPredecessor : existingPredecessors) {
assert existingPredecessor != null;
predecessorRefs[i++] = refFactory.create(existingPredecessor);
}
}
org.modeshape.graph.property.Property isCheckedOut = propertyFactory().create(JcrLexicon.IS_CHECKED_OUT, true);
org.modeshape.graph.property.Property versionHistory = propertyFactory().create(JcrLexicon.VERSION_HISTORY,
refFactory.create(historyUuid));
org.modeshape.graph.property.Property baseVersion = propertyFactory().create(JcrLexicon.BASE_VERSION,
refFactory.create(versionUuid));
org.modeshape.graph.property.Property predecessors = propertyFactory().create(JcrLexicon.PREDECESSORS, predecessorRefs);
// This batch will get executed as part of the save
batch.set(isCheckedOut, versionHistory, baseVersion, predecessors).on(node.getPath()).and();
// Refresh the version storage node ...
Node<JcrNodePayload, JcrPropertyPayload> storageNode = cache().findNode(null, versionStoragePath);
cache().refresh(storageNode.getNodeId(), versionStoragePath, false);
}
UUID initializeVersionStorageFor( Node<JcrNodePayload, JcrPropertyPayload> node,
UUID historyUuid,
UUID originalVersionUuid,
UUID versionUuid,
List<UUID> predecessors ) {
JcrNodePayload payload = node.getPayload();
Graph systemGraph = session().repository().createSystemGraph(context());
Name primaryTypeName = payload.getPrimaryTypeName();
List<Name> mixinTypeNames = payload.getMixinTypeNames();
PropertyInfo<JcrPropertyPayload> jcrUuidProp = node.getProperty(JcrLexicon.UUID);
UUID jcrUuid = uuid(jcrUuidProp.getProperty().getFirstValue());
Path historyPath = versionHistoryPathFor(jcrUuid);
Batch systemBatch = systemGraph.batch();
// Determine if there are any intermediate paths to where this history node is to be ...
Path[] intermediatePaths = versionHistoryPathsTo(historyPath);
if (intermediatePaths != null) {
// Create any intermediate nodes, if absent ...
for (Path intermediatePath : intermediatePaths) {
systemBatch.create(intermediatePath)
.with(JcrLexicon.PRIMARY_TYPE, ModeShapeLexicon.VERSION_HISTORY_FOLDER)
.ifAbsent()
.and();
}
}
systemBatch.create(historyPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.VERSION_HISTORY)
.and(JcrLexicon.VERSIONABLE_UUID, jcrUuid)
.and(JcrLexicon.UUID, historyUuid)
.ifAbsent()
.and();
if (originalVersionUuid != null) {
systemBatch.set(JcrLexicon.COPIED_FROM).on(historyPath).to(originalVersionUuid).and();
}
Path versionLabelsPath = path(historyPath, JcrLexicon.VERSION_LABELS);
systemBatch.create(versionLabelsPath).with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.VERSION_LABELS).ifAbsent().and();
Path rootVersionPath = path(historyPath, JcrLexicon.ROOT_VERSION);
DateTime now = context().getValueFactories().getDateFactory().create();
systemBatch.create(rootVersionPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.VERSION)
.and(JcrLexicon.CREATED, now)
.and(JcrLexicon.UUID, versionUuid)
.ifAbsent()
.and();
Path frozenVersionPath = path(rootVersionPath, JcrLexicon.FROZEN_NODE);
systemBatch.create(frozenVersionPath)
.with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FROZEN_NODE)
.and(JcrLexicon.FROZEN_UUID, jcrUuid)
.and(JcrLexicon.FROZEN_PRIMARY_TYPE, primaryTypeName)
.and(JcrLexicon.FROZEN_MIXIN_TYPES, mixinTypeNames)
.ifAbsent()
.and();
systemBatch.execute();
// Re-read the version UUID, in case the version history was already there ...
org.modeshape.graph.Node rootVersion = systemGraph.getNodeAt(rootVersionPath);
UUID baseVersion = rootVersion.getLocation().getUuid();
if (!baseVersion.equals(versionUuid)) {
// The version history already exists, so baseVersion should be set to the version without
// a successor, and the predecessors should be set to the base version ...
org.modeshape.graph.Node historyNode = systemGraph.getNodeAt(historyPath);
for (Location childLocation : historyNode.getChildren()) {
if (childLocation.getPath().endsWith(JcrLexicon.ROOT_VERSION)) continue;
if (childLocation.getPath().endsWith(JcrLexicon.VERSION_LABELS)) continue;
org.modeshape.graph.Node versionNode = systemGraph.getNodeAt(childLocation);
if (versionNode.getProperty(JcrLexicon.SUCCESSORS) == null) {
baseVersion = childLocation.getUuid();
break;
}
}
}
predecessors.add(baseVersion);
assert baseVersion != null;
return baseVersion;
}
@NotThreadSafe
private class RestoreCommand {
private Map<Version, AbstractJcrNode> existingVersions;
private Set<Path> versionRootPaths;
private Collection<Version> nonExistingVersions;
private boolean removeExisting;
private String labelToRestore;
private Map<AbstractJcrNode, AbstractJcrNode> changedNodes;
public RestoreCommand( Map<Version, AbstractJcrNode> existingVersions,
Set<Path> versionRootPaths,
Collection<Version> nonExistingVersions,
String labelToRestore,
boolean removeExisting ) {
super();
this.existingVersions = existingVersions;
this.versionRootPaths = versionRootPaths;
this.nonExistingVersions = nonExistingVersions;
this.removeExisting = removeExisting;
this.labelToRestore = labelToRestore;