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.templating.elements.attribute;
35
36 import info.magnolia.context.Context;
37 import info.magnolia.rendering.template.ComponentAvailability;
38 import info.magnolia.templating.elements.AreaElement;
39
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.Optional;
45
46 import javax.inject.Inject;
47 import javax.inject.Provider;
48
49 import org.apache.commons.collections4.CollectionUtils;
50 import org.apache.commons.lang3.StringUtils;
51
52
53
54
55 public class AvailableComponents implements ElementAttribute<AreaElement> {
56
57 private final Provider<Context> contextProvider;
58
59 @Inject
60 public AvailableComponents(Provider<Context> contextProvider) {
61 this.contextProvider = contextProvider;
62 }
63
64 @Override
65 public Optional<String> getValue(AreaElement element) {
66 return Optional.ofNullable(resolveAvailableComponents(element));
67 }
68
69 private String resolveAvailableComponents(AreaElement element) {
70 if (StringUtils.isNotEmpty(element.getAvailableComponents())) {
71 return StringUtils.remove(element.getAvailableComponents(), " ");
72 }
73 if (element.getAreaDefinition() != null && element.getAreaDefinition().getAvailableComponents().size() > 0) {
74 Iterator<ComponentAvailability> iterator = element.getAreaDefinition().getAvailableComponents().values().iterator();
75 List<String> componentIds = new ArrayList<>();
76 final Collection<String> userRoles = contextProvider.get().getUser().getAllRoles();
77 while (iterator.hasNext()) {
78 ComponentAvailability availableComponent = iterator.next();
79 if (availableComponent.isEnabled()) {
80
81 final Collection<String> roles = availableComponent.getRoles();
82 if (!roles.isEmpty()) {
83 if (CollectionUtils.containsAny(userRoles, roles)) {
84 componentIds.add(availableComponent.getId());
85 }
86 } else {
87 componentIds.add(availableComponent.getId());
88 }
89 }
90 }
91 return StringUtils.join(componentIds, ',');
92 }
93 return "";
94 }
95 }