Class ApplicationConfig
- java.lang.Object
-
- io.ultreia.java4all.config.ApplicationConfig
-
- Direct Known Subclasses:
OverwriteApplicationConfig,SubApplicationConfig
public class ApplicationConfig extends Object
Application configuration.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'
ApplicationConfigqui 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 clefCONFIG_FILE_NAMEpour 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...)ousaveForUser(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
ApplicationConfign'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' oudoAllAction()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'annotationApplicationConfig.Action.Stepsur 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
ApplicationConfigsupporte les substituions de variables de la forme ${xxx} oùxxxest 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 Map<Integer,List<ApplicationConfig.Action>>actionsTODOprotected Map<String,List<String>>aliasesTODOstatic StringAPP_NAMEPermet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.protected Map<Class<?>,Object>cacheActionTODOprotected Map<String,ApplicationConfig.CacheItem<?>>cacheOptionTODOstatic StringCLASS_METHOD_SEPARATORUsed to know what is separator between class and methodstatic StringCONFIG_ENCODINGConfiguration encoding key option.static StringCONFIG_FILE_NAMEConfiguration file key option.static StringCONFIG_PATHConfiguration directory where config path in located.protected RuntimeStorageconfigStorageTo read/write config.protected Map<String,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 StringLIST_SEPARATORprotected StringosNameSystem os name.protected EnumMap<ApplicationConfigScope,Properties>propertiesByScopeContient les fichiers de propriétés par scope.protected List<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(ApplicationConfigInit init)All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command lineApplicationConfig(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 line
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddAction(ApplicationConfig.Action action)Add action to list of action to do.voidaddActionAlias(String alias, String actionMethod)Add alias for action.voidaddAlias(String alias, String... target)All argument in aliases as key is substitued by target.static Objectcall(Object o, Method m, String... params)Call method m with params as String.protected static ObjectchoiceArgument(Class<?> clazz, List args, boolean nullIfMissing)Permet de matcher un type d'argument attendu clazz parmi un ensemble possible de candidat.voidcleanUserConfig(String... excludeKeys)Clean the user configuration file (The one in user home) and save it in user config file.protected static Objectconvert(String v, Class<?> clazz)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.voiddoAllAction()Do all action in specified order step (first 0).List<Integer>getActionStep()Return ordered action step number.CharsetgetCharset()ApplicationConfiggetConfig(Map<String,String> overwrite)StringgetConfigFileName()Get name of file where options are read (in /etc, $HOME, $CURDIR).protected StringgetConfigFileNameOption()StringgetConfigPath()Get configuration file path to use.FilegetCurrentConfigFile()Obtain the current directory config file location.StringgetEncoding()Get the encoding used to read/write resources.protected StringgetEncodingOption()Obtains the key used to store the option encoding.PropertiesgetFlatOptions()Get all options as flatPropertiesobject (replace inner options).PropertiesgetFlatOptions(boolean replaceInner)Get all options as flatPropertiesobject.static List<Method>getMethod(Class<?> clazz, String methodName, boolean ignoreCase)Get all methods with name given in argument without check parameters.static List<Method>getMethod(String name, boolean ignoreCase)List method that match name, name must be [package.]protected Map<String,Method>getMethods()Get all set method on this object or super object.<E> EgetObject(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(Class<E> clazz, 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.ObjectgetOption(ConfigOptionDef key)Get option value from a option definition.<T> TgetOption(Class<T> clazz, String key)Get option value as typed value.StringgetOption(String key)get option value as string.booleangetOptionAsBoolean(String key)Get option value asboolean.Class<?>getOptionAsClass(String key)Get option value asClass.ColorgetOptionAsColor(String key)Get option value asColor.DategetOptionAsDate(String key)Get option value asDate.doublegetOptionAsDouble(String key)Get option value asdouble.FilegetOptionAsFile(String key)Get option value asFile.floatgetOptionAsFloat(String key)Get option value asfloat.intgetOptionAsInt(String key)Get option value asint.KeyStrokegetOptionAsKeyStroke(String key)Get option value asKeyStroke.ApplicationConfig.OptionListgetOptionAsList(String key)Help to convert value to list of object.LocalegetOptionAsLocale(String key)Get option value asLocale.longgetOptionAsLong(String key)Get option value aslong.<E> EgetOptionAsObject(Class<E> clazz, String key)Deprecated.usegetOption(Class, String)instead.ObjectgetOptionAsObject(String key)Deprecated.usegetOption(Class, String)instead.PropertiesgetOptionAsProperties(String 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'.ObjectgetOptionAsSingleton(String key)retourne l'objet instancier via la classe recupere dans la configuration via la cle 'key'.TimegetOptionAsTime(String key)Get option value asTime.TimestampgetOptionAsTimestamp(String key)Get option value asTimestamp.URLgetOptionAsURL(String key)Get option value asURL.io.ultreia.java4all.util.VersiongetOptionAsVersion(String key)Get option value asVersion.PropertiesgetOptions()Get all options from configuration.PropertiesgetOptionStartsWith(String prefix)Permet de recuperer l'ensemble des options commencant par une certaine chaine.StringgetOsArch()Get os arch (system propertyos.arch).StringgetOsName()Get os name (system propertyos.name).protected String[]getParams(Method m, ListIterator<String> args)Take required argument for method in args.StringgetPrintableConfig(String includePattern, int padding)Return all configuration used with value, that respect includePatternprotected PropertiesgetProperties(ApplicationConfigScope scope)SubApplicationConfiggetSubConfig(String prefix)Returns a sub config that encapsulate this ApplicationConfig.FilegetSystemConfigFile()Obtain the system config file location.protected StringgetSystemConfigurationPath()Get system configuration path.List<String>getUnparsed()Return list of unparsed command line argumentStringgetUserConfigDirectory()Get user configuration path.FilegetUserConfigFile()Obtain the user config file location.static StringgetUserHome()Get user home directory (system propertyuser.home).StringgetUsername()Get user name (system propertyuser.name).booleanhasOption(ConfigOptionDef key)Teste si un option existe ou nonbooleanhasOption(String key)Teste si un option existe ou non.protected voidinit(ApplicationConfigInit init)On sépare l'initialisation du constructeur pour pouvoir ne pas exécuter ce code sur des classes surchargeant ApplicationConfigbooleanisUseOnlyAliases()<A extends ConfigActionDef>
voidloadActions(A[] actions)Load given actions.<O extends ConfigOptionDef>
voidloadDefaultOptions(O... options)Load default given options.protected voidloadResource(URI uri, Properties properties)Load a resources given by hisurito the givenpropertiesargument.static <E> EnewInstance(Class<E> clazz, Collection<?> args, boolean nullIfMissing)Invoke constructor on clazz to create new instance.ApplicationConfigparse(String... args)Parse option and call set necessary method, read jvm, env variable, Load configuration file and prepare Action.voidprintConfig()For debugging.voidprintConfig(PrintStream output)Print out current configuration in specified output.protected voidputAll(Properties prop, ApplicationConfigScope scope)voidputObject(Object o)ajoute un objet dans le context, la classe de l'objet est utilise comme clevoidputObject(String name, Object o)ajoute un objet dans le context, 'name' est utilise comme cleprotected voidremove(String key, ApplicationConfigScope... scopes)StringreplaceRecursiveOptions(String option)Replace included ${xxx} suboptions by their values.voidsave(File file, boolean forceAll, String... excludeKeys)Save configuration, in specified file.voidsaveForCurrent(String... excludeKeys)Save configuration, in current directory using thegetConfigFileName().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 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.voidsetOption(String key, String value)Set 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 Detail
-
LIST_SEPARATOR
public static final String LIST_SEPARATOR
- See Also:
- Constant Field Values
-
CONFIG_FILE_NAME
public static final String CONFIG_FILE_NAME
Configuration file key option.- See Also:
- Constant Field Values
-
CONFIG_ENCODING
public static final String CONFIG_ENCODING
Configuration encoding key option.- See Also:
- Constant Field Values
-
APP_NAME
public static final String APP_NAME
Permet d'associer un nom de contexte pour prefixer les optionsCONFIG_PATHetCONFIG_FILE_NAME.- See Also:
- Constant Field Values
-
CONFIG_PATH
public static final String 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:
- Constant Field Values
-
CLASS_METHOD_SEPARATOR
public static final String CLASS_METHOD_SEPARATOR
Used to know what is separator between class and method- See Also:
- Constant Field Values
-
osName
protected String osName
System os name. (windows, linux, max os x)
-
useOnlyAliases
protected boolean useOnlyAliases
TODO
-
inParseOptionPhase
protected boolean inParseOptionPhase
vrai si on est en train de parser les options de la ligne de commande.
-
propertiesByScope
protected EnumMap<ApplicationConfigScope,Properties> propertiesByScope
Contient les fichiers de propriétés par scope.
-
cacheOption
protected Map<String,ApplicationConfig.CacheItem<?>> cacheOption
TODO
-
unparsed
protected List<String> unparsed
contient apres l'appel de parse, la liste des arguments non utilises
-
actions
protected Map<Integer,List<ApplicationConfig.Action>> actions
TODO
-
context
protected Map<String,Object> context
permet de conserver des objets associe avec ce ApplicationConfig
-
configStorage
protected RuntimeStorage configStorage
To read/write config.
-
-
Constructor Detail
-
ApplicationConfig
public ApplicationConfig()
Init ApplicationConfig with current simple class name as config file.Also init converters.
- See Also:
ConverterUtil.initConverters()
-
ApplicationConfig
public ApplicationConfig(String configFilename)
Create configuration for a particular configuration filename- Parameters:
configFilename- name of config to use
-
ApplicationConfig
public ApplicationConfig(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(Properties defaults, 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
public ApplicationConfig(ApplicationConfigInit init)
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
-
-
Method Detail
-
getUserHome
public static String getUserHome()
Get user home directory (system propertyuser.home).- Returns:
- user home directory
-
newInstance
public static <E> E newInstance(Class<E> clazz, Collection<?> args, boolean nullIfMissing)
Invoke constructor on clazz to create new instance. Try to find argument for constructor in args parameter.- Type Parameters:
E- FIXME- Parameters:
clazz- class of object to instanciateargs- all possible parameter that constructor can usednullIfMissing- if no suitable class or object found in args, use null value (no exception)- Returns:
- new instance
- Throws:
IllegalArgumentException- if something is wrong during instanciation
-
choiceArgument
protected static Object choiceArgument(Class<?> clazz, List args, boolean nullIfMissing)
Permet de matcher un type d'argument attendu clazz parmi un ensemble possible de candidat. Les candidats peuvent etre des classes qu'il faudra instancier pour satisfaire le type demande.- Parameters:
clazz- le type recherchéargs- la liste des arguments ou des typesnullIfMissing- pour retourner nulle si l'argument n'est pas trouvé- Returns:
- le type d'argument trouvé
-
getMethod
public static List<Method> getMethod(Class<?> clazz, String methodName, boolean ignoreCase)
Get all methods with name given in argument without check parameters.- Parameters:
clazz- where to search methodmethodName- method name to searchignoreCase- if true, ignore difference in method name case- Returns:
- list of detected methods
-
getMethod
public static List<Method> getMethod(String name, boolean ignoreCase)
List method that match name, name must be [package.][class][#][method] if package, class or method missing, exception throw- Parameters:
name- name of the methodignoreCase- check exact method name if false- Returns:
- list of method that match name
- Since:
- 2.6.9
-
call
public static Object call(Object o, Method m, String... params) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException
Call method m with params as String. Each param is converted to required type for method with beanutils converter- Parameters:
o- object where method must be callm- method to callparams- parameters for method call- Returns:
- returned method's value
- Throws:
IllegalAccessException- FIXMEIllegalArgumentException- FIXMEInvocationTargetException- FIXMEInstantiationException- FIXME
-
init
protected void init(ApplicationConfigInit 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
-
getUsername
public String getUsername()
Get user name (system propertyuser.name).- Returns:
- user name
-
getOsName
public String getOsName()
Get os name (system propertyos.name).- Returns:
- os name
- Since:
- 2.6.6
-
getOsArch
public String getOsArch()
Get os arch (system propertyos.arch).- Returns:
- os arch
- Since:
- 2.6.6
-
loadDefaultOptions
public <O extends ConfigOptionDef> void loadDefaultOptions(O... options)
Load default given options.- Type Parameters:
O- type of enum extendConfigOptionDef- Parameters:
options- options to load- Since:
- 2.4.8
-
loadActions
public <A extends ConfigActionDef> void loadActions(A[] actions)
Load given actions.- Type Parameters:
A- type of enum extendConfigActionDef- Parameters:
actions- actions to load- Since:
- 2.4.8
-
setDefaultOption
public void setDefaultOption(String key, 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
protected Properties getProperties(ApplicationConfigScope scope)
-
putAll
protected void putAll(Properties prop, ApplicationConfigScope scope)
-
save
public void save(File file, boolean forceAll, String... excludeKeys) throws IOException
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
public void saveForSystem(String... excludeKeys) throws ApplicationConfigSaveException
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
public void saveForUser(String... excludeKeys) throws ApplicationConfigSaveException
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
-
saveForCurrent
public void saveForCurrent(String... excludeKeys) throws ApplicationConfigSaveException
Save configuration, in current directory using thegetConfigFileName(). Default, env and command line note saved.- Parameters:
excludeKeys- optional list of keys to exclude from- Throws:
ApplicationConfigSaveException
-
cleanUserConfig
public void cleanUserConfig(String... excludeKeys) throws ApplicationConfigSaveException
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
public File getSystemConfigFile() throws ApplicationConfigFileNameNotInitializedException
Obtain the system config file location.- Returns:
- the system config file location
- Throws:
ApplicationConfigFileNameNotInitializedException- if no config file name found in configuration
-
getUserConfigFile
public File getUserConfigFile() throws ApplicationConfigFileNameNotInitializedException
Obtain the user config file location.- Returns:
- the user config file location
- Throws:
ApplicationConfigFileNameNotInitializedException- if no config file name found in configuration
-
getCurrentConfigFile
public File getCurrentConfigFile() throws ApplicationConfigFileNameNotInitializedException
Obtain the current directory config file location.- Returns:
- the current directory config file location
- Throws:
ApplicationConfigFileNameNotInitializedException- if no config file name found in configuration
-
getUnparsed
public List<String> getUnparsed()
Return list of unparsed command line argument- Returns:
- list of unparsed arguments
-
addAction
public void addAction(ApplicationConfig.Action action)
Add action to list of action to do.- Parameters:
action- action to add, can be null.
-
getActionStep
public List<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 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:
ApplicationConfig.Action.Step
-
doAction
public void doAction(int step) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationExceptionDo 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:
ApplicationConfig.Action.Step
-
isUseOnlyAliases
public boolean isUseOnlyAliases()
-
setUseOnlyAliases
public void setUseOnlyAliases(boolean useOnlyAliases)
-
getCharset
public Charset getCharset()
-
getEncoding
public 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(String encoding)
Set the new encoding option.- Parameters:
encoding- the new value of the option encoding- Since:
- 2.3
-
addAlias
public void addAlias(String alias, 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(String alias, 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
-
getConfigFileName
public String getConfigFileName()
Get name of file where options are read (in /etc, $HOME, $CURDIR).- Returns:
- name of file
-
setConfigFileName
public void setConfigFileName(String name)
Set name of file where options are read (in /etc, $HOME, $CURDIR) This set usedsetDefaultOption(String, String).- Parameters:
name- file name
-
getConfigFileNameOption
protected String getConfigFileNameOption()
-
getEncodingOption
protected String getEncodingOption()
Obtains the key used to store the option encoding.- Returns:
- the encoding option'key
- Since:
- 2.3
-
setAppName
public void setAppName(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 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 String getSystemConfigurationPath()
Get system configuration path.Currently supported:
- Windows : C:\Windows\System32
- Unix : /etc/
- Returns:
- the system path
- Since:
- 1.2.1
-
getUserConfigDirectory
public 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(String key)
Teste si un option existe ou non.- Parameters:
key- la clef de l'option à tester- Returns:
truesi l'option existe,falsesinon.
-
hasOption
public boolean hasOption(ConfigOptionDef key)
Teste si un option existe ou non- Parameters:
key- la clef de l'option à tester- Returns:
truesi 'loption existe,falsesinon.
-
putObject
public void putObject(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(String name, 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(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(Class<E> clazz, 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
@Deprecated public Object getOptionAsObject(String key)
Deprecated.usegetOption(Class, String)instead.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
@Deprecated public <E> E getOptionAsObject(Class<E> clazz, String key)
Deprecated.usegetOption(Class, String)instead.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 Object getOptionAsSingleton(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(Class<E> clazz, 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(String key, String value)
Set option value. If the value is null, then the option is removed.- Parameters:
key- property keyvalue- property value
-
getOption
public String getOption(String key)
get option value as string.Replace inner ${xxx} value.
- Parameters:
key- the option's key- Returns:
- String representation value
-
replaceRecursiveOptions
public String replaceRecursiveOptions(String option)
Replace included ${xxx} suboptions by their values.- Parameters:
option- option to replace into- Returns:
- replaced option
- Since:
- 1.1.3
-
getConfig
public ApplicationConfig getConfig(Map<String,String> overwrite)
- 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
public SubApplicationConfig getSubConfig(String prefix)
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 Properties getOptionStartsWith(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
public Object getOption(ConfigOptionDef key)
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(Class<T> clazz, 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> Object convertOption(Class<T> clazz, String key, 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
public ApplicationConfig.OptionList getOptionAsList(String key)
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 File getOptionAsFile(String key)
Get option value asFile.- Parameters:
key- the option's key- Returns:
- value as file
-
getOptionAsColor
public Color getOptionAsColor(String key)
Get option value asColor.- Parameters:
key- the option's key- Returns:
- value as color
-
getOptionAsProperties
public Properties getOptionAsProperties(String key) throws IOException
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
public URL getOptionAsURL(String key)
Get option value asURL.- Parameters:
key- the option's key- Returns:
- value as URL
-
getOptionAsClass
public Class<?> getOptionAsClass(String key)
Get option value asClass.- Parameters:
key- the option's key- Returns:
- value as Class
-
getOptionAsDate
public Date getOptionAsDate(String key)
Get option value asDate.- Parameters:
key- the option's key- Returns:
- value as Date
-
getOptionAsTime
public Time getOptionAsTime(String key)
Get option value asTime.- Parameters:
key- the option's key- Returns:
- value as Time
-
getOptionAsTimestamp
public Timestamp getOptionAsTimestamp(String key)
Get option value asTimestamp.- Parameters:
key- the option's key- Returns:
- value as Timestamp
-
getOptionAsInt
public int getOptionAsInt(String key)
Get option value asint.- Parameters:
key- the option's key- Returns:
- value as
int
-
getOptionAsLong
public long getOptionAsLong(String key)
Get option value aslong.- Parameters:
key- the option's key- Returns:
- value as
long
-
getOptionAsFloat
public float getOptionAsFloat(String key)
Get option value asfloat.- Parameters:
key- the option's key- Returns:
- value as
float - Since:
- 2.2
-
getOptionAsDouble
public double getOptionAsDouble(String key)
Get option value asdouble.- Parameters:
key- the option's key- Returns:
- value as
double
-
getOptionAsBoolean
public boolean getOptionAsBoolean(String key)
Get option value asboolean.- Parameters:
key- the option's key- Returns:
- value as
boolean.
-
getOptionAsLocale
public Locale getOptionAsLocale(String key)
Get option value asLocale.- Parameters:
key- the option's key- Returns:
- value as
Locale. - Since:
- 2.0
-
getOptionAsVersion
public io.ultreia.java4all.util.Version getOptionAsVersion(String key)
Get option value asVersion.- Parameters:
key- the option's key- Returns:
- value as
Version. - Since:
- 2.0
-
getOptionAsKeyStroke
public KeyStroke getOptionAsKeyStroke(String key)
Get option value asKeyStroke.- Parameters:
key- the option's key- Returns:
- value as
KeyStroke. - Since:
- 2.5.1
-
getOptions
public Properties getOptions()
Get all options from configuration.- Returns:
- Properties which contains all options
-
setOptions
public void setOptions(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 Properties getFlatOptions()
Get all options as flatPropertiesobject (replace inner options).- Returns:
- flat Properties object
- Since:
- 1.2.2
-
getFlatOptions
public 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
-
getMethods
protected Map<String,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 String[] getParams(Method m, ListIterator<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(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
public ApplicationConfig parse(String... args) throws ArgumentsParserException
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
-
loadResource
protected void loadResource(URI uri, Properties properties) throws IOException
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:
Properties.load(Reader)
-
saveResource
protected void saveResource(File file, Properties properties, String comment)
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:
Properties.store(Writer, String)
-
printConfig
public void printConfig()
For debugging.
-
printConfig
public void printConfig(PrintStream output)
Print out current configuration in specified output.- Parameters:
output- output to write config to- Since:
- 1.1.4
-
getPrintableConfig
public String getPrintableConfig(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
protected void remove(String key, ApplicationConfigScope... scopes)
-
-