View Javadoc
1   package emissary.command.converter;
2   
3   import org.apache.commons.lang3.StringUtils;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   import picocli.CommandLine.ITypeConverter;
7   
8   import java.nio.file.Files;
9   import java.nio.file.Path;
10  import java.nio.file.Paths;
11  import javax.annotation.Nullable;
12  
13  public class PathExistsConverter implements ITypeConverter<Path> {
14      private final String optionName;
15  
16      public PathExistsConverter() {
17          this(null);
18      }
19  
20      public PathExistsConverter(@Nullable String optionName) {
21          this.optionName = optionName;
22      }
23  
24      private static final Logger LOG = LoggerFactory.getLogger(PathExistsConverter.class);
25  
26      @Override
27      public Path convert(String value) {
28          return convert(optionName, value);
29      }
30  
31      public Path convert(String option, String value) {
32          Path p = Paths.get(StringUtils.removeEnd(value, "/"));
33          // ensure the value exists
34          if (!Files.exists(p)) {
35              String msg = String.format("The option '%s' was configured with path '%s' which does not exist", option, p);
36              LOG.error(msg);
37              throw new IllegalArgumentException(msg);
38          }
39          return p;
40      }
41  
42      public String getOptionName() {
43          return optionName;
44      }
45  
46  }