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.resources.app.availability;
35
36 import info.magnolia.jcr.util.SessionUtil;
37 import info.magnolia.resourceloader.Resource;
38 import info.magnolia.resourceloader.ResourceOrigin;
39 import info.magnolia.resourceloader.jcr.JcrResourceOrigin;
40 import info.magnolia.resourceloader.layered.LayeredResource;
41 import info.magnolia.ui.vaadin.integration.contentconnector.ContentConnector;
42
43 import java.util.List;
44
45 import javax.inject.Inject;
46 import javax.jcr.Node;
47 import javax.jcr.RepositoryException;
48
49 import org.apache.commons.io.FilenameUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 import com.google.common.collect.Lists;
54 import com.google.common.net.MediaType;
55 import com.vaadin.data.Item;
56 import com.vaadin.data.Property;
57
58
59
60
61
62
63
64
65
66
67 public class IsNotBinaryFileRule extends AbstractResourceAvailabilityRule {
68
69 private static final Logger log = LoggerFactory.getLogger(IsNotBinaryFileRule.class);
70 private static final List WHITELISTED_EXTENSIONS = Lists.newArrayList("bpmn", "css", "dtd", "ftl", "html", "js", "jocl", "json", "lsp", "lst", "ltx", "text", "xml", "xsb", "xsd");
71
72 private final ContentConnector contentConnector;
73
74 @Inject
75 public IsNotBinaryFileRule(ResourceOrigin origin, ContentConnector contentConnector) {
76 super(origin);
77 this.contentConnector = contentConnector;
78 }
79
80 @Override
81 protected boolean isAvailableFor(Resource itemId) {
82 LayeredResource layeredResource = (LayeredResource) itemId;
83
84 if (layeredResource.getFirst().getOrigin() instanceof JcrResourceOrigin) {
85 String resourcePath = layeredResource.getFirst().getPath();
86 try {
87 Node node = SessionUtil.getNode(JcrResourceOrigin.RESOURCES_WORKSPACE, resourcePath);
88 if (node != null) {
89 if (node.hasNode(JcrResourceOrigin.BINARY_NODE_NAME)) {
90 return false;
91 } else if (node.hasProperty(JcrResourceOrigin.TEXT_PROPERTY)) {
92 return true;
93 }
94 }
95 } catch (RepositoryException e) {
96 log.warn("Error evaluating availability for node [{}]", itemId.getPath(), e.getMessage());
97 }
98 return false;
99 }
100
101
102 Item item = contentConnector.getItem(itemId.getPath());
103 MediaType type = resolveMediaType(item);
104 return (type != null && type.is(MediaType.ANY_TEXT_TYPE)) || isExtensionWhitelisted(itemId.getName());
105 }
106
107 private MediaType resolveMediaType(Item item) {
108 Property mimeTypeProperty = item.getItemProperty("format");
109 if (mimeTypeProperty != null && mimeTypeProperty.getValue() != null) {
110 String resourceFormat = mimeTypeProperty.getValue().toString();
111 return MediaType.parse(resourceFormat);
112 }
113 return null;
114 }
115
116 private boolean isExtensionWhitelisted(String fileName) {
117 String extension = FilenameUtils.getExtension(fileName);
118 return WHITELISTED_EXTENSIONS.contains(extension);
119 }
120 }