7980255e3e8a5d9019ed65a4de028b28c903ffb7
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / commandline / parameterparser / parameter / FileParameter.java
1 package eu.svjatoslav.commons.commandline.parameterparser.parameter;
2
3 import java.io.File;
4
5 import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
6 import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
7
8 public class FileParameter extends Parameter {
9
10         private ExistanceType existanceType = ExistanceType.DOES_NOT_MATTER;
11
12         public FileParameter(final String description) {
13                 super(description, ArgumentCount.SINGLE);
14         }
15
16         @Override
17         public FileParameter addAliases(final String... aliasArray) {
18                 super.addAliases(aliasArray);
19                 return this;
20         }
21
22         @Override
23         public java.lang.String describeFormat() {
24                 return existanceType.description + "file";
25         }
26
27         public File getValue() {
28
29                 if (arguments.size() != 1)
30                         throw new RuntimeException("Parameter " + description
31                                         + " shall have exactly 1 argument.");
32
33                 return new File(arguments.get(0));
34         }
35
36         public FileParameter mustExist() {
37                 existanceType = ExistanceType.MUST_EXIST;
38                 return this;
39         }
40
41         public FileParameter mustNotExist() {
42                 existanceType = ExistanceType.MUST_NOT_EXIST;
43                 return this;
44         }
45
46         @Override
47         public FileParameter setMandatory() {
48                 mandatory = true;
49                 return this;
50         }
51
52         @Override
53         public boolean validate(final java.lang.String value) {
54                 final File file = new File(value);
55
56                 if (existanceType == ExistanceType.MUST_EXIST) {
57                         if (file.exists() && file.isFile())
58                                 return true;
59                         return false;
60                 }
61
62                 if (existanceType == ExistanceType.MUST_NOT_EXIST) {
63                         if (file.exists())
64                                 return false;
65                         return true;
66                 }
67
68                 if (existanceType == ExistanceType.DOES_NOT_MATTER) {
69                         if (file.exists())
70                                 if (file.isDirectory())
71                                         return false;
72
73                         return true;
74                 }
75
76                 return false;
77         }
78
79 }