01: package org.kohsuke.args4j.spi;
02:
03: import java.util.ResourceBundle;
04:
05: import org.kohsuke.args4j.OptionDef;
06: import org.kohsuke.args4j.CmdLineException;
07: import org.kohsuke.args4j.CmdLineParser;
08: import org.kohsuke.args4j.NamedOptionDef;
09:
10: /**
11: * Code that parses operands of an option into Java.
12: *
13: * <p>
14: * This class can be extended by application to support additional Java datatypes in option operands.
15: *
16: * <p>
17: * Implementation of this class needs to be registered to args4j by using
18: * {@link CmdLineParser#registerHandler(Class,Class)}
19: *
20: * @param <T>
21: * The type of the field that this {@link OptionHandler} works with.
22: *
23: * @author Kohsuke Kawaguchi
24: */
25: public abstract class OptionHandler<T> {
26: /**
27: * The annotation.
28: */
29: public final OptionDef option;
30: /**
31: * Object to be used for setting value.
32: */
33: public final Setter<? super T> setter;
34: /**
35: * The owner to which this handler belongs to.
36: */
37: public final CmdLineParser owner;
38:
39: protected OptionHandler(CmdLineParser parser, OptionDef option,
40: Setter<? super T> setter) {
41: this .owner = parser;
42: this .option = option;
43: this .setter = setter;
44: }
45:
46: /**
47: * Called if the option that this owner recognizes is found.
48: *
49: * @param params
50: * The rest of the arguments. This method can use this
51: * object to access the arguments of the option if necessary.
52: *
53: * The object is valid only during the method call.
54: *
55: * @return
56: * The number of arguments consumed. For example, return 0
57: * if this option doesn't take any parameter.
58: */
59: public abstract int parseArguments(Parameters params)
60: throws CmdLineException;
61:
62: /**
63: * Gets the default meta variable name used to print the usage screen.
64: *
65: * @return null to hide a meta variable.
66: */
67: public abstract String getDefaultMetaVariable();
68:
69: public final String getMetaVariable(ResourceBundle rb) {
70: String token = option.metaVar();
71: if (token.length() == 0)
72: token = getDefaultMetaVariable();
73: if (token == null)
74: return null;
75:
76: if (rb != null) {
77: String localized = rb.getString(token);
78: if (localized != null)
79: token = localized;
80: }
81:
82: return token;
83: }
84:
85: public final String getNameAndMeta(ResourceBundle rb) {
86: String str = option.isArgument() ? "" : option.toString();
87: String meta = getMetaVariable(rb);
88: if (meta != null) {
89: if (str.length() > 0) {
90: str += " ";
91: }
92: str += meta;
93: }
94: return str;
95: }
96: }
|