1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.maven.plugins.slinginitialcontenttransform.contentparser;
21
22 import java.util.Map;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.sling.contentparser.api.ContentHandler;
28
29 import io.wcm.tooling.commons.contentpackagebuilder.element.ContentElement;
30 import io.wcm.tooling.commons.contentpackagebuilder.element.ContentElementImpl;
31
32
33
34
35 final class ContentElementHandler implements ContentHandler {
36
37 private ContentElement root;
38
39 @SuppressWarnings("java:S5998")
40 private static final Pattern PATH_PATTERN = Pattern.compile("^((/[^/]+)*)(/([^/]+))$");
41
42 @Override
43 public void resource(String path, Map<String, Object> properties) {
44 if (StringUtils.equals(path, "/")) {
45 root = new ContentElementImpl(null, properties);
46 }
47 else {
48 if (root == null) {
49 throw new IllegalStateException("Root resource not set.");
50 }
51 Matcher matcher = PATH_PATTERN.matcher(path);
52 if (!matcher.matches()) {
53 throw new IllegalStateException("Unexpected path:" + path);
54 }
55 String relativeParentPath = StringUtils.stripStart(matcher.group(1), "/");
56 String name = matcher.group(4);
57 ContentElement parent;
58 if (StringUtils.isEmpty(relativeParentPath)) {
59 parent = root;
60 }
61 else {
62 parent = root.getChild(relativeParentPath);
63 }
64 if (parent == null) {
65 throw new IllegalStateException("Parent '" + relativeParentPath + "' does not exist.");
66 }
67 parent.getChildren().put(name, new ContentElementImpl(name, properties));
68 }
69 }
70
71 public ContentElement getRoot() {
72 return root;
73 }
74
75 }