View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2019 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.wcm.ui.granite.pathfield.impl.util;
21  
22  import java.util.Iterator;
23  
24  import org.apache.commons.collections4.Predicate;
25  import org.apache.commons.collections4.iterators.FilterIterator;
26  import org.apache.commons.collections4.iterators.TransformIterator;
27  import org.apache.sling.api.resource.Resource;
28  import org.apache.sling.api.resource.ResourceWrapper;
29  import org.jetbrains.annotations.NotNull;
30  
31  /**
32   * Wraps a resource and filters all children by given predicate.
33   */
34  public class PredicatedResourceWrapper extends ResourceWrapper {
35  
36    private final Predicate<Resource> predicate;
37  
38    /**
39     * @param resource Resource
40     * @param predicate Predicate
41     */
42    public PredicatedResourceWrapper(Resource resource, Predicate<Resource> predicate) {
43      super(resource);
44      this.predicate = predicate;
45    }
46  
47    @Override
48    public Resource getChild(@NotNull String relPath) {
49      Resource child = super.getChild(relPath);
50      if (child == null || !predicate.evaluate(child)) {
51        return null;
52      }
53      return new PredicatedResourceWrapper(child, predicate);
54    }
55  
56    @Override
57    @SuppressWarnings("null")
58    public Iterator<Resource> listChildren() {
59      return new TransformIterator<>(new FilterIterator<>(super.listChildren(), predicate),
60          obj -> new PredicatedResourceWrapper(obj, predicate));
61    }
62  
63    @Override
64    public boolean hasChildren() {
65      if (!super.hasChildren()) {
66        return false;
67      }
68      return listChildren().hasNext();
69    }
70  
71  }