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 générer l'aide en ligne. Pour éviter 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 à l'exécution, mais c'est 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éfinie
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 variables 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 défaut--monOption key value1 value2: est la syntaxe si vous avez ajouté une méthodesetMonOption(key, value1, value2)sur votre classe de configuration qui hérite deApplicationConfig. Dans ce cas, vous pouvez mettre les arguments que vous souhaitez du moment qu'ils sont convertibles de la représentation String vers le type que vous avez mis.
Les actions
Les actions ne peuvent être 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
à l'action d'avoir à 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
utilisé (il doit être accessible). Toutes méthodes d'actions faisant
parties d'un même objet utiliseront la même instance de cet 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 utilisés. Sinon
Le nombre exact d'arguments nécessaire a la méthode sont utilisés.
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 méthode qui fera l'action en
précisant une autre valeur que 0.
doAction(0); ... do something ... doAction(1);
Dans cet exemple, on fait un traitement entre l'exécution des actions de niveau 0 et les actions de niveau 1.
Les arguments non parsés
Tout ce qui n'est pas option ou action est considéré comme non parse et peut
être récupéré par la méthode 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 utilisée. Pour éviter ceci, il est possible de définir
des alias ce qui permet de créer des options courtes par exemple. Pour cela,
on utilise la méthode addAlias(String, String...).
En faite avant le parsing de la ligne de commande tous les alias trouvés sont automatiquement remplacés par leur correspondance. Il est donc possible d'utiliser ce mécanisme pour autre chose par exemple :addAlias("-v", "--option", "verbose", "true");addAlias("-o", "--option", "outputfile");addAlias("-i", "--mon.package.MaClass#MaMethode", "import");
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 à ê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 élément doit être séparé 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>> TODOTODOstatic 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 EnumMap<ApplicationConfigScope, Properties> Contient les fichiers de propriétés par scope.Contient après l'appel deparse(String...), la liste des arguments non utilisésprotected booleanTODO -
Constructor Summary
ConstructorsModifierConstructorDescriptionInit ApplicationConfig with current simple class name as config file.<O extends ConfigOptionDef, A extends ConfigActionDef>ApplicationConfig(Class<O> optionClass, Class<A> actionClass, Properties defaults, String configFilename) Deprecated.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 substituted by target.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.]voiddoAction(int step) Do action in specified step.voidDo all action in specified order step (first 0).Return ordered action step number. example: 0,1,5,6Get 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> ERécupère un objet de la class<E>, s'il n'existe pas encore, il est créé (il faut donc que class<E> soit instantiable).<E> ERécupère un objet ayant le nom 'name', s'il n'existe pas encore, il est créé 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 an 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 récupère 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 récupère 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 récupère dans la configuration via la cle 'key'.Retourne l'objet instancié via la classe récupère 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 récupérer l'ensemble des options commençant 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 PropertiesgetSubConfig(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's name (system propertyuser.name).booleanTeste si une option existe ou non.booleanhasOption(ConfigOptionDef key) Teste si une 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 ApplicationConfigboolean<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 utilisé comme clevoidajoute un objet dans le context, 'name' est utilise comme cleprotected voidremove(String key, ApplicationConfigScope... scopes) 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.voidsetAppName(String appName) Use appName to add a context inconfig.fileandconfig.pathoptions.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
-
CONFIG_ENCODING
-
APP_NAME
Permet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.- 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
-
unparsed
Contient après l'appel deparse(String...), la liste des arguments non utilisés -
aliases
-
actions
TODO -
context
-
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:
-
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:
-
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 <O extends ConfigOptionDef, A extends ConfigActionDef> 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 sépare l'init du corps du constructeur, car les sous classes ne doivent pas l'exécuter.- 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
-
getOsName
-
getOsArch
-
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
-
getProperties
-
putAll
-
save
Save configuration, in specified file.- Parameters:
file- file where config will be writtenforceAll- 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 forever 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's 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
-
addAction
Add action to list of action to do.- Parameters:
action- action to add, can be null.
-
getActionStep
-
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
-
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
-
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 inconfig.fileandconfig.pathoptions.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.
- Returns:
- the user configuration path
- Since:
- 1.2.1
-
hasOption
Teste si une option existe ou non.- Parameters:
key- la clef de l'option à tester- Returns:
truesi l'option existe,falsesinon.
-
hasOption
Teste si une option existe ou non- Parameters:
key- la clef de l'option à tester- Returns:
truesi l'option existe,falsesinon.
-
putObject
Ajoute un objet dans le context, la classe de l'objet est utilisé comme cle- Parameters:
o- l'objet à ajouter- Since:
- 2.4.2
-
putObject
-
getObject
Récupère un objet de la class<E>, s'il n'existe pas encore, il est créé (il faut donc que class<E> soit instantiable).E peut prendre en argument du constructeur 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
Récupère un objet ayant le nom 'name', s'il n'existe pas encore, il est créé en utilisant la class<E>, sinon il est simplement caster vers cette classe.E peut prendre en argument du constructeur 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
-
getOptionAsObject
Retourne une nouvelle instance d'un objet dont on récupère la class dans la configuration via la cle 'key' et le cast en E. Retourne null si la cle n'est pas retrouvéE peut prendre en argument du constructeur 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 instancié via la classe récupère dans la configuration via la cle 'key'. Une fois instancie, le meme objet est toujours retourné. Ou null si key n'est pas rétrouvé.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 récupère dans la configuration via la cle 'key'. Une fois instancie, le meme objet est toujours retourné. Ou null si key n'est pas retrouvéLa 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
-
getOption
-
replaceRecursiveOptions
-
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 automatically at beginning of all key- Returns:
- sub config that encapsulate this ApplicationConfig
- Since:
- 2.4.9
-
getOptionStartsWith
Permet de récupérer l'ensemble des options commençant par une certaine chaine.- Parameters:
prefix- début de clé à récupérer- Returns:
- la liste des options filtrées
-
getOption
Get option value from an option definition.- Parameters:
key- the definition of the option- Returns:
- the value for the given option
-
getOption
-
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 represents 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 finally- Parameters:
key- the key of searched option- Returns:
- value of option list
-
getOptionAsFile
-
getOptionAsColor
-
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 occurs on read file
-
getOptionAsURL
-
getOptionAsClass
-
getOptionAsDate
-
getOptionAsTime
-
getOptionAsTimestamp
-
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
-
getOptionAsVersion
Get option value asVersion.- Parameters:
key- the option's key- Returns:
- value as
Version. - Since:
- 2.0
-
getOptionAsKeyStroke
-
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
-
getMethods
-
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 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:
IllegalAccessException- 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- 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
-
ApplicationConfig(Properties, String)