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 * Creates a new filtering suffix state strategy.
43 * @param suffixPartFilter the {@link Predicate} that defines which suffix parts are allowed
44 */
45 public FilteringSuffixStateStrategy(Predicate<String> suffixPartFilter) {
46 this.suffixPartFilter = suffixPartFilter;
47 }
48
49 @Override
50 public @NotNull List<String> getSuffixPartsToKeep(@NotNull SlingHttpServletRequest request) {
51
52 // get and split suffix parts from the current request
53 String existingSuffix = request.getRequestPathInfo().getSuffix();
54 String[] suffixPartArray = splitSuffix(existingSuffix);
55
56 // iterate over all these suffix parts and gather those that should be kept
57 List<String> suffixPartsToKeep = new ArrayList<>();
58 for (int i = 0; i < suffixPartArray.length; i++) {
59 String nextPart = suffixPartArray[i];
60
61 // for each part: check filter if it should be inc
62 if (suffixPartFilter == null || suffixPartFilter.test(nextPart)) {
63 suffixPartsToKeep.add(nextPart);
64 }
65 }
66
67 return suffixPartsToKeep;
68 }
69
70 }