View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2021 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
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   * {@link ContentHandler} implementation that produces a tree of {@link ContentElement} items.
34   */
35  final class ContentElementHandler implements ContentHandler {
36  
37    private ContentElement root;
38  
39    @SuppressWarnings("java:S5998") // paths are assumed to be safe
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  }