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.ui.databinding.converter;
35
36 import info.magnolia.cms.util.PathUtil;
37 import info.magnolia.ui.datasource.jcr.JcrDatasourceDefinition;
38 import info.magnolia.ui.datasource.jcr.JcrSessionManager;
39
40 import java.util.Optional;
41
42 import javax.jcr.Node;
43 import javax.jcr.RepositoryException;
44 import javax.jcr.Session;
45
46 import com.vaadin.data.Converter;
47 import com.vaadin.data.Result;
48 import com.vaadin.data.ValueContext;
49
50 import lombok.SneakyThrows;
51
52
53
54
55
56 public class JcrItemToLinkConverter implements Converter<Node, String> {
57
58 private final JcrDatasourceDefinition definition;
59 private final JcrSessionManager contentDecorator;
60
61 public JcrItemToLinkConverter(JcrDatasourceDefinition definition, JcrSessionManager contentDecorator) {
62 this.definition = definition;
63 this.contentDecorator = contentDecorator;
64 }
65
66 @SneakyThrows(RepositoryException.class)
67 @Override
68 public Result<String> convertToModel(Node value, ValueContext context) {
69 if (value == null) {
70 return Result.ok(null);
71 }
72 return Result.ok(value.getIdentifier());
73 }
74
75 @Override
76 public Node convertToPresentation(String value, ValueContext context) {
77 if (value == null) {
78 return null;
79 }
80 return resolveNodeByIdOrPath(value);
81 }
82
83 private Node resolveNodeByIdOrPath(String value) {
84
85 return Optional.ofNullable(getNodeByIdSafely(value))
86 .orElseGet(() -> getNodeByPath(value));
87 }
88
89 private Session getSession() throws RepositoryException {
90 return contentDecorator.getJCRSession();
91 }
92
93 private Node getNodeByIdSafely(String value) {
94 try {
95 return getSession().getNodeByIdentifier(value);
96 } catch (RepositoryException e) {
97
98 return null;
99 }
100 }
101
102 @SneakyThrows(RepositoryException.class)
103 private Node getNodeByPath(String value) {
104 return getSession().getNode(PathUtil.createPath(definition.getRootPath(), value));
105 }
106 }