AbstractPathFencedLookup.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements. See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache license, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the license for the specific language governing permissions and
  15.  * limitations under the license.
  16.  */
  17. package org.apache.commons.text.lookup;

  18. import java.nio.file.Path;
  19. import java.nio.file.Paths;
  20. import java.util.Arrays;
  21. import java.util.Collections;
  22. import java.util.List;
  23. import java.util.Optional;
  24. import java.util.stream.Collectors;

  25. /**
  26.  * Abstracts guarding Path lookups with fences.
  27.  */
  28. abstract class AbstractPathFencedLookup extends AbstractStringLookup {

  29.     /**
  30.      * Fences guarding Path resolution.
  31.      */
  32.     protected final List<Path> fences;

  33.     /**
  34.      * Constructs a new instance.
  35.      *
  36.      * @param fences The fences guarding Path resolution.
  37.      */
  38.     AbstractPathFencedLookup(final Path... fences) {
  39.         this.fences = fences != null ? Arrays.stream(fences).map(Path::toAbsolutePath).collect(Collectors.toList()) : Collections.emptyList();
  40.     }

  41.     /**
  42.      * Gets a Path for the given file name checking that it resolves within our fences.
  43.      *
  44.      * @param fileName the file name to resolve.
  45.      * @return a fenced Path.
  46.      * @throws IllegalArgumentException if the file name is not without our fences.
  47.      */
  48.     protected Path getPath(final String fileName) {
  49.         final Path path = Paths.get(fileName);
  50.         if (fences.isEmpty()) {
  51.             return path;
  52.         }
  53.         final Path pathAbs = path.normalize().toAbsolutePath();
  54.         final Optional<Path> first = fences.stream().filter(pathAbs::startsWith).findFirst();
  55.         if (first.isPresent()) {
  56.             return path;
  57.         }
  58.         throw IllegalArgumentExceptions.format("[%s] -> [%s] not in %s", fileName, pathAbs, fences);
  59.     }

  60. }