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 package info.magnolia.jcr.wrapper;
35
36 import info.magnolia.context.MgnlContext;
37
38 import java.util.Optional;
39
40 import javax.jcr.Node;
41 import javax.jcr.RepositoryException;
42 import javax.jcr.Session;
43
44 import com.machinezoo.noexception.Exceptions;
45
46
47
48
49
50 public class LazyNodeWrapper extends DelegateNodeWrapper {
51
52 private String workspace;
53 private String nodeIdentifier;
54 private transient Node node;
55
56 public static Node of(Node node) {
57 return Optional.ofNullable(node)
58 .map(Exceptions.wrap().function(LazyNodeWrapper::new))
59 .orElse(null);
60 }
61
62 public LazyNodeWrapper(String workspace, String nodeIdentifier) {
63 this.workspace = workspace;
64 this.nodeIdentifier = nodeIdentifier;
65 }
66
67 public LazyNodeWrapper(Node node) throws RepositoryException {
68 this.workspace = node.getSession().getWorkspace().getName();
69 this.nodeIdentifier = node.getIdentifier();
70 this.node = node;
71 }
72
73 @Override
74 public synchronized Node getWrappedNode() {
75 return Optional.ofNullable(node)
76 .filter(Exceptions.wrap().predicate(node -> node.getSession().isLive()))
77 .orElseGet(Exceptions.wrap().supplier(
78 () -> {
79 Session session = getSessionForWrappedNode(workspace);
80 return session.getNodeByIdentifier(nodeIdentifier);
81 })
82 );
83 }
84
85 @Override
86 public void setWrappedNode(Node node) {
87 Exceptions.wrap().run(() -> {
88 workspace = node.getSession().getWorkspace().getName();
89 nodeIdentifier = node.getIdentifier();
90 LazyNodeWrapper.this.node = node;
91 });
92 }
93
94 protected Session getSessionForWrappedNode(String workspace) throws RepositoryException {
95 try {
96 return MgnlContext.getJCRSession(workspace);
97 } catch (Exception e) {
98 return MgnlContext.getSystemContext().getJCRSession(workspace);
99 }
100 }
101 }