1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.handler.url.ui;
21
22 import org.apache.commons.lang3.StringUtils;
23 import org.apache.sling.api.SlingHttpServletRequest;
24 import org.apache.sling.api.resource.Resource;
25 import org.apache.sling.models.annotations.Model;
26 import org.apache.sling.models.annotations.injectorspecific.InjectionStrategy;
27 import org.apache.sling.models.annotations.injectorspecific.Self;
28 import org.jetbrains.annotations.NotNull;
29 import org.jetbrains.annotations.Nullable;
30 import org.osgi.annotation.versioning.ProviderType;
31
32 import com.day.cq.wcm.api.Page;
33 import com.day.cq.wcm.api.PageManager;
34
35 import io.wcm.handler.url.spi.UrlHandlerConfig;
36 import io.wcm.sling.models.annotations.AemObject;
37 import io.wcm.wcm.commons.util.Path;
38
39
40
41
42 @ProviderType
43 @Model(adaptables = {SlingHttpServletRequest.class, Resource.class})
44 public final class SiteRoot {
45
46 private Page siteRootPage;
47
48 @AemObject(injectionStrategy = InjectionStrategy.OPTIONAL)
49 private Page currentPage;
50 @AemObject
51 private PageManager pageManager;
52 @Self
53 private UrlHandlerConfig urlHandlerConfig;
54
55
56
57
58
59
60 public @Nullable String getRootPath(@Nullable Page page) {
61 if (page == null) {
62 return null;
63 }
64 return getRootPath(page.adaptTo(Resource.class));
65 }
66
67
68
69
70
71
72 public @Nullable String getRootPath(@Nullable Resource resource) {
73 int rootLevel = urlHandlerConfig.getSiteRootLevel(resource);
74 if (rootLevel > 0 && resource != null) {
75 return Path.getAbsoluteParent(resource.getPath(), rootLevel, resource.getResourceResolver());
76 }
77 return null;
78 }
79
80
81
82
83
84 public @Nullable String getRootPath() {
85 return getRootPath(currentPage);
86 }
87
88
89
90
91
92 public @Nullable Page getRootPage() {
93 if (siteRootPage == null) {
94 String rootPath = getRootPath();
95 if (rootPath != null) {
96 siteRootPage = pageManager.getPage(getRootPath());
97 }
98 }
99 return siteRootPage;
100 }
101
102
103
104
105
106
107 public @Nullable Page getRelativePage(@NotNull String relativePath) {
108 String path = getRootPath();
109 if (path == null) {
110 return null;
111 }
112 StringBuilder sb = new StringBuilder(path);
113 if (!relativePath.startsWith("/")) {
114 sb.append("/");
115 }
116 sb.append(relativePath);
117 return pageManager.getPage(sb.toString());
118 }
119
120
121
122
123
124 public boolean isRootPage(@NotNull Page page) {
125 return StringUtils.equals(page.getPath(), getRootPath());
126 }
127
128 }