Class ApplicationConfig
- Direct Known Subclasses:
OverwriteApplicationConfig,SubApplicationConfig
A finir...
- Ajout d'annotations sur les méthodes pour preciser plus de chose pour les options (pattern, min/max, alias, description, ...)
- Trouver un moyen de document les options et actions pour automatiquement generer l'aide en ligne. Pour eviter de devoir maintenir une méthode dans lequel est écrit l'aide en plus des options.
- Prise en compte du flag
useOnlyAliases - Vu qu'en java on ne peut pas pointer une méthode mais seulement une classe il y a un bout des actions qui sont des chaînes (nom de la méthode). Il faudrait faire un plugin maven qui check que l'action existe bien durant la compilation. Il est simple de le faire a l'execution mais c trop tard :(
- Ajouter de la documentation pour
getOptionAsList(String)
Bonnes pratiques
TODO A revoir en introduisant le nouveau constructeur avec ApplicationConfigInit
Vous devez créer une factory pour créer les instances d'ApplicationConfig qui contiendra par exemple une méthode :
public static ApplicationConfig getConfig(
Properties props, String configFilename, String ... args) {
ApplicationConfig conf = new ApplicationConfig(
MyAppConfigOption.class, MyAppConfigAction.class,
props, configFilename);
try {
conf.parse(args);
} catch (ArgumentsParserException eee) {
if (log.isErrorEnabled()) {
log.error("Can't load app configuration", eee);
}
}
return conf;
}
- MyAppConfigOption doit étendre
ConfigOptionDefet décrire les options de la configuration de l'application. - MyAppConfigAction doit étendre
ConfigActionDefet décrire la liste des actions et de leur alias disponible pour l'application.
Lecture des fichiers de configuration
La lecture des fichiers de configuration se fait durant l'appel de la méthode
parse(String...) en utilisant la valeur de qui doit être définit
dans les options avec pour clef CONFIG_FILE_NAME pour
trouver les fichiers (voir Les options de configuration pour l'ordre de
chargement des fichiers)
La sauvegarde
La sauvegarde des options se fait via une des trois méthodes disponibles :-
save(File, boolean, String...)sauve les données dans le fichier demandé -
saveForSystem(String...)sauvegarde les données dans /etc -
saveForUser(String...)sauvegarde les données dans $HOME
Lors de l'utilisation de la methode saveForSystem(String...) ou
saveForUser(String...) seules les options lues dans un fichier ou modifiées par
programmation (setOption(String, String) seront sauvegardées. Par exemple les
options passees sur la ligne de commande ne seront pas sauvées.
Les options de configuration
Cette classe permet de lire les fichiers de configuration, utiliser les variable d'environnement et de parser la ligne de commande. L'ordre de prise en compte des informations trouvées est le suivant (le premier le plus important) :
- options ajoutées par programmation:
setOption(String, String) - ligne de commande
- variable d'environnement de la JVM: java -Dkey=value
- variable d'environnement; export key=value
- fichier de configuration du repertoire courant: $user.dir/filename
- fichier de configuration du repertoire home de l'utilisateur: $user.home/.filename
- fichier de configuration du repertoire /etc: /etc/filename
- fichier de configuration trouve dans le classpath: $CLASSPATH/filename
- options ajoutées par programmation:
setDefaultOption(String, String)
Les options sur la ligne de commande sont de la forme:
--option key value --monOption key value1 value2
- --option key value: est la syntaxe par defaut
- --monOption key value1 value2: est la syntaxe si vous avez ajouter une
méthode setMonOption(key, value1, value2) sur votre classe de configuration
qui hérite de
ApplicationConfig. Dans ce cas vous pouvez mettre les arguments que vous souhaitez du moment qu'ils soient convertibles de la representation String vers le type que vous avez mis.
Les actions
Les actions ne peuvent etre que sur la ligne de commande. Elles sont de la forme:
--le.package.LaClass#laMethode arg1 arg2 arg3 ... argN
Une action est donc défini par le chemin complet vers la méthode qui traitera
l'action. Cette méthode peut-être une méthode static ou non. Si la méthode
n'est pas static lors de l'instanciation de l'objet on essaie de passer en
paramètre du constructeur la classe de configuration utilisée pour permettre
a l'action d'avoir a sa disposition les options de configuration. Si aucun
constructeur avec comme seul paramètre une classe héritant de
ApplicationConfig n'existe alors le constructeur par défaut est
utilise (il doit être accessible). Toutes methodes d'actions faisant
parties d'un meme objet utiliseront la meme instance de cette objet lors
de leur execution.
Si la méthode utilise les arguments variants alors tous les arguments jusqu'au prochain -- ou la fin de la ligne de commande sont utilises. Sinon Le nombre exact d'argument nécessaire a la méthode sont utilises.
Les arguments sont automatiquement converti dans le bon type réclamé par la methode.
Si l'on veut des arguments optionnels le seul moyen actuellement est d'utiliser une méthode avec des arguments variants
Les actions ne sont pas execute mais seulement parsées. Pour les exécuter
il faut utiliser la méthode doAction(int) qui prend en argument un numéro
de 'step' ou doAllAction() qui fait les actions dans l'ordre de leur step.
Par défaut toutes les actions sont de niveau 0 et sont exécutées
dans l'ordre d'apparition sur la ligne de commande. Si l'on souhaite
distinguer les actions il est possible d'utiliser l'annotation
ApplicationConfig.Action.Step sur la methode qui fera l'action en
precisant une autre valeur que 0.
doAction(0); ... do something ... doAction(1);
dans cette exemple on fait un traitement entre l'execution des actions de niveau 0 et les actions de niveau 1.
Les arguments non parsées
Tout ce qui n'est pas option ou action est considèré comme non parse et peut
etre recupere par la methode getUnparsed(). Si l'on souhaite forcer
la fin du parsing de la ligne de commande il est possible de mettre --.
Par exemple:
monProg "mon arg" --option k1 v1 -- --option k2 v2 -- autre
Dans cet exemple seule la premiere option sera considère comme une option.
On retrouvera dans unparsed: "mon arg", "--option", "k2", "v2", "--",
"autre"
Les alias
On voit qu'aussi bien pour les actions que pour les options, le nom de la
méthode doit être utilise. Pour éviter ceci il est possible de définir
des alias ce qui permet de creer des options courtes par exemple. Pour cela,
on utilise la méthode addAlias(String, String...).
addAlias("-v", "--option", "verbose", "true");
addAlias("-o", "--option", "outputfile");
addAlias("-i", "--mon.package.MaClass#MaMethode", "import");
En faite avant le parsing de la ligne de commande tous les alias trouves sont
automatiquement remplacer par leur correspondance. Il est donc possible
d'utiliser ce mécanisme pour autre chose par exemple:
addAlias("cl", "Code Lutin");
addAlias("bp", "Benjamin POUSSIN);
Dans le premier exemple on simplifie une option de flags l'option -v n'attend donc plus d'argument. Dans le second exemple on simplifie une option qui attend encore un argument de type File. Enfin dans le troisième exemple on simplifie la syntaxe d'une action et on force le premier argument de l'action a être "import".
Conversion de type
Pour la conversion de type nous utilisons common-beans. Les types supportes sont:
- les primitif (byte, short, int, long, float, double, char, boolean)
-
String -
File -
URL -
Class - Sql
Date - Sql
Time - Sql
Timestamp - les tableaux d'un type primitif ou
String. Chaque element doit etre separe par une virgule.
Pour supporter d'autre type, il vous suffit d'enregistrer de nouveau converter dans commons-beans.
Les substitutions de variable
ApplicationConfig supporte les substituions de variables de la forme
${xxx} où xxx est une autre variable de la configuration.
Exemple (dans un fichier de configuration):
firstname = John
lastname = Doe
fullname = ${firstname} ${lastname}
getOption("fullname") retournera "John Doe".- Since:
- 0.30
- Author:
- Benjamin Poussin - poussin@codelutin.com, Tony Chemit - dev@tchemit.fr
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classDefines a runtime action to be launched via theApplicationConfig.Action.doAction()method.protected static classItem used for cacheOptionstatic class -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected Map<Integer,List<ApplicationConfig.Action>> TODOstatic final StringProperty name ofadjustinginternal state.TODOstatic final StringPermet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.protected ApplicationConfigIOHelperPour gérer la lecture/écriture des properties.TODOprotected Map<String,ApplicationConfig.CacheItem<?>> TODOstatic final StringConfiguration encoding key option.static final StringConfiguration file key option.static final StringConfiguration directory where config path in located.permet de conserver des objets associe avec ce ApplicationConfigprotected booleanvrai si on est en train de parser les options de la ligne de commande.static final Stringprotected StringSystem os name.protected PropertyChangeSupportDeprecated.since 3.1, we should no more use property change support on ApplicationConfigprotected EnumMap<ApplicationConfigScope,Properties> Contient les fichiers de propriétés par scope.contient apres l'appel de parse, la liste des arguments non utilisesprotected booleanTODO -
Constructor Summary
ConstructorsConstructorDescriptionInit ApplicationConfig with current simple class name as config file.ApplicationConfig(Class<O> optionClass, Class<A> actionClass, Properties defaults, String configFilename) Deprecated.since 2.4.8, prefer useApplicationConfig(Properties, String)ApplicationConfig(String configFilename) Create configuration for a particular configuration filenameApplicationConfig(Properties defaults) Init ApplicationConfig with current simple class name as config file and use Properties parameter as defaultsApplicationConfig(Properties defaults, String configFilename) All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command lineAll in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line -
Method Summary
Modifier and TypeMethodDescriptionvoidaddAction(ApplicationConfig.Action action) Add action to list of action to do.voidaddActionAlias(String alias, String actionMethod) Add alias for action.voidAll argument in aliases as key is substitued by target.voidDeprecated.voidaddPropertyChangeListener(String propertyName, PropertyChangeListener listener) Deprecated.voidcleanUserConfig(String... excludeKeys) Clean the user configuration file (The one in user home) and save it in user config file.protected <T> ObjectconvertOption(Class<T> clazz, String key, String value, boolean asList) Convert value in instance of clazz or List if asList is trueprotected ApplicationConfig.ActioncreateAction(String name, ListIterator<String> args) Create action from string, string must be [package.][class][#][method] if package, class or method missing, default is usedvoiddoAction(int step) Do action in specified step.voidDo all action in specified order step (first 0).protected voidfirePropertyChange(String propertyName, Object oldValue, Object newValue) Return ordered action step number.Get name of file where options are read (in /etc, $HOME, $CURDIR).protected StringGet configuration file path to use.Get the encoding used to read/write resources.protected StringObtains the key used to store the option encoding.Get all options as flatPropertiesobject (replace inner options).getFlatOptions(boolean replaceInner) Get all options as flatPropertiesobject.Get all set method on this object or super object.<E> Erecupere un objet de la class<E>, s'il n'existe pas encore, il est cree (il faut donc que class<E> soit instanciable).<E> Erecupere un objet ayant le nom 'name', s'il n'existe pas encore, il est cree en utilisant la class<E>, sinon il est simplement caster vers cette classe.<T> TGet option value as typed value.get option value as string.getOption(ConfigOptionDef key) Get option value from a option definition.booleangetOptionAsBoolean(String key) Get option value asboolean.Class<?>getOptionAsClass(String key) Get option value asClass.getOptionAsColor(String key) Get option value asColor.getOptionAsDate(String key) Get option value asDate.doublegetOptionAsDouble(String key) Get option value asdouble.getOptionAsFile(String key) Get option value asFile.floatgetOptionAsFloat(String key) Get option value asfloat.intgetOptionAsInt(String key) Get option value asint.Get option value asKeyStroke.getOptionAsList(String key) Help to convert value to list of object.getOptionAsLocale(String key) Get option value asLocale.longgetOptionAsLong(String key) Get option value aslong.<E> EgetOptionAsObject(Class<E> clazz, String key) retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key' et le cast en E.getOptionAsObject(String key) retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key'.Get option value asProperties, this property must be a filepath and file must be a properties.<E> EgetOptionAsSingleton(Class<E> clazz, String key) retourne l'objet caster en 'E', instancier via la classe recupere dans la configuration via la cle 'key'.retourne l'objet instancier via la classe recupere dans la configuration via la cle 'key'.getOptionAsTime(String key) Get option value asTime.Get option value asTimestamp.getOptionAsURL(String key) Get option value asURL.org.nuiton.version.VersiongetOptionAsVersion(String key) Get option value asVersion.Get all options from configuration.getOptionStartsWith(String prefix) Permet de recuperer l'ensemble des options commencant par une certaine chaine.Get os arch (system propertyos.arch).Get os name (system propertyos.name).protected String[]getParams(Method m, ListIterator<String> args) Take required argument for method in args.getPrintableConfig(String includePattern, int padding) Return all configuration used with value, that respect includePatternprotected PropertiesDeprecated.getPropertyChangeListeners(String propertyName) Deprecated.getSubConfig(String prefix) Returns a sub config that encapsulate this ApplicationConfig.Obtain the system config file location.protected StringGet system configuration path.Return list of unparsed command line argumentGet user configuration path.Obtain the user config file location.static StringGet user home directory (system propertyuser.home).Get user name (system propertyuser.name).booleanhasListeners(String propertyName) Deprecated.booleanTeste si un option existe ou non.booleanhasOption(ConfigOptionDef key) Teste si un option existe ou nonprotected voidinit(Properties defaults, String configFilename) Deprecated.since 3.0, no more used, use nowinit(ApplicationConfigInit)protected voidinit(ApplicationConfigInit init) On sépare l'initialisation du constructeur pour pouvoir ne pas exécuter ce code sur des classes surchargeant ApplicationConfigprotected voidinstallSaveUserAction(String... properties) Install thesaveUserActionon givneproperties.booleanboolean<A extends ConfigActionDef>
voidloadActions(A[] actions) Load given actions.<A extends ConfigActionDef>
voidloadActions(Class<A> actionClass) Deprecated.since 2.4.8, prefer use nowloadActions(ConfigActionDef[])<O extends ConfigOptionDef>
voidloadDefaultOptions(Class<O> optionClass) Deprecated.since 2.4.8, prefer use nowloadDefaultOptions(ConfigOptionDef[])<O extends ConfigOptionDef>
voidloadDefaultOptions(O[] options) Load default given options.protected voidloadResource(URI uri, Properties properties) Load a resources given by hisurito the givenpropertiesargument.protected voidmigrateUserConfigurationFile(File oldHomeConfig, File homeConfig) Move old user configuration fileoldHomeConfigtohomeConfig.Parse option and call set necessary method, read jvm, env variable, Load configuration file and prepare Action.voidFor debugging.voidprintConfig(PrintStream output) Print out current configuration in specified output.protected voidputAll(Properties prop, ApplicationConfigScope scope) voidajoute un objet dans le context, la classe de l'objet est utilise comme clevoidajoute un objet dans le context, 'name' est utilise comme cleprotected voidremove(String key, ApplicationConfigScope... scopes) voidDeprecated.voidremovePropertyChangeListener(String propertyName, PropertyChangeListener listener) Deprecated.replaceRecursiveOptions(String option) Replace included ${xxx} suboptions by their values.voidSave configuration, in specified file.voidsaveForSystem(String... excludeKeys) Save configuration, in system directory (/etc/) using thegetConfigFileName().voidsaveForUser(String... excludeKeys) Save configuration, in user home directory using thegetConfigFileName().protected voidsaveResource(File file, Properties properties, String comment) Save the givenpropertiesinto the givenfilewith the givencomment.voidsetAdjusting(boolean adjusting) voidsetAppName(String appName) Use appName to add a context in config.file and config.path options.voidsetConfigFileName(String name) Set name of file where options are read (in /etc, $HOME, $CURDIR) This set usedsetDefaultOption(String, String).voidsetDefaultOption(String key, String value) Used to put default configuration option in config option.voidsetEncoding(String encoding) Set the new encoding option.voidSet option value.voidsetOptions(Properties options) Set manually options when you don't want to use parse method to check properties file configured bysetConfigFileName(String).voidsetUseOnlyAliases(boolean useOnlyAliases)
-
Field Details
-
LIST_SEPARATOR
- See Also:
-
CONFIG_FILE_NAME
Configuration file key option.- See Also:
-
CONFIG_ENCODING
Configuration encoding key option.- See Also:
-
APP_NAME
Permet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.- See Also:
-
ADJUSTING_PROPERTY
Property name ofadjustinginternal state.- Since:
- 1.3
- See Also:
-
CONFIG_PATH
Configuration directory where config path in located.Use default system configuration if nothing is defined:
- Linux : /etc/xxx.properties
- Windows : C:\\Windows\\System32\\xxx.properties
- Mac OS : /etc/
- See Also:
-
osName
System os name. (windows, linux, max os x) -
useOnlyAliases
protected boolean useOnlyAliasesTODO -
inParseOptionPhase
protected boolean inParseOptionPhasevrai si on est en train de parser les options de la ligne de commande. -
propertiesByScope
Contient les fichiers de propriétés par scope. -
cacheOption
TODO -
cacheAction
TODO -
unparsed
contient apres l'appel de parse, la liste des arguments non utilises -
aliases
TODO -
actions
TODO -
pcs
Deprecated.since 3.1, we should no more use property change support on ApplicationConfigsupport of config modification. -
context
permet de conserver des objets associe avec ce ApplicationConfig -
applicationIOHelper
Pour gérer la lecture/écriture des properties.- Since:
- 3.1
-
-
Constructor Details
-
ApplicationConfig
public ApplicationConfig()Init ApplicationConfig with current simple class name as config file.Also init converters.
- See Also:
-
ConverterUtil.initConverters()
-
ApplicationConfig
Create configuration for a particular configuration filename- Parameters:
configFilename- name of config to use
-
ApplicationConfig
Init ApplicationConfig with current simple class name as config file and use Properties parameter as defaultsAlso init converters.
- Parameters:
defaults- properties- See Also:
-
ConverterUtil.initConverters()
-
ApplicationConfig
All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line- Parameters:
defaults- properties that override default value of optionClass, can be nullconfigFilename- override default config filename, can be null- Since:
- 2.4.8
-
ApplicationConfig
All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line- Parameters:
init- configuration builder- Since:
- 3.0
-
ApplicationConfig
@Deprecated public ApplicationConfig(Class<O> optionClass, Class<A> actionClass, Properties defaults, String configFilename) Deprecated.since 2.4.8, prefer useApplicationConfig(Properties, String)All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line- Type Parameters:
O- option typeA- action type- Parameters:
optionClass- class that describe option, can be nullactionClass- class that describe action, can be nulldefaults- properties that override default value of optionClass, can be nullconfigFilename- override default config filename, can be null
-
-
Method Details
-
init
On sépare l'initialisation du constructeur pour pouvoir ne pas exécuter ce code sur des classes surchargeant ApplicationConfig- Parameters:
init- l'objet d'initialisation de l'applicationConfig
-
init
Deprecated.since 3.0, no more used, use nowinit(ApplicationConfigInit)On separt l'init du corps du constructeur, car les sous classes ne doivent pas l'executer.- Parameters:
defaults- properties that override default value of optionClass, can be nullconfigFilename- override default config filename, can be null- Since:
- 2.4.9
-
getUserHome
Get user home directory (system propertyuser.home).- Returns:
- user home directory
-
getUsername
Get user name (system propertyuser.name).- Returns:
- user name
-
getOsName
Get os name (system propertyos.name).- Returns:
- os name
- Since:
- 2.6.6
-
getOsArch
Get os arch (system propertyos.arch).- Returns:
- os arch
- Since:
- 2.6.6
-
loadDefaultOptions
Deprecated.since 2.4.8, prefer use nowloadDefaultOptions(ConfigOptionDef[])Load default options of enum pass in param (enum must extendConfigOptionDef)- Type Parameters:
O- type of enum extendConfigOptionDef- Parameters:
optionClass- to load
-
loadDefaultOptions
Load default given options.- Type Parameters:
O- type of enum extendConfigOptionDef- Parameters:
options- options to load- Since:
- 2.4.8
-
loadActions
Deprecated.since 2.4.8, prefer use nowloadActions(ConfigActionDef[])Load actions of enum pass in param (enum must extendConfigActionDef)- Type Parameters:
A- type of enum extendConfigActionDef- Parameters:
actionClass- to load
-
loadActions
Load given actions.- Type Parameters:
A- type of enum extendConfigActionDef- Parameters:
actions- actions to load- Since:
- 2.4.8
-
setDefaultOption
Used to put default configuration option in config option. Those options are used as fallback value.- Parameters:
key- default property keyvalue- default property value
-
getProperties
-
putAll
-
save
Save configuration, in specified file.- Parameters:
file- file where config will be writenforceAll- if true save all config option (with defaults, classpath, env, command line)excludeKeys- optional list of keys to exclude from- Throws:
IOException- if IO pb
-
saveForSystem
Save configuration, in system directory (/etc/) using thegetConfigFileName(). Default, env and commande line note saved.- Parameters:
excludeKeys- optional list of keys to exclude from- Throws:
ApplicationConfigSaveException
-
saveForUser
Save configuration, in user home directory using thegetConfigFileName(). Default, env and commande line note saved- Parameters:
excludeKeys- optional list of keys to exclude from- Throws:
ApplicationConfigSaveException
-
cleanUserConfig
Clean the user configuration file (The one in user home) and save it in user config file.All options with an empty value will be removed from this file.
Moreover, like
saveForUser(String...)the givenexcludeKeyswill never be saved.This method can be useful when migrating some configuration from a version to another one with deprecated options (otherwise they will stay for ever in the configuration file with an empty value which is not acceptable).
Important note: Using this method can have some strange side effects, since it could then allow to reuse default configurations from other level (default, env, jvm,...). Use with care only!
- Parameters:
excludeKeys- optional list of key to not treat in cleaning process, nor save in user user config file.- Throws:
ApplicationConfigSaveException- Since:
- 2.6.6
-
getSystemConfigFile
Obtain the system config file location.- Returns:
- the system config file location
- Throws:
ApplicationConfigFileNameNotInitializedException- if no config file name found in configuration
-
getUserConfigFile
Obtain the user config file location.- Returns:
- the user config file location
- Throws:
ApplicationConfigFileNameNotInitializedException- if no config file name found in configuration
-
getUnparsed
Return list of unparsed command line argument- Returns:
- list of unparsed arguments
-
addAction
Add action to list of action to do.- Parameters:
action- action to add, can be null.
-
getActionStep
Return ordered action step number. example: 0,1,5,6- Returns:
- ordered action step number
- Since:
- 2.4
-
doAllAction
public void doAllAction() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationExceptionDo all action in specified order step (first 0).- Throws:
IllegalAccessException- if action invocation failedIllegalArgumentException- if action invocation failedInvocationTargetException- if action invocation failedInstantiationException- if action invocation failed- Since:
- 2.4
- See Also:
-
doAction
public void doAction(int step) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException Do action in specified step.- Parameters:
step- do action only defined in this step- Throws:
IllegalAccessException- if action invocation failedIllegalArgumentException- if action invocation failedInvocationTargetException- if action invocation failedInstantiationException- if action invocation failed- See Also:
-
setUseOnlyAliases
public void setUseOnlyAliases(boolean useOnlyAliases) -
isUseOnlyAliases
public boolean isUseOnlyAliases() -
getEncoding
Get the encoding used to read/write resources.This value is stored as an option using the
getEncodingOption()key.- Returns:
- the encoding used to read/write resources.
- Since:
- 2.3
-
setEncoding
Set the new encoding option.- Parameters:
encoding- the new value of the option encoding- Since:
- 2.3
-
addAlias
All argument in aliases as key is substitued by target.- Parameters:
alias- alias string as '-v'target- substitution as '--option verbose true'
-
addActionAlias
Add alias for action. This method put just -- front the actionMethod and calladdAlias(String, String...).- Parameters:
alias- the alias to add for the given method actionactionMethod- must be fully qualified method path: package.Class#method
-
setConfigFileName
Set name of file where options are read (in /etc, $HOME, $CURDIR) This set usedsetDefaultOption(String, String).- Parameters:
name- file name
-
getConfigFileName
Get name of file where options are read (in /etc, $HOME, $CURDIR).- Returns:
- name of file
-
isAdjusting
public boolean isAdjusting() -
setAdjusting
public void setAdjusting(boolean adjusting) -
getConfigFileNameOption
-
getEncodingOption
Obtains the key used to store the option encoding.- Returns:
- the encoding option'key
- Since:
- 2.3
-
setAppName
Use appName to add a context in config.file and config.path options.Ex for an application named 'pollen' :
config.fileoption becomespollen.config.fileandconfig.pathbecomespollen.config.path- Parameters:
appName- to use as application context- Since:
- 1.2.1
-
getConfigPath
Get configuration file path to use.Use (in order) one of the following definition:
CONFIG_PATHoption- system dependant path
- Returns:
- path to use with endind
File.separator - Since:
- 1.2.1
-
getSystemConfigurationPath
Get system configuration path.Currently supported:
- Windows : C:\Windows\System32
- Unix : /etc/
- Returns:
- the system path
- Since:
- 1.2.1
-
getUserConfigDirectory
Get user configuration path.Currently supported:
- Windows : ${user.home}\\Application Data\\
- Max os x : ${user.home}/Library/Application Support
- Unix : ${user.home}/.config
Unix norm is based on freedesktop concept explained here : http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
- Returns:
- the user configuration path
- Since:
- 1.2.1
-
hasOption
Teste si un option existe ou non.- Parameters:
key- la clef de l'option à tester- Returns:
truesi l'option existe,falsesinon.
-
hasOption
Teste si un option existe ou non- Parameters:
key- la clef de l'option à tester- Returns:
truesi 'loption existe,falsesinon.
-
putObject
ajoute un objet dans le context, la classe de l'objet est utilise comme cle- Parameters:
o- l'objet à ajouter- Since:
- 2.4.2
-
putObject
ajoute un objet dans le context, 'name' est utilise comme cle- Parameters:
name- clef de l'optiono- value de l'option- Since:
- 2.4.2
-
getObject
recupere un objet de la class<E>, s'il n'existe pas encore, il est cree (il faut donc que class<E> soit instanciable).E peut prendre en argument du contruteur un objet de type ApplicationConfig
- Type Parameters:
E- le type de l'option à récupérer- Parameters:
clazz- le type de l'option à récupérer (ou créer)- Returns:
- l'objet requis
- Since:
- 2.4.2
-
getObject
recupere un objet ayant le nom 'name', s'il n'existe pas encore, il est cree en utilisant la class<E>, sinon il est simplement caster vers cette classe.E peut prendre en argument du contruteur un objet de type ApplicationConfig
- Type Parameters:
E- le type de l'option à récupérer- Parameters:
clazz- le type de l'option à récupérer (ou créer)name- le nom de l'option à récupérer (ou créer)- Returns:
- l'objet requis
- Since:
- 2.4.2
-
getOptionAsObject
retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key'. Retourne null si la cle n'est pas retrouve.- Parameters:
key- le nom de l'option à récupérer- Returns:
- l'objet requis
- Since:
- 2.4.2
-
getOptionAsObject
retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key' et le cast en E. Retourne null si la cle n'est pas retrouveE peut prendre en argument du contruteur un objet de type ApplicationConfig
- Type Parameters:
E- le type de l'option à récupérer- Parameters:
clazz- le type de l'option à récupérerkey- le nom de l'option à récupérer- Returns:
- l'objet requis
- Since:
- 2.4.2
-
getOptionAsSingleton
retourne l'objet instancier via la classe recupere dans la configuration via la cle 'key'. Une fois instancie, le meme objet est toujours retourne. On null si key n'est pas retrouve.La classe peut avoir un constructeur prenant un ApplicationConfig
- Parameters:
key- le nom de l'option à récupérer- Returns:
- l'objet requis
- Since:
- 2.4.2
-
getOptionAsSingleton
retourne l'objet caster en 'E', instancier via la classe recupere dans la configuration via la cle 'key'. Une fois instancie, le meme objet est toujours retourne. On null si key n'est pas retrouveLa classe peut avoir un constructeur prenant un ApplicationConfig
- Type Parameters:
E- le type de l'option à récupérer- Parameters:
clazz- le type de l'option à récupérerkey- le nom de l'option à récupérer- Returns:
- l'objet requis
- Since:
- 2.4.2
-
setOption
Set option value. If the value is null, then the option is removed.- Parameters:
key- property keyvalue- property value
-
getOption
get option value as string.Replace inner ${xxx} value.
- Parameters:
key- the option's key- Returns:
- String representation value
-
replaceRecursiveOptions
Replace included ${xxx} suboptions by their values.- Parameters:
option- option to replace into- Returns:
- replaced option
- Since:
- 1.1.3
-
getConfig
- Parameters:
overwrite- overwrite properties- Returns:
- new ApplicationConfig with overwrite use as value for option if found in it. Otherwise return value found in this config
-
getSubConfig
Returns a sub config that encapsulate this ApplicationConfig.- Parameters:
prefix- prefix to put automaticaly at beginning of all key- Returns:
- sub config that encapsulate this ApplicationConfig
- Since:
- 2.4.9
-
getOptionStartsWith
Permet de recuperer l'ensemble des options commencant par une certaine chaine.- Parameters:
prefix- debut de cle a recuperer- Returns:
- la liste des options filtrées
-
getOption
Get option value from a option definition.- Parameters:
key- the definition of the option- Returns:
- the value for the given option
-
getOption
Get option value as typed value.- Type Parameters:
T- type of the object wanted as return type- Parameters:
clazz- type of object wanted as return typekey- the option's key- Returns:
- typed value
-
convertOption
Convert value in instance of clazz or List if asList is trueexample:
- convertOption(Boolean.class, "toto", "true,true", false) → false
- convertOption(Boolean.class, "toto", null, false) → ? ConverterUtil dependant
- convertOption(Boolean.class, "toto", "true,true", true) → [true, true]
- convertOption(Boolean.class, "toto", null, true) → []
- Type Parameters:
T- result type expected- Parameters:
clazz- result type expectedkey- option keyvalue- value to convertasList- value is string that represente a list- Returns:
- the converted option in the required type
-
getOptionAsList
Help to convert value to list of object. If no option for this key empty List is returned finaly- Parameters:
key- the key of searched option- Returns:
- value of option list
-
getOptionAsFile
Get option value asFile.- Parameters:
key- the option's key- Returns:
- value as file
-
getOptionAsColor
Get option value asColor.- Parameters:
key- the option's key- Returns:
- value as color
-
getOptionAsProperties
Get option value asProperties, this property must be a filepath and file must be a properties.Returned Properties is
RecursiveProperties.- Parameters:
key- the option's key- Returns:
- Properties object loaded with value pointed by file
- Throws:
IOException- if exception occured on read file
-
getOptionAsURL
Get option value asURL.- Parameters:
key- the option's key- Returns:
- value as URL
-
getOptionAsClass
Get option value asClass.- Parameters:
key- the option's key- Returns:
- value as Class
-
getOptionAsDate
Get option value asDate.- Parameters:
key- the option's key- Returns:
- value as Date
-
getOptionAsTime
Get option value asTime.- Parameters:
key- the option's key- Returns:
- value as Time
-
getOptionAsTimestamp
Get option value asTimestamp.- Parameters:
key- the option's key- Returns:
- value as Timestamp
-
getOptionAsInt
Get option value asint.- Parameters:
key- the option's key- Returns:
- value as
int
-
getOptionAsLong
Get option value aslong.- Parameters:
key- the option's key- Returns:
- value as
long
-
getOptionAsFloat
Get option value asfloat.- Parameters:
key- the option's key- Returns:
- value as
float - Since:
- 2.2
-
getOptionAsDouble
Get option value asdouble.- Parameters:
key- the option's key- Returns:
- value as
double
-
getOptionAsBoolean
Get option value asboolean.- Parameters:
key- the option's key- Returns:
- value as
boolean.
-
getOptionAsLocale
Get option value asLocale.- Parameters:
key- the option's key- Returns:
- value as
Locale. - Since:
- 2.0
-
getOptionAsVersion
Get option value asVersion.- Parameters:
key- the option's key- Returns:
- value as
Version. - Since:
- 2.0
-
getOptionAsKeyStroke
Get option value asKeyStroke.- Parameters:
key- the option's key- Returns:
- value as
KeyStroke. - Since:
- 2.5.1
-
getOptions
Get all options from configuration.- Returns:
- Properties which contains all options
-
setOptions
Set manually options when you don't want to use parse method to check properties file configured bysetConfigFileName(String).- Parameters:
options- Properties which contains all options to set
-
getFlatOptions
Get all options as flatPropertiesobject (replace inner options).- Returns:
- flat Properties object
- Since:
- 1.2.2
-
getFlatOptions
Get all options as flatPropertiesobject.- Parameters:
replaceInner- iftruereplace imbricated options by theirs values- Returns:
- flat Properties object
- Since:
- 1.2.2
-
installSaveUserAction
Install thesaveUserActionon givneproperties.- Parameters:
properties- properties on which insalls the saveUserAction
-
getMethods
Get all set method on this object or super object.- Returns:
- map with method name without set and in lower case as key, and method as value
-
getParams
Take required argument for method in args. Argument used is removed from args. If method has varArgs, we take all argument to next '--'- Parameters:
m- the method to callargs- iterator with many argument (equals or more than necessary- Returns:
- the arguments found for the given method
-
createAction
protected ApplicationConfig.Action createAction(String name, ListIterator<String> args) throws ArgumentsParserException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException Create action from string, string must be [package.][class][#][method] if package, class or method missing, default is used- Parameters:
name- name of the actionargs- arguments for action invocation- Returns:
- the created action
- Throws:
ArgumentsParserException- if parsing failedIllegalAccessException- if could not create actionIllegalArgumentException- if could not create actionInstantiationException- if could not create actionInvocationTargetException- if could not create action
-
parse
Parse option and call set necessary method, read jvm, env variable, Load configuration file and prepare Action.- Parameters:
args- argument as main(String[] args)- Returns:
- ApplicationConfig instance
- Throws:
ArgumentsParserException- if parsing failed
-
migrateUserConfigurationFile
Move old user configuration fileoldHomeConfigtohomeConfig.- Parameters:
oldHomeConfig- old configuration file pathhomeConfig- new configuration file path- Throws:
IOException- if could not move configuration file
-
loadResource
Load a resources given by hisurito the givenpropertiesargument.- Parameters:
uri- the uri to loadproperties- the properties file to load- Throws:
IOException- if something occurs bad while loading resource- Since:
- 2.3
- See Also:
-
saveResource
Save the givenpropertiesinto the givenfilewith the givencomment.- Parameters:
file- the location where to store the propertiesproperties- the properties file to savecomment- the comment to add in the saved file- Throws:
IOException- if something occurs bad while saving resource- Since:
- 2.3
- See Also:
-
printConfig
public void printConfig()For debugging. -
printConfig
Print out current configuration in specified output.- Parameters:
output- output to write config to- Since:
- 1.1.4
-
getPrintableConfig
Return all configuration used with value, that respect includePattern- Parameters:
includePattern- null for all value, or config key pattern (ex: "wikitty.*")padding- for better presentation, you can use padding to align '=' sign- Returns:
- string that represent config
- Since:
- 1.5.2
-
remove
-
firePropertyChange
-
addPropertyChangeListener
Deprecated. -
addPropertyChangeListener
@Deprecated public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) Deprecated. -
removePropertyChangeListener
Deprecated. -
removePropertyChangeListener
@Deprecated public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) Deprecated. -
hasListeners
Deprecated. -
getPropertyChangeListeners
Deprecated. -
getPropertyChangeListeners
Deprecated.
-