View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2014 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.handler.url.suffix;
21  
22  import static io.wcm.handler.url.suffix.impl.UrlSuffixUtil.splitSuffix;
23  
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.function.Predicate;
27  
28  import org.apache.sling.api.SlingHttpServletRequest;
29  import org.jetbrains.annotations.NotNull;
30  import org.osgi.annotation.versioning.ProviderType;
31  
32  /**
33   * Implementation of {@link SuffixStateKeepingStrategy} that calls a Filter for each suffix part from the
34   * current request to decide if it should be kept when constructing a new suffix.
35   */
36  @ProviderType
37  public final class FilteringSuffixStateStrategy implements SuffixStateKeepingStrategy {
38  
39    private final Predicate<String> suffixPartFilter;
40  
41    /**
42     * @param suffixPartFilter the {@link Predicate} that defines which suffix parts are allowed
43     */
44    public FilteringSuffixStateStrategy(Predicate<String> suffixPartFilter) {
45      this.suffixPartFilter = suffixPartFilter;
46    }
47  
48    @Override
49    public @NotNull List<String> getSuffixPartsToKeep(@NotNull SlingHttpServletRequest request) {
50  
51      // get and split suffix parts from the current request
52      String existingSuffix = request.getRequestPathInfo().getSuffix();
53      String[] suffixPartArray = splitSuffix(existingSuffix);
54  
55      // iterate over all these suffix parts and gather those that should be kept
56      List<String> suffixPartsToKeep = new ArrayList<>();
57      for (int i = 0; i < suffixPartArray.length; i++) {
58        String nextPart = suffixPartArray[i];
59  
60        // for each part: check filter if it should be inc
61        if (suffixPartFilter == null || suffixPartFilter.test(nextPart)) {
62          suffixPartsToKeep.add(nextPart);
63        }
64      }
65  
66      return suffixPartsToKeep;
67    }
68  
69  }