Class ApplicationConfig
- Direct Known Subclasses:
OverwriteApplicationConfig,SubApplicationConfig
public class ApplicationConfig
extends java.lang.Object
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 Classes Modifier and Type Class Description static classApplicationConfig.ActionDefines a runtime action to be launched via theApplicationConfig.Action.doAction()method.protected static classApplicationConfig.CacheItem<T>Item used for cacheOptionstatic classApplicationConfig.OptionList -
Field Summary
Fields Modifier and Type Field Description protected java.util.Map<java.lang.Integer,java.util.List<ApplicationConfig.Action>>actionsTODOstatic java.lang.StringADJUSTING_PROPERTYProperty name ofadjustinginternal state.protected java.util.Map<java.lang.String,java.util.List<java.lang.String>>aliasesTODOstatic java.lang.StringAPP_NAMEPermet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.protected ApplicationConfigIOHelperapplicationIOHelperPour gérer la lecture/écriture des properties.protected java.util.Map<java.lang.Class<?>,java.lang.Object>cacheActionTODOprotected java.util.Map<java.lang.String,ApplicationConfig.CacheItem<?>>cacheOptionTODOstatic java.lang.StringCONFIG_ENCODINGConfiguration encoding key option.static java.lang.StringCONFIG_FILE_NAMEConfiguration file key option.static java.lang.StringCONFIG_PATHConfiguration directory where config path in located.protected java.util.Map<java.lang.String,java.lang.Object>contextpermet de conserver des objets associe avec ce ApplicationConfigprotected booleaninParseOptionPhasevrai si on est en train de parser les options de la ligne de commande.static java.lang.StringLIST_SEPARATORprotected java.lang.StringosNameSystem os name.protected java.beans.PropertyChangeSupportpcsDeprecated.since 3.1, we should no more use property change support on ApplicationConfigprotected java.util.EnumMap<ApplicationConfigScope,java.util.Properties>propertiesByScopeContient les fichiers de propriétés par scope.protected java.util.List<java.lang.String>unparsedcontient apres l'appel de parse, la liste des arguments non utilisesprotected booleanuseOnlyAliasesTODO -
Constructor Summary
Constructors Constructor Description ApplicationConfig()Init ApplicationConfig with current simple class name as config file.ApplicationConfig(java.lang.Class<O> optionClass, java.lang.Class<A> actionClass, java.util.Properties defaults, java.lang.String configFilename)Deprecated.since 2.4.8, prefer useApplicationConfig(Properties, String)ApplicationConfig(java.lang.String configFilename)Create configuration for a particular configuration filenameApplicationConfig(java.util.Properties defaults)Init ApplicationConfig with current simple class name as config file and use Properties parameter as defaultsApplicationConfig(java.util.Properties defaults, java.lang.String configFilename)All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command lineApplicationConfig(ApplicationConfigInit init)All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line -
Method Summary
Modifier and Type Method Description voidaddAction(ApplicationConfig.Action action)Add action to list of action to do.voidaddActionAlias(java.lang.String alias, java.lang.String actionMethod)Add alias for action.voidaddAlias(java.lang.String alias, java.lang.String... target)All argument in aliases as key is substitued by target.voidaddPropertyChangeListener(java.beans.PropertyChangeListener listener)Deprecated.voidaddPropertyChangeListener(java.lang.String propertyName, java.beans.PropertyChangeListener listener)Deprecated.voidcleanUserConfig(java.lang.String... excludeKeys)Clean the user configuration file (The one in user home) and save it in user config file.protected <T> java.lang.ObjectconvertOption(java.lang.Class<T> clazz, java.lang.String key, java.lang.String value, boolean asList)Convert value in instance of clazz or List if asList is trueprotected ApplicationConfig.ActioncreateAction(java.lang.String name, java.util.ListIterator<java.lang.String> args)Create action from string, string must be [package.]voiddoAction(int step)Do action in specified step.voiddoAllAction()Do all action in specified order step (first 0).protected voidfirePropertyChange(java.lang.String propertyName, java.lang.Object oldValue, java.lang.Object newValue)java.util.List<java.lang.Integer>getActionStep()Return ordered action step number.ApplicationConfiggetConfig(java.util.Map<java.lang.String,java.lang.String> overwrite)java.lang.StringgetConfigFileName()Get name of file where options are read (in /etc, $HOME, $CURDIR).protected java.lang.StringgetConfigFileNameOption()java.lang.StringgetConfigPath()Get configuration file path to use.java.lang.StringgetEncoding()Get the encoding used to read/write resources.protected java.lang.StringgetEncodingOption()Obtains the key used to store the option encoding.java.util.PropertiesgetFlatOptions()Get all options as flatPropertiesobject (replace inner options).java.util.PropertiesgetFlatOptions(boolean replaceInner)Get all options as flatPropertiesobject.protected java.util.Map<java.lang.String,java.lang.reflect.Method>getMethods()Get all set method on this object or super object.<E> EgetObject(java.lang.Class<E> clazz)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> EgetObject(java.lang.Class<E> clazz, java.lang.String name)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.<T> TgetOption(java.lang.Class<T> clazz, java.lang.String key)Get option value as typed value.java.lang.StringgetOption(java.lang.String key)get option value as string.java.lang.ObjectgetOption(ConfigOptionDef key)Get option value from a option definition.booleangetOptionAsBoolean(java.lang.String key)Get option value asboolean.java.lang.Class<?>getOptionAsClass(java.lang.String key)Get option value asClass.java.awt.ColorgetOptionAsColor(java.lang.String key)Get option value asColor.java.util.DategetOptionAsDate(java.lang.String key)Get option value asDate.doublegetOptionAsDouble(java.lang.String key)Get option value asdouble.java.io.FilegetOptionAsFile(java.lang.String key)Get option value asFile.floatgetOptionAsFloat(java.lang.String key)Get option value asfloat.intgetOptionAsInt(java.lang.String key)Get option value asint.javax.swing.KeyStrokegetOptionAsKeyStroke(java.lang.String key)Get option value asKeyStroke.ApplicationConfig.OptionListgetOptionAsList(java.lang.String key)Help to convert value to list of object.java.util.LocalegetOptionAsLocale(java.lang.String key)Get option value asLocale.longgetOptionAsLong(java.lang.String key)Get option value aslong.<E> EgetOptionAsObject(java.lang.Class<E> clazz, java.lang.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.java.lang.ObjectgetOptionAsObject(java.lang.String key)retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key'.java.util.PropertiesgetOptionAsProperties(java.lang.String key)Get option value asProperties, this property must be a filepath and file must be a properties.<E> EgetOptionAsSingleton(java.lang.Class<E> clazz, java.lang.String key)retourne l'objet caster en 'E', instancier via la classe recupere dans la configuration via la cle 'key'.java.lang.ObjectgetOptionAsSingleton(java.lang.String key)retourne l'objet instancier via la classe recupere dans la configuration via la cle 'key'.java.sql.TimegetOptionAsTime(java.lang.String key)Get option value asTime.java.sql.TimestampgetOptionAsTimestamp(java.lang.String key)Get option value asTimestamp.java.net.URLgetOptionAsURL(java.lang.String key)Get option value asURL.org.nuiton.version.VersiongetOptionAsVersion(java.lang.String key)Get option value asVersion.java.util.PropertiesgetOptions()Get all options from configuration.java.util.PropertiesgetOptionStartsWith(java.lang.String prefix)Permet de recuperer l'ensemble des options commencant par une certaine chaine.java.lang.StringgetOsArch()Get os arch (system propertyos.arch).java.lang.StringgetOsName()Get os name (system propertyos.name).protected java.lang.String[]getParams(java.lang.reflect.Method m, java.util.ListIterator<java.lang.String> args)Take required argument for method in args.java.lang.StringgetPrintableConfig(java.lang.String includePattern, int padding)Return all configuration used with value, that respect includePatternprotected java.util.PropertiesgetProperties(ApplicationConfigScope scope)java.beans.PropertyChangeListener[]getPropertyChangeListeners()Deprecated.java.beans.PropertyChangeListener[]getPropertyChangeListeners(java.lang.String propertyName)Deprecated.SubApplicationConfiggetSubConfig(java.lang.String prefix)Returns a sub config that encapsulate this ApplicationConfig.java.io.FilegetSystemConfigFile()Obtain the system config file location.protected java.lang.StringgetSystemConfigurationPath()Get system configuration path.java.util.List<java.lang.String>getUnparsed()Return list of unparsed command line argumentjava.lang.StringgetUserConfigDirectory()Get user configuration path.java.io.FilegetUserConfigFile()Obtain the user config file location.static java.lang.StringgetUserHome()Get user home directory (system propertyuser.home).java.lang.StringgetUsername()Get user name (system propertyuser.name).booleanhasListeners(java.lang.String propertyName)Deprecated.booleanhasOption(java.lang.String key)Teste si un option existe ou non.booleanhasOption(ConfigOptionDef key)Teste si un option existe ou nonprotected voidinit(java.util.Properties defaults, java.lang.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(java.lang.String... properties)Install thesaveUserActionon givneproperties.booleanisAdjusting()booleanisUseOnlyAliases()<A extends ConfigActionDef>
voidloadActions(A[] actions)Load given actions.<A extends ConfigActionDef>
voidloadActions(java.lang.Class<A> actionClass)Deprecated.since 2.4.8, prefer use nowloadActions(ConfigActionDef[])<O extends ConfigOptionDef>
voidloadDefaultOptions(java.lang.Class<O> optionClass)Deprecated.since 2.4.8, prefer use nowloadDefaultOptions(ConfigOptionDef[])<O extends ConfigOptionDef>
voidloadDefaultOptions(O[] options)Load default given options.protected voidloadResource(java.net.URI uri, java.util.Properties properties)Load a resources given by hisurito the givenpropertiesargument.protected voidmigrateUserConfigurationFile(java.io.File oldHomeConfig, java.io.File homeConfig)Move old user configuration fileoldHomeConfigtohomeConfig.ApplicationConfigparse(java.lang.String... args)Parse option and call set necessary method, read jvm, env variable, Load configuration file and prepare Action.voidprintConfig()For debugging.voidprintConfig(java.io.PrintStream output)Print out current configuration in specified output.protected voidputAll(java.util.Properties prop, ApplicationConfigScope scope)voidputObject(java.lang.Object o)ajoute un objet dans le context, la classe de l'objet est utilise comme clevoidputObject(java.lang.String name, java.lang.Object o)ajoute un objet dans le context, 'name' est utilise comme cleprotected voidremove(java.lang.String key, ApplicationConfigScope... scopes)voidremovePropertyChangeListener(java.beans.PropertyChangeListener listener)Deprecated.voidremovePropertyChangeListener(java.lang.String propertyName, java.beans.PropertyChangeListener listener)Deprecated.java.lang.StringreplaceRecursiveOptions(java.lang.String option)Replace included ${xxx} suboptions by their values.voidsave(java.io.File file, boolean forceAll, java.lang.String... excludeKeys)Save configuration, in specified file.voidsaveForSystem(java.lang.String... excludeKeys)Save configuration, in system directory (/etc/) using thegetConfigFileName().voidsaveForUser(java.lang.String... excludeKeys)Save configuration, in user home directory using thegetConfigFileName().protected voidsaveResource(java.io.File file, java.util.Properties properties, java.lang.String comment)Save the givenpropertiesinto the givenfilewith the givencomment.voidsetAdjusting(boolean adjusting)voidsetAppName(java.lang.String appName)Use appName to add a context in config.file and config.path options.voidsetConfigFileName(java.lang.String name)Set name of file where options are read (in /etc, $HOME, $CURDIR) This set usedsetDefaultOption(String, String).voidsetDefaultOption(java.lang.String key, java.lang.String value)Used to put default configuration option in config option.voidsetEncoding(java.lang.String encoding)Set the new encoding option.voidsetOption(java.lang.String key, java.lang.String value)Set option value.voidsetOptions(java.util.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
public static final java.lang.String LIST_SEPARATOR- See Also:
- Constant Field Values
-
CONFIG_FILE_NAME
public static final java.lang.String CONFIG_FILE_NAMEConfiguration file key option.- See Also:
- Constant Field Values
-
CONFIG_ENCODING
public static final java.lang.String CONFIG_ENCODINGConfiguration encoding key option.- See Also:
- Constant Field Values
-
APP_NAME
public static final java.lang.String APP_NAMEPermet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.- See Also:
- Constant Field Values
-
ADJUSTING_PROPERTY
public static final java.lang.String ADJUSTING_PROPERTYProperty name ofadjustinginternal state.- Since:
- 1.3
- See Also:
- Constant Field Values
-
CONFIG_PATH
public static final java.lang.String CONFIG_PATHConfiguration 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:
- Constant Field Values
-
osName
protected java.lang.String osNameSystem 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
protected java.util.Map<java.lang.Class<?>,java.lang.Object> cacheActionTODO -
unparsed
protected java.util.List<java.lang.String> unparsedcontient apres l'appel de parse, la liste des arguments non utilises -
aliases
protected java.util.Map<java.lang.String,java.util.List<java.lang.String>> aliasesTODO -
actions
TODO -
pcs
@Deprecated protected java.beans.PropertyChangeSupport pcsDeprecated.since 3.1, we should no more use property change support on ApplicationConfigsupport of config modification. -
context
protected java.util.Map<java.lang.String,java.lang.Object> contextpermet 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
public ApplicationConfig(java.lang.String configFilename)Create configuration for a particular configuration filename- Parameters:
configFilename- name of config to use
-
ApplicationConfig
public ApplicationConfig(java.util.Properties defaults)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
public ApplicationConfig(java.util.Properties defaults, java.lang.String configFilename)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(java.lang.Class<O> optionClass, java.lang.Class<A> actionClass, java.util.Properties defaults, java.lang.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 protected void init(java.util.Properties defaults, java.lang.String configFilename)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
public static java.lang.String getUserHome()Get user home directory (system propertyuser.home).- Returns:
- user home directory
-
getUsername
public java.lang.String getUsername()Get user name (system propertyuser.name).- Returns:
- user name
-
getOsName
public java.lang.String getOsName()Get os name (system propertyos.name).- Returns:
- os name
- Since:
- 2.6.6
-
getOsArch
public java.lang.String getOsArch()Get os arch (system propertyos.arch).- Returns:
- os arch
- Since:
- 2.6.6
-
loadDefaultOptions
@Deprecated public <O extends ConfigOptionDef> void loadDefaultOptions(java.lang.Class<O> optionClass)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
public void setDefaultOption(java.lang.String key, java.lang.String value)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
public void save(java.io.File file, boolean forceAll, java.lang.String... excludeKeys) throws java.io.IOExceptionSave 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:
java.io.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
public java.util.List<java.lang.String> 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
public java.util.List<java.lang.Integer> getActionStep()Return ordered action step number. example: 0,1,5,6- Returns:
- ordered action step number
- Since:
- 2.4
-
doAllAction
public void doAllAction() throws java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.reflect.InvocationTargetException, java.lang.InstantiationExceptionDo all action in specified order step (first 0).- Throws:
java.lang.IllegalAccessException- if action invocation failedjava.lang.IllegalArgumentException- if action invocation failedjava.lang.reflect.InvocationTargetException- if action invocation failedjava.lang.InstantiationException- if action invocation failed- Since:
- 2.4
- See Also:
ApplicationConfig.Action.Step
-
doAction
public void doAction(int step) throws java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.reflect.InvocationTargetException, java.lang.InstantiationExceptionDo action in specified step.- Parameters:
step- do action only defined in this step- Throws:
java.lang.IllegalAccessException- if action invocation failedjava.lang.IllegalArgumentException- if action invocation failedjava.lang.reflect.InvocationTargetException- if action invocation failedjava.lang.InstantiationException- if action invocation failed- See Also:
ApplicationConfig.Action.Step
-
setUseOnlyAliases
public void setUseOnlyAliases(boolean useOnlyAliases) -
isUseOnlyAliases
public boolean isUseOnlyAliases() -
getEncoding
public java.lang.String 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
public void setEncoding(java.lang.String encoding)Set the new encoding option.- Parameters:
encoding- the new value of the option encoding- Since:
- 2.3
-
addAlias
public void addAlias(java.lang.String alias, java.lang.String... target)All argument in aliases as key is substitued by target.- Parameters:
alias- alias string as '-v'target- substitution as '--option verbose true'
-
addActionAlias
public void addActionAlias(java.lang.String alias, java.lang.String actionMethod)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
public void setConfigFileName(java.lang.String name)Set name of file where options are read (in /etc, $HOME, $CURDIR) This set usedsetDefaultOption(String, String).- Parameters:
name- file name
-
getConfigFileName
public java.lang.String 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
protected java.lang.String getConfigFileNameOption() -
getEncodingOption
protected java.lang.String getEncodingOption()Obtains the key used to store the option encoding.- Returns:
- the encoding option'key
- Since:
- 2.3
-
setAppName
public void setAppName(java.lang.String appName)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
public java.lang.String 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
protected java.lang.String getSystemConfigurationPath()Get system configuration path.Currently supported:
- Windows : C:\Windows\System32
- Unix : /etc/
- Returns:
- the system path
- Since:
- 1.2.1
-
getUserConfigDirectory
public java.lang.String 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
public boolean hasOption(java.lang.String key)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
public void putObject(java.lang.Object o)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
public void putObject(java.lang.String name, java.lang.Object o)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
public <E> E getObject(java.lang.Class<E> clazz)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
public <E> E getObject(java.lang.Class<E> clazz, java.lang.String name)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
public java.lang.Object getOptionAsObject(java.lang.String key)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
public <E> E getOptionAsObject(java.lang.Class<E> clazz, java.lang.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. 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
public java.lang.Object getOptionAsSingleton(java.lang.String key)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
public <E> E getOptionAsSingleton(java.lang.Class<E> clazz, java.lang.String key)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
public void setOption(java.lang.String key, java.lang.String value)Set option value. If the value is null, then the option is removed.- Parameters:
key- property keyvalue- property value
-
getOption
public java.lang.String getOption(java.lang.String key)get option value as string.Replace inner ${xxx} value.
- Parameters:
key- the option's key- Returns:
- String representation value
-
replaceRecursiveOptions
public java.lang.String replaceRecursiveOptions(java.lang.String option)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
public java.util.Properties getOptionStartsWith(java.lang.String prefix)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
public <T> T getOption(java.lang.Class<T> clazz, java.lang.String key)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
protected <T> java.lang.Object convertOption(java.lang.Class<T> clazz, java.lang.String key, java.lang.String value, boolean asList)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
public java.io.File getOptionAsFile(java.lang.String key)Get option value asFile.- Parameters:
key- the option's key- Returns:
- value as file
-
getOptionAsColor
public java.awt.Color getOptionAsColor(java.lang.String key)Get option value asColor.- Parameters:
key- the option's key- Returns:
- value as color
-
getOptionAsProperties
public java.util.Properties getOptionAsProperties(java.lang.String key) throws java.io.IOExceptionGet 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:
java.io.IOException- if exception occured on read file
-
getOptionAsURL
public java.net.URL getOptionAsURL(java.lang.String key)Get option value asURL.- Parameters:
key- the option's key- Returns:
- value as URL
-
getOptionAsClass
public java.lang.Class<?> getOptionAsClass(java.lang.String key)Get option value asClass.- Parameters:
key- the option's key- Returns:
- value as Class
-
getOptionAsDate
public java.util.Date getOptionAsDate(java.lang.String key)Get option value asDate.- Parameters:
key- the option's key- Returns:
- value as Date
-
getOptionAsTime
public java.sql.Time getOptionAsTime(java.lang.String key)Get option value asTime.- Parameters:
key- the option's key- Returns:
- value as Time
-
getOptionAsTimestamp
public java.sql.Timestamp getOptionAsTimestamp(java.lang.String key)Get option value asTimestamp.- Parameters:
key- the option's key- Returns:
- value as Timestamp
-
getOptionAsInt
public int getOptionAsInt(java.lang.String key)Get option value asint.- Parameters:
key- the option's key- Returns:
- value as
int
-
getOptionAsLong
public long getOptionAsLong(java.lang.String key)Get option value aslong.- Parameters:
key- the option's key- Returns:
- value as
long
-
getOptionAsFloat
public float getOptionAsFloat(java.lang.String key)Get option value asfloat.- Parameters:
key- the option's key- Returns:
- value as
float - Since:
- 2.2
-
getOptionAsDouble
public double getOptionAsDouble(java.lang.String key)Get option value asdouble.- Parameters:
key- the option's key- Returns:
- value as
double
-
getOptionAsBoolean
public boolean getOptionAsBoolean(java.lang.String key)Get option value asboolean.- Parameters:
key- the option's key- Returns:
- value as
boolean.
-
getOptionAsLocale
public java.util.Locale getOptionAsLocale(java.lang.String key)Get option value asLocale.- Parameters:
key- the option's key- Returns:
- value as
Locale. - Since:
- 2.0
-
getOptionAsVersion
public org.nuiton.version.Version getOptionAsVersion(java.lang.String key)Get option value asVersion.- Parameters:
key- the option's key- Returns:
- value as
Version. - Since:
- 2.0
-
getOptionAsKeyStroke
public javax.swing.KeyStroke getOptionAsKeyStroke(java.lang.String key)Get option value asKeyStroke.- Parameters:
key- the option's key- Returns:
- value as
KeyStroke. - Since:
- 2.5.1
-
getOptions
public java.util.Properties getOptions()Get all options from configuration.- Returns:
- Properties which contains all options
-
setOptions
public void setOptions(java.util.Properties options)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
public java.util.Properties getFlatOptions()Get all options as flatPropertiesobject (replace inner options).- Returns:
- flat Properties object
- Since:
- 1.2.2
-
getFlatOptions
public java.util.Properties getFlatOptions(boolean replaceInner)Get all options as flatPropertiesobject.- Parameters:
replaceInner- iftruereplace imbricated options by theirs values- Returns:
- flat Properties object
- Since:
- 1.2.2
-
installSaveUserAction
protected void installSaveUserAction(java.lang.String... properties)Install thesaveUserActionon givneproperties.- Parameters:
properties- properties on which insalls the saveUserAction
-
getMethods
protected java.util.Map<java.lang.String,java.lang.reflect.Method> 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
protected java.lang.String[] getParams(java.lang.reflect.Method m, java.util.ListIterator<java.lang.String> args)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(java.lang.String name, java.util.ListIterator<java.lang.String> args) throws ArgumentsParserException, java.lang.InstantiationException, java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.reflect.InvocationTargetExceptionCreate 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 failedjava.lang.IllegalAccessException- if could not create actionjava.lang.IllegalArgumentException- if could not create actionjava.lang.InstantiationException- if could not create actionjava.lang.reflect.InvocationTargetException- 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
protected void migrateUserConfigurationFile(java.io.File oldHomeConfig, java.io.File homeConfig) throws java.io.IOExceptionMove old user configuration fileoldHomeConfigtohomeConfig.- Parameters:
oldHomeConfig- old configuration file pathhomeConfig- new configuration file path- Throws:
java.io.IOException- if could not move configuration file
-
loadResource
protected void loadResource(java.net.URI uri, java.util.Properties properties) throws java.io.IOExceptionLoad a resources given by hisurito the givenpropertiesargument.- Parameters:
uri- the uri to loadproperties- the properties file to load- Throws:
java.io.IOException- if something occurs bad while loading resource- Since:
- 2.3
- See Also:
Properties.load(Reader)
-
saveResource
protected void saveResource(java.io.File file, java.util.Properties properties, java.lang.String comment) throws java.io.IOExceptionSave 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:
java.io.IOException- if something occurs bad while saving resource- Since:
- 2.3
- See Also:
Properties.store(Writer, String)
-
printConfig
public void printConfig()For debugging. -
printConfig
public void printConfig(java.io.PrintStream output)Print out current configuration in specified output.- Parameters:
output- output to write config to- Since:
- 1.1.4
-
getPrintableConfig
public java.lang.String getPrintableConfig(java.lang.String includePattern, int padding)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
protected void firePropertyChange(java.lang.String propertyName, java.lang.Object oldValue, java.lang.Object newValue) -
addPropertyChangeListener
@Deprecated public void addPropertyChangeListener(java.beans.PropertyChangeListener listener)Deprecated. -
addPropertyChangeListener
@Deprecated public void addPropertyChangeListener(java.lang.String propertyName, java.beans.PropertyChangeListener listener)Deprecated. -
removePropertyChangeListener
@Deprecated public void removePropertyChangeListener(java.beans.PropertyChangeListener listener)Deprecated. -
removePropertyChangeListener
@Deprecated public void removePropertyChangeListener(java.lang.String propertyName, java.beans.PropertyChangeListener listener)Deprecated. -
hasListeners
@Deprecated public boolean hasListeners(java.lang.String propertyName)Deprecated. -
getPropertyChangeListeners
@Deprecated public java.beans.PropertyChangeListener[] getPropertyChangeListeners(java.lang.String propertyName)Deprecated. -
getPropertyChangeListeners
@Deprecated public java.beans.PropertyChangeListener[] getPropertyChangeListeners()Deprecated.
-