org.nuiton.util
Class ApplicationConfig

java.lang.Object
  extended by org.nuiton.util.ApplicationConfig

public class ApplicationConfig
extends Object

Application configuration.

A finir...

Usage

Create subclass of ApplicationConfig, where in constructor you call setConfigFileName(String), setDefaultOption(String, String), addAlias(String, String...), addActionAlias(String, String), to have properly value.
     
     conf = new MonAppConfig();
     conf.parse(args);
     here you can used conf.getOption(key);
     conf.doAction(0);
     ...
     conf.doAction(n);
 

Lecture des fichiers de configuration

La lecture des fichiers de configuration se fait durant l'appel de la methode parse(java.lang.String[]) en utilisant la valeur de getConfigFileName() 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 methodes disponibles : Lors de l'utilisation de la methode saveForSystem(java.lang.String...) ou saveForUser(java.lang.String...) seules les options lues dans un fichier ou modifiées par programmation (setOption(java.lang.String, java.lang.String) seront sauvegardées. Par exemple les options passees sur la ligne de commande ne seront pas sauvees.

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) : Les options sur la ligne de commande sont de la forme:
 --option key value
 --monOption key value1 value2
 

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 defini par le chemin complet vers la methode qui traitera l'action. Cette methode peut-etre une methode static ou non. Si la methode n'est pas static lors de l'instanciation de l'objet on essaie de passer en parametre du constructeur la classe de configuration utilisee pour permettre a l'action d'avoir a sa disposition les options de configuration. Si aucun constructeur avec comme seul parametre une classe heritant de ApplicationConfig n'existe alors le constructeur par defaut est utilise (il doit etre accessible). Toutes methodes d'actions faisant parties d'un meme objet utiliseront la meme instance de cette objet lors de leur execution.

Si la methode 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 necessaire a la methode sont utilises.

Les arguments sont automatiquement converti dans le bon type reclame par la methode.

Si l'on veut des arguments optionnels le seul moyen actuellement est d'utiliser une methode avec des arguments variants

Les actions ne sont pas execute mais seulement parsees. Pour les executer il faut utiliser la méthode doAction(int) qui prend en argument un numero de 'step'. Par defaut toutes les actions sont de niveau 0 et sont executee 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 considere 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 considere 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 methode doit etre utilise. Pour eviter ceci il est possible de definir des alias ce qui permet de creer des options courtes par exemple. Pour cela, on utilise la methode addAlias(java.lang.String, java.lang.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 mecanisme 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 argment de type File. Enfin dans le troisieme exemple on simplifie la syntaxe d'une action et on force le premier argument de l'action a etre "import".

Conversion de type

Pour la conversion de type nous utilisons common-beans. Les types supportes sont: Pour suporter d'autre type, il vous suffit d'enregistrer de nouveau converter dans commons-beans.

Les substitutions de variable

ApplicationConfig supporte les substition de variables de la forme ${xxx}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
Version:
$Revision: 1871 $

Last update $Date: 2010-06-01 15:31:51 +0200 (mar., 01 juin 2010) $ by

Author:
poussin

Nested Class Summary
static class ApplicationConfig.Action
          Defines a runtime action to be launched via the ApplicationConfig.Action.doAction() method.
protected static class ApplicationConfig.CacheItem<T>
          Item used for cacheOption
static interface ApplicationConfig.OptionDef
          Le contrat de marquage des options, on utilise cette interface pour caracteriser une option de configuration.
 
Field Summary
protected  Map<Integer,List<ApplicationConfig.Action>> actions
          TODO
static String ADJUSTING_PROPERTY
          Property name of adjusting internal state.
protected  Map<String,List<String>> aliases
          TODO
static String APP_NAME
          TODO
protected  Map<Class<?>,Object> cacheAction
          TODO
protected  Map<String,ApplicationConfig.CacheItem<?>> cacheOption
          TODO
protected  Properties classpath
          TODO
static String CONFIG_FILE_NAME
          Configuration file key option.
static String CONFIG_PATH
          Configuration directory where config path in located.
protected  Properties curfile
          TODO
protected  Properties defaults
          TODO
protected  Properties env
          TODO
protected  Properties etcfile
          TODO
protected  Properties homefile
          TODO
protected  boolean inParseOptionPhase
          vrai si on est en train de parser les options de la ligne de commande.
protected  Properties jvm
          TODO
protected  Properties line
          TODO
protected  Properties options
          TODO
protected  String osName
          System os name.
protected  PropertyChangeSupport pcs
          suport of config modification.
protected  List<String> unparsed
          contient apres l'appel de parse, la liste des arguments non utilises
protected  boolean useOnlyAliases
          TODO
protected  String userPath
          Deprecated. since 1.2.1, and can't be removed (for migration purpose)
 
Constructor Summary
ApplicationConfig()
          Init ApplicationConfig with current simple class name as config file.
 
Method Summary
 void addAction(ApplicationConfig.Action action)
          Add action to list of action to do
 void addActionAlias(String alias, String actionMethod)
          Add alias for action.
 void addAlias(String alias, String... target)
          All argument in aliases as key is substitued by target.
 void addPropertyChangeListener(PropertyChangeListener listener)
           
 void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)
           
protected  ApplicationConfig.Action createAction(String name, ListIterator<String> args)
          Create action from string, string must be [package.]
 void doAction(int step)
          Do action in specified step.
protected  void firePropertyChange(String propertyName, Object oldValue, Object newValue)
           
 String getConfigFileName()
          Get name of file where options are read (in /etc, $HOME, $CURDIR).
protected  String getConfigFileNameOption()
           
 String getConfigPath()
          Get configuration file path to use.
 Properties getFlatOptions()
          Get all options as flat Properties object (replace inner options).
 Properties getFlatOptions(boolean replaceInner)
          Get all options as flat Properties object.
protected  Map<String,Method> getMethods()
          Get all set method on this object or super object.
 Object getOption(ApplicationConfig.OptionDef key)
          Get option value from a option definition.
<T> T
getOption(Class<T> clazz, String key)
          Get option value as typed value.
 String getOption(String key)
          get option value as string.
 boolean getOptionAsBoolean(String key)
          Get option value as boolean.
 Class<?> getOptionAsClass(String key)
          Get option value as Class.
 Date getOptionAsDate(String key)
          Get option value as Date.
 double getOptionAsDouble(String key)
          Get option value as double.
 File getOptionAsFile(String key)
          Get option value as File.
 int getOptionAsInt(String key)
          Get option value as int.
 Time getOptionAsTime(String key)
          Get option value as Time.
 Timestamp getOptionAsTimestamp(String key)
          Get option value as Timestamp.
 URL getOptionAsURL(String key)
          Get option value as URL.
 Properties getOptions()
          Get all options from configuration.
 Properties getOptionStartsWith(String prefix)
          Permet de recuperer l'ensemble des options commencant par une certaine chaine.
protected  String[] getParams(Method m, ListIterator<String> args)
          Take required argument for method in args.
 PropertyChangeListener[] getPropertyChangeListeners()
           
 PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
           
 File getSystemConfigFile()
          Obtain the system config file location.
protected  String getSystemConfigurationPath()
          Get system configuration path.
 List<String> getUnparsed()
          Return list of unparsed command line argument
 File getUserConfigFile()
          Obtain the user config file location.
static String getUserHome()
          Get user home directory (system property user.home).
 String getUsername()
          Get user name (system property user.name).
protected  String getUserPath()
          Get user configuration path.
 boolean hasListeners(String propertyName)
           
protected  void installSaveUserAction(String... properties)
          Install the saveUserAction on givne properties.
 boolean isAdjusting()
           
 boolean isUseOnlyAliases()
           
protected  void migrateUserConfigurationFile(File oldHomeConfig, File homeConfig)
          Move old user configuration file oldHomeConfig to homeConfig.
 void parse(String[] args)
          Parse option and call set necessary method, read jvm, env variable, Load configuration file and prepare Action.
 void printConfig()
          For debugging.
 void printConfig(PrintStream output)
          Print out current configuration in specified output.
 void removePropertyChangeListener(PropertyChangeListener listener)
           
 void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)
           
protected  String replaceRecursiveOptions(String option)
          Replace included ${xxx} suboptions by their values.
 void save(File file, boolean forceAll, String... excludeKeys)
          Save configuration, in specified file.
 void saveForSystem(String... excludeKeys)
          Save configuration, in system directory (/etc/) using the getConfigFileName().
 void saveForUser(String... excludeKeys)
          Save configuration, in user home directory using the getConfigFileName().
 void setAdjusting(boolean adjusting)
           
 void setAppName(String appName)
          Use appName to add a context in config.file and config.path options.
 void setConfigFileName(String name)
          Set name of file where options are read (in /etc, $HOME, $CURDIR) This set used setDefaultOption(String, String)
protected  void setDefaultOption(String key, String value)
          Used to put default configuration option in config option.
 void setOption(String key, String value)
          Set option value.
 void setOptions(Properties options)
          Set manually options when you don't want to use parse method to check properties file configured by setConfigFileName(java.lang.String).
 void setUseOnlyAliases(boolean useOnlyAliases)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CONFIG_FILE_NAME

public static final String CONFIG_FILE_NAME
Configuration file key option.

See Also:
Constant Field Values

APP_NAME

public static final String APP_NAME
TODO

See Also:
Constant Field Values

ADJUSTING_PROPERTY

public static final String ADJUSTING_PROPERTY
Property name of adjusting internal state.

Since:
1.3
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:

See Also:
Constant Field Values

osName

protected String osName
System os name. (windows, linux, max os x)


useOnlyAliases

protected boolean useOnlyAliases
TODO


userPath

@Deprecated
protected String userPath
Deprecated. since 1.2.1, and can't be removed (for migration purpose)
file $user.home/.[filename] Not used anymore. Just used for migration issue.


inParseOptionPhase

protected boolean inParseOptionPhase
vrai si on est en train de parser les options de la ligne de commande.


defaults

protected Properties defaults
TODO


classpath

protected Properties classpath
TODO


etcfile

protected Properties etcfile
TODO


homefile

protected Properties homefile
TODO


curfile

protected Properties curfile
TODO


env

protected Properties env
TODO


jvm

protected Properties jvm
TODO


line

protected Properties line
TODO


options

protected Properties options
TODO


cacheOption

protected Map<String,ApplicationConfig.CacheItem<?>> cacheOption
TODO


cacheAction

protected Map<Class<?>,Object> cacheAction
TODO


unparsed

protected List<String> unparsed
contient apres l'appel de parse, la liste des arguments non utilises


aliases

protected Map<String,List<String>> aliases
TODO


actions

protected Map<Integer,List<ApplicationConfig.Action>> actions
TODO


pcs

protected PropertyChangeSupport pcs
suport of config modification.

Constructor Detail

ApplicationConfig

public ApplicationConfig()
Init ApplicationConfig with current simple class name as config file. Also init converters.

See Also:
ConverterUtil.initConverters()
Method Detail

getUserHome

public static String getUserHome()
Get user home directory (system property user.home).

Returns:
user home directory

getUsername

public String getUsername()
Get user name (system property user.name).

Returns:
user name

setDefaultOption

protected 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 key
value - default property value

save

public void save(File file,
                 boolean forceAll,
                 String... excludeKeys)
          throws IOException
Save configuration, in specified file.

Parameters:
file - file where config will be writen
forceAll - 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)
Save configuration, in system directory (/etc/) using the getConfigFileName(). Default, env and commande line note saved.

Parameters:
excludeKeys - optional list of keys to exclude from

saveForUser

public void saveForUser(String... excludeKeys)
Save configuration, in user home directory using the getConfigFileName(). Default, env and commande line note saved

Parameters:
excludeKeys - optional list of keys to exclude from

getSystemConfigFile

public File getSystemConfigFile()
Obtain the system config file location.

Returns:
the system config file location

getUserConfigFile

public File getUserConfigFile()
Obtain the user config file location.

Returns:
the user config file location

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.

doAction

public void doAction(int step)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException,
                     InstantiationException
Do action in specified step.

Parameters:
step - do action only defined in this step
Throws:
IllegalAccessException - if action invocation failed
IllegalArgumentException - if action invocation failed
InvocationTargetException - if action invocation failed
InstantiationException - if action invocation failed
See Also:
ApplicationConfig.Action.Step

setUseOnlyAliases

public void setUseOnlyAliases(boolean useOnlyAliases)

isUseOnlyAliases

public boolean isUseOnlyAliases()

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 call addAlias(String, String...)

Parameters:
alias - the alias to add for the given method action
actionMethod - must be fully qualified method path: package.Class.method

setConfigFileName

public void setConfigFileName(String name)
Set name of file where options are read (in /etc, $HOME, $CURDIR) This set used setDefaultOption(String, String)

Parameters:
name - file name

getConfigFileName

public 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 String getConfigFileNameOption()

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.file option becomes pollen.config.file

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:

Returns:
path to use with endind File.separator
Since:
1.2.1

getSystemConfigurationPath

protected String getSystemConfigurationPath()
Get system configuration path. Currently supported:

Returns:
the system path
Since:
1.2.1

getUserPath

protected String getUserPath()
Get user configuration path. Currently supported: 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

setOption

public void setOption(String key,
                      String value)
Set option value.

Parameters:
key - property key
value - 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

protected String replaceRecursiveOptions(String option)
Replace included ${xxx} suboptions by their values.

Parameters:
option - option to replace into
Returns:
replaced option
Since:
1.1.3

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(ApplicationConfig.OptionDef 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 type
key - the option's key
Returns:
typed value

getOptionAsFile

public File getOptionAsFile(String key)
Get option value as File.

Parameters:
key - the option's key
Returns:
value as file

getOptionAsURL

public URL getOptionAsURL(String key)
Get option value as URL.

Parameters:
key - the option's key
Returns:
value as URL

getOptionAsClass

public Class<?> getOptionAsClass(String key)
Get option value as Class.

Parameters:
key - the option's key
Returns:
value as Class

getOptionAsDate

public Date getOptionAsDate(String key)
Get option value as Date.

Parameters:
key - the option's key
Returns:
value as Date

getOptionAsTime

public Time getOptionAsTime(String key)
Get option value as Time.

Parameters:
key - the option's key
Returns:
value as Time

getOptionAsTimestamp

public Timestamp getOptionAsTimestamp(String key)
Get option value as Timestamp.

Parameters:
key - the option's key
Returns:
value as Timestamp

getOptionAsInt

public int getOptionAsInt(String key)
Get option value as int.

Parameters:
key - the option's key
Returns:
value as int

getOptionAsDouble

public double getOptionAsDouble(String key)
Get option value as double.

Parameters:
key - the option's key
Returns:
value as double

getOptionAsBoolean

public boolean getOptionAsBoolean(String key)
Get option value as boolean.

Parameters:
key - the option's key
Returns:
value as boolean.

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 by setConfigFileName(java.lang.String).

Parameters:
options - Properties which contains all options to set

getFlatOptions

public Properties getFlatOptions()
Get all options as flat Properties object (replace inner options).

Returns:
flat Properties object
Since:
1.2.2

getFlatOptions

public Properties getFlatOptions(boolean replaceInner)
Get all options as flat Properties object.

Parameters:
replaceInner - if true replace imbricated options by theirs values
Returns:
flat Properties object
Since:
1.2.2

installSaveUserAction

protected void installSaveUserAction(String... properties)
Install the saveUserAction on givne properties.

Parameters:
properties - properties on which insalls the saveUserAction

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 call
args - 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 action
args - arguments for action invocation
Returns:
the created action
Throws:
ArgumentsParserException - if parsing failed
IllegalAccessException - if could not create action
IllegalArgumentException - if could not create action
InstantiationException - if could not create action
InvocationTargetException - if could not create action

parse

public void 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)
Throws:
ArgumentsParserException - if parsing failed

migrateUserConfigurationFile

protected void migrateUserConfigurationFile(File oldHomeConfig,
                                            File homeConfig)
                                     throws IOException
Move old user configuration file oldHomeConfig to homeConfig.

Parameters:
oldHomeConfig - old configuration file path
homeConfig - new configuration file path
Throws:
IOException - if could not move configuration file

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

firePropertyChange

protected void firePropertyChange(String propertyName,
                                  Object oldValue,
                                  Object newValue)

addPropertyChangeListener

public void addPropertyChangeListener(PropertyChangeListener listener)

addPropertyChangeListener

public void addPropertyChangeListener(String propertyName,
                                      PropertyChangeListener listener)

removePropertyChangeListener

public void removePropertyChangeListener(PropertyChangeListener listener)

removePropertyChangeListener

public void removePropertyChangeListener(String propertyName,
                                         PropertyChangeListener listener)

hasListeners

public boolean hasListeners(String propertyName)

getPropertyChangeListeners

public PropertyChangeListener[] getPropertyChangeListeners(String propertyName)

getPropertyChangeListeners

public PropertyChangeListener[] getPropertyChangeListeners()


Copyright © 2004-2010 CodeLutin. All Rights Reserved.