public abstract class Arguments
extends java.lang.Object
class CmdArgs extends Arguments { /**Argument is manually tested in testArgument(...) * / public String sTitle; /**Argument needs a Arguments.SetArgument(...) implementation, longer form * / public File fOut; public File fIn; public String sContent; /**Argument as String value defined in one definition, the value is in timestamp.val But it must be also added with addArg(this.timestamp), see ctor. * / public Argument timestamp = new Argument("-time", ":yyyy-MM-dd+hh:mm sets a timestamp in UTC (GMT)"); /**This is a single SetArgument implementation for one argument which should be added with {(at)link #addArg(Argument)}. Not recommended. / Arguments.SetArgument setOutput = new Arguments.SetArgument(){ (at)Override public boolean setArgument(String val){ CmdArgs.this.fOut = new File(val); return true; }}; /**All Arguments for this application. This is the recommended combination of all in one long array. use {(at)link #addArgs(Argument[])} to add this given array. / Argument[] argsAppl = { new Argument("-o", ":path/to/output.file" , new SetArgument() { (at)Override public boolean setArgument (String val) { CmdArgs.this.fIn = new File(val); return CmdArgs.this.fIn.exists(); } }) , new Argument("-inZip", ":D:/path/to/file.odx:content.xml to analyze a stored XML in a zip format" , new SetArgument() { @Override public boolean setArgument (String val) { int posSep = val.indexOf(':', 3); if(posSep <0) { return false; } CmdArgs.this.fIn = new File(val.substring(0, posSep)); CmdArgs.this.sContent = val.substring(posSep+1); return CmdArgs.this.fIn.exists(); } }) }; CmdArgs () { super.aboutInfo = "...your about info"; super.helpInfo="obligate args: -o:..."; //Hint: the manual tested sTitle don't need addArg(...) addArg(new Argument("-o", ":path/to/output.file", this.setOutput)); addArg(this.timestamp); // add all single given Argument (not recommended, see next) addArgs(this.argsAppl); // add all arguments from Array } /**This operation is only necessary if arguments should be tested manually here, not recommended. The super.testArgument does all the work for given Argument instances. (at)throws FileNotFoundException * / (at)Override protected boolean testArgument(String arg, int nArg) throws FileNotFoundException { boolean bOk = true; //set to false if the argc is not passed String value; if( (value = checkArgVal("-title", arg)) !=null) { this.sTitle = value; //the graphic GUI-appearance } else { bOk = super.testArgument(arg, nArg); } return bOk; } /**This operation checks the consistence of all operations. * / (at)Override public boolean testConsistence(Appendable msg) throws IOException { boolean bOk = true; if(this.fOut == null) { msg.append("-o:outfile obligate\n"); bOk = false; } if(!bOk) { super.showHelp(msg); } return bOk; } }You should instantiate in your application:
public static int amain(Args args) { MyAppl thiz = new MyAppl(args); // call with your proper prepared arguments int exitCode = thiz.exec(); // arguments can be given whatever it is necessary or possible return exitCode; }It offers an
amain(args)
which is also usable inside another Java program, with given Args,
or for example inside a JzTxtCmd script where also an exception or a error return value will be processed in a specific kind.
amain(args)
is called from:public static int smain ( String[] sArgs, Appendable logHelp, Appendable logError) { CmdArgs args = new CmdArgs(); // your inherit class of Arguments if(sArgs.length ==0) { // show help if no arguments are given. args.showHelp(logHelp); return(1); } if( ! args.parseArgs(sArgs, logError) // returns true if no argument error || ! args.testConsistence(logError) // returns true if all arguments are proper ) { return(254); // argument error } //LogMessageStream log = new LogMessageStream(System.out); int exitCode = amain(args); // internal amain with prepared Args return exitCode; }In the main you should call:
public static void main ( String[] sArgs) { try { int exitCode = smain(sArgs); System.exit(exitCode); // the exit code for the cmd line script } catch (Exception e) { // last fall back, unexpected exception System.err.println("Unexpected: " + e.getMessage()); e.printStackTrace(System.err); System.exit(255); // the exit code for unexpected for the cmd line script } }
-x:...
---comment
simple comment args with three minus
--@path/to/file
read arguments from a file, whereas one line is one argument.
--@path/to/file:label
read arguments from a part of a file after the label, see next.
java -cp classpath pkg.path.Class --@localfile.bat:myLabel ::myLabel ## ::-o:path/to/myoutput ##That is the output file for xyz ::inputfile pauseThis is an example/pattern for a batch file, which contains the arguments one per line in the argument file.
Modifier and Type | Class and Description |
---|---|
static class |
Arguments.Argument
Class to describe one argument.
|
static interface |
Arguments.SetArgument
Interface for implementation of setting arguments.
|
Modifier and Type | Field and Description |
---|---|
protected java.lang.String |
aboutInfo |
private java.util.List<Arguments.Argument[]> |
argArrays
List of all argument arrays which are not hard coded in an derivation of
testArgument(String, int) |
private java.util.List<Arguments.Argument> |
argList
List of all arguments which are not hard coded in an derivation of
testArgument(String, int) |
private java.lang.Appendable |
errMsg |
static int |
exitCodeArgError
Can be used as exit from main().
|
private static java.text.DateFormat |
formatDateHHmm |
private static java.text.DateFormat |
formatDateYYYYMMDD |
protected java.lang.String |
helpInfo |
private java.lang.Appendable |
outMsg |
private java.lang.String |
sLogLevel |
private java.lang.String |
sLogPath |
static java.lang.String |
sVersion
Version, history and license.
|
Constructor and Description |
---|
Arguments() |
Modifier and Type | Method and Description |
---|---|
java.lang.String |
aboutInfo() |
protected void |
addArg(Arguments.Argument arg)
Add one argument.
|
protected void |
addArgs(Arguments.Argument[] args)
Add all arguments given in an array.
|
protected boolean |
checkArg(java.lang.String check,
java.lang.String arg)
Checks whether an option arg is given without argument value.
|
protected java.lang.String |
checkArgVal(java.lang.String check,
java.lang.String arg)
Check whether an arg with value is given.
|
protected boolean |
errMsg(java.lang.String text,
java.lang.Object... val)
Writes an error message especially usable in the implementation of SetArguments due to the pattern:
new Argument("-dirXYZ", ":
|
static java.lang.String |
getEnv(java.lang.String nameEnv)
Operation used for environment variables in arguments, see
replaceEnv(String) . |
java.lang.String |
getLogLevel()
Should be return int
|
java.lang.String |
getLogPath() |
boolean |
parseArgs(java.lang.String[] args)
This is the user operation to process all arguments from a container as String[].
|
boolean |
parseArgs(java.lang.String[] args,
java.lang.Appendable errMsg)
This is the user operation to process all arguments from a container as String[].
|
private boolean |
parseArgs(java.lang.String[] args,
int recursive) |
void |
readArguments(java.lang.String[] cmdArgs)
Read arguments from given command line arguments.
|
static void |
readConfig(java.lang.Object data,
java.io.InputStream fIn,
java.lang.String sLeadingDesignation,
LogMessage log)
A commonly usable operation to read any configuration data,
usual given in a file given as argument file.
|
static void |
readConfig(java.lang.Object data,
java.lang.String sLine,
LogMessage log)
Read one config value from any String.
|
static java.lang.String |
replaceEnv(java.lang.String argval)
Replaces expressions "...
|
void |
showHelp(java.lang.Appendable out)
Writes all arguments with
Argument#arg Arguments.Argument.help in its order in one in a line. |
protected boolean |
testArgument(java.lang.String argc,
int nArg)
This operation tests one argument maybe from a container as String[].
|
abstract boolean |
testConsistence(java.lang.Appendable msg)
This operation should be implemented and called by the user.
|
private boolean |
tryTestArgument(java.lang.String argc,
int nArg,
java.lang.Appendable errMsg,
java.io.Closeable farg)
Wraps
testArgument(String, int) in try-catch to catch a user Exception while evaluating argument strings. |
public static final java.lang.String sVersion
tryTestArgument(String, int, Appendable, Closeable)
calls replaceEnv(...) to see the effective argument
on error message.
replaceEnv(String)
bugfix for "...$Identifier..."
readConfig(Object, InputStream, String, LogMessage)
errMsg(String, Object...)
able to call in an non static implementation of Arguments.SetArgument.setArgument(String)
,
see javadoc there.
Arguments.SetArgument.setArgument(String)
can throw now IOException
instead only FileNotFoundException
parseArgs(String[], Appendable)
is now exception free, more simple in handling.
If the helpInfo
starts with "!" then it will be written on emtpy arguments.
With that changes the usage is more simple, see example in javadoc to the class.
replaceEnv(String)
: If it starts with "/tmp/" it substitutes the TMP on windows.
readArguments(String[])
as ready to usable in main().
checkArgVal(String, String)
improved, see comments in code there. Accept spaces
testConsistence(Appendable)
instead testArgs(...), more expressive. Adaption necessary and done in all vishia Files
Arguments.Argument
can now also contain the value itself, more simple for pure String arguments.
replaceEnv(String)
with also $identifier
MainCmd
.
private static java.text.DateFormat formatDateYYYYMMDD
private static java.text.DateFormat formatDateHHmm
protected java.lang.String aboutInfo
protected java.lang.String helpInfo
private java.util.List<Arguments.Argument> argList
testArgument(String, int)
private java.util.List<Arguments.Argument[]> argArrays
testArgument(String, int)
public static int exitCodeArgError
private java.lang.String sLogPath
private java.lang.String sLogLevel
private java.lang.Appendable outMsg
private java.lang.Appendable errMsg
protected final void addArg(Arguments.Argument arg)
arg
- Should be constant initialized given in the inherited class.protected final void addArgs(Arguments.Argument[] args)
args
- Should be constant initialized given in the inherited class.public static java.lang.String replaceEnv(java.lang.String argval)
System.getProperty(String)
which can be set before Java-intern,
replaces also start with "/tmp/" for Windows, replaces "/tmp" with the PATH stored in TMP or TEMP.
argval
- String with possible environment variables to replace or starting with "/tmp/..."java.lang.IllegalArgumentException
- on faulty name of environment variablepublic static final java.lang.String getEnv(java.lang.String nameEnv)
replaceEnv(String)
.
Additional "DATE" and "TIME" is supported which returns "2025-04-03" and "17_45_33" adequate with the current time on call.nameEnv
- java.lang.IllegalArgumentException
- if the environment variable are not found.protected boolean testArgument(java.lang.String argc, int nArg) throws java.io.IOException
super.textArgument(argc, nArg);Overriding may not be recommended. Use instead
addArg(Argument)
to add simple test snippet wrapped in an instance of Arguments.Argument
.
tryTestArgument(String, int, Appendable, Closeable)
,
which is called in parseArgs(String[], Appendable)
and nothing else.
It is protected to prevent faulty calling.
argc
- The given argumentnArg
- position of the argument in the container, counted from 0argList
given on ctorjava.io.FileNotFoundException
- If the argument is formally accepted but evaluation cause an exceptionjava.io.IOException
FileNotFoundException
accepted by user implementations., 2024-05-24 with possible IOException
accepted by user implementations because it is possible
to Appendable.append(CharSequence)
a message or do anything with files etc. The Exception forces an argument error., TODO it is interesting that this operation returns null if ok and a error string as error message comes from Arguments.SetArgument.setArgument(String)
protected final boolean checkArg(java.lang.String check, java.lang.String arg)
checkArgVal(String, String)
.
The arg should be identically with checkcheck
- arg
- protected final java.lang.String checkArgVal(java.lang.String check, java.lang.String arg)
check
is the given check String.
check
- The start sequence of the argarg
- given one argument, either one line in arg file, or sequence till space in cmd linevalue
it is matching.public final boolean parseArgs(java.lang.String[] args) throws java.io.IOException
main(String[] args)
args
- The argument string array.java.io.IOException
java.lang.IllegalArgumentException
- on argument errorpublic final boolean parseArgs(java.lang.String[] args, java.lang.Appendable errMsg)
main(String[] args)
args
- The argument string array.
If the helpInfo
starts with "!" the help info is shown on empty arguments.errMsg
- if given then all arguments will be parsed. Errors will be output here.testConsistence(Appendable)
afterwards.
false argument error, the application may be used though if testConsistence(Appendable)
returns true.java.io.IOException
- only on unexpected errors writing errMsgjava.lang.IllegalArgumentException
- on argument error only if errMsg == nullprivate final boolean parseArgs(java.lang.String[] args, int recursive) throws java.io.IOException
java.io.IOException
private final boolean tryTestArgument(java.lang.String argc, int nArg, java.lang.Appendable errMsg, java.io.Closeable farg) throws java.io.IOException
testArgument(String, int)
in try-catch to catch a user Exception while evaluating argument strings.argc
- nArg
- errMsg
- if given, outputs the errorfarg
- if given, close it on error if error is not given, before an IllegalArgumentException
is thrownjava.io.IOException
- only on formally IO error on errMsgjava.lang.IllegalArgumentException
- if errMsg==null and the argument is faulty.protected boolean errMsg(java.lang.String text, java.lang.Object... val) throws java.io.IOException
new Argument("-dirXYZ", ":Any example directory should exists", new SetArgument() { (at)Override public boolean setArgument(String val) throws IOException { File dir = new File(val).getAbsoluteFile(); if(dir.exists() && dir.isDirectory()) { CmdArgs.this.dirXYZ = dir; return true; } else { return CmdArgs.this.errMsg("-dirXYZ:%s not found as directory", dir ); } }}}
text
- val
- java.io.IOException
public void showHelp(java.lang.Appendable out)
Argument#arg
Arguments.Argument.help
in its order in one in a line.out
- Any output channeljava.io.IOException
- only on unexpected problems with outpublic java.lang.String aboutInfo()
public abstract boolean testConsistence(java.lang.Appendable msg) throws java.io.IOException
#showArgs(Appendable)
to output the help info on error.msg
- to write out an info as line with \n for faulty arguments. System.err
can be used.java.io.IOException
- only on unexpected problems writing msgpublic void readArguments(java.lang.String[] cmdArgs)
parseArgs(String[], Appendable)
and testConsistence(Appendable)
cmdArgs
- public java.lang.String getLogPath()
public java.lang.String getLogLevel()
public static void readConfig(java.lang.Object data, java.io.InputStream fIn, java.lang.String sLeadingDesignation, LogMessage log) throws java.io.IOException
name=value; //commentThe name is searched as element in data, and set with the given value. It calls
readConfig(Object, String, LogMessage)
.
data
- Any data class.fIn
- opened Stream to read from, also able to get with Class.getResourceAsStream(String)
from inside a jar archive, or just as FileInputStream
sLeadingDesignation
- null, then not used, possible identifier on left side of a line as designation.
With them it is possible to use any other, for example a batch or shell script which holds values.java.io.IOException
public static void readConfig(java.lang.Object data, java.lang.String sLine, LogMessage log)
name = value; //commentThe name is searched as element in data, and set with the given value. Internally it calls
DataAccess.storeValue(Object, Object, boolean)
with the name via DataAccess.DatapathElement
data
- sLine
- log
-