use generics for more elegant code
[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-2014, 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 java.io.File;
13
14 import eu.svjatoslav.commons.commandline.parameterparser.ArgumentCount;
15 import eu.svjatoslav.commons.commandline.parameterparser.Parameter;
16
17 public class FileParameter extends Parameter<FileParameter> {
18
19         private ExistanceType existanceType = ExistanceType.DOES_NOT_MATTER;
20
21         public FileParameter(final String description) {
22                 super(description, ArgumentCount.SINGLE);
23         }
24
25         @Override
26         public java.lang.String describeFormat() {
27                 return existanceType.description + " file";
28         }
29
30         @Override
31         public File getValue() {
32
33                 if (arguments.size() != 1)
34                         throw new RuntimeException("Parameter " + description
35                                         + " shall have exactly 1 argument.");
36
37                 return new File(arguments.get(0));
38         }
39
40         public FileParameter mustExist() {
41                 existanceType = ExistanceType.MUST_EXIST;
42                 return this;
43         }
44
45         public FileParameter mustNotExist() {
46                 existanceType = ExistanceType.MUST_NOT_EXIST;
47                 return this;
48         }
49
50         @Override
51         public boolean validate(final java.lang.String value) {
52                 final File file = new File(value);
53
54                 if (existanceType == ExistanceType.MUST_EXIST) {
55                         if (file.exists() && file.isFile())
56                                 return true;
57                         return false;
58                 }
59
60                 if (existanceType == ExistanceType.MUST_NOT_EXIST) {
61                         if (file.exists())
62                                 return false;
63                         return true;
64                 }
65
66                 if (existanceType == ExistanceType.DOES_NOT_MATTER) {
67                         if (file.exists())
68                                 if (file.isDirectory())
69                                         return false;
70
71                         return true;
72                 }
73
74                 return false;
75         }
76
77 }