Code formatting.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / commandline / parameterparser / parameter / FileParameter.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2017, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.commandline.parameterparser.parameter;
11
12 import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
13 import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
14
15 import java.io.File;
16
17 public class FileParameter extends Parameter<File, FileParameter> {
18
19     private ExistenceType existenceType = ExistenceType.DOES_NOT_MATTER;
20
21     public FileParameter(final String description) {
22         super(description, ArgumentCount.SINGLE);
23     }
24
25     protected static boolean validateFile(ExistenceType existenceType, String value) {
26         final File file = new File(value);
27
28         if (existenceType == ExistenceType.MUST_EXIST) {
29             return file.exists() && file.isFile();
30         }
31
32         if (existenceType == ExistenceType.MUST_NOT_EXIST) {
33             return !file.exists();
34         }
35
36         if (existenceType == ExistenceType.DOES_NOT_MATTER) {
37             if (file.exists())
38                 if (file.isDirectory())
39                     return false;
40
41             return true;
42         }
43
44         return false;
45     }
46
47     @Override
48     public java.lang.String describeFormat() {
49         return existenceType.description + " file";
50     }
51
52     @Override
53     public File getValue() {
54
55         if (arguments.size() != 1)
56             throw new RuntimeException("Parameter " + description
57                     + " shall have exactly 1 argument.");
58
59         return new File(arguments.get(0));
60     }
61
62     public FileParameter mustExist() {
63         existenceType = ExistenceType.MUST_EXIST;
64         return this;
65     }
66
67     public FileParameter mustNotExist() {
68         existenceType = ExistenceType.MUST_NOT_EXIST;
69         return this;
70     }
71
72     @Override
73     public boolean validate(final java.lang.String value) {
74         return validateFile(existenceType, value);
75     }
76
77 }