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.context.Context;
38 import info.magnolia.ui.datasource.jcr.SessionReattachingNodeWrapper;
39 import info.magnolia.ui.datasource.jcr.JcrDatasourceDefinition;
40
41 import java.util.Optional;
42
43 import javax.inject.Provider;
44 import javax.jcr.Node;
45 import javax.jcr.RepositoryException;
46 import javax.jcr.Session;
47
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 import com.vaadin.data.Converter;
52 import com.vaadin.data.Result;
53 import com.vaadin.data.ValueContext;
54
55 import lombok.SneakyThrows;
56
57
58
59
60
61 public class JcrItemToLinkConverter implements Converter<Node, String> {
62
63 private static final Logger log = LoggerFactory.getLogger(JcrItemToLinkConverter.class);
64 private final JcrDatasourceDefinition definition;
65 private final Provider<Context> contextProvider;
66
67 public JcrItemToLinkConverter(JcrDatasourceDefinition definition, Provider<Context> contextProvider) {
68 this.definition = definition;
69 this.contextProvider = contextProvider;
70 }
71
72 @SneakyThrows
73 @Override
74 public Result<String> convertToModel(Node value, ValueContext context) {
75 if (value == null) {
76 return Result.ok(null);
77 }
78 return Result.ok(value.getIdentifier());
79 }
80
81 @Override
82 public Node convertToPresentation(String value, ValueContext context) {
83 if (value == null) {
84 return null;
85 }
86 return resolveNodeByIdOrPath(value);
87 }
88
89 private Node resolveNodeByIdOrPath(String value) {
90 try {
91
92 return new SessionReattachingNodeWrapper(Optional.ofNullable(getNodeByIdSafely(value))
93 .orElseGet(() -> getNodeByPath(value)));
94 } catch (RepositoryException e) {
95 log.warn("Failed to resolve node with provided value [{}]. The item may have been deleted or its name misspelled. Will return null", value);
96 return null;
97 }
98 }
99
100 private Session getSession() throws RepositoryException {
101 return contextProvider.get().getJCRSession(definition.getWorkspace());
102 }
103
104 private Node getNodeByIdSafely(String value) {
105 try {
106 return getSession().getNodeByIdentifier(value);
107 } catch (RepositoryException e) {
108
109 return null;
110 }
111 }
112
113 @SneakyThrows(RepositoryException.class)
114 private Node getNodeByPath(String value) {
115 return getSession().getNode(PathUtil.createPath(definition.getRootPath(), value));
116 }
117 }