org.nuiton.util
Class ApplicationConfig

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

public class ApplicationConfig
extends Object

To do

Usage

  • create subclass of ApplicationConfig, where in constructor you call addAliases, setConfigFileName, setDefaultActionPackage, setDefaultActionClass, setDefaultActionMethod 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 disponible

    Lors de l'utilisation de la methode saveForSystem(String[]) ou saveForUser(String[]) seul les options lu dans un fichier ou modifier par programmation (setOption(java.lang.String, java.lang.String) seront sauvegardees. 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 la suivante (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. Ils 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 utiilser la methode 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 parses

    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 supporte sont:

    Pour suporter d'autre type, il vous suffit d'enregistrer de nouveau converter dans commons-beans

    Since:
    0.30

    Last update $Date$ by $Author$

    Version:
    $Revision$
    Author:
    poussin

    Nested Class Summary
    static class ApplicationConfig.Action
               
    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
               
    protected  Map<String,List<String>> aliases
               
    protected  Map<Class<?>,Object> cacheAction
               
    protected  Map<String,ApplicationConfig.CacheItem<?>> cacheOption
               
    protected  Properties classpath
               
    static String CONFIG_FILE_NAME
               
    protected  Properties curfile
               
    protected  Properties defaults
               
    protected  Properties env
               
    protected  Properties etcfile
               
    protected  Properties homefile
               
    protected  boolean inParseOptionPhase
              vrai si on est en train de parser les options de la ligne de commande
    protected  Properties jvm
               
    protected  Properties line
               
    protected  Properties options
               
    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
               
     
    Constructor Summary
    ApplicationConfig()
               
     
    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)
               
    protected  void firePropertyChange(String propertyName, Object oldValue, Object newValue)
               
     String getConfigFileName()
               
    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 typed value
     Class<?> getOptionAsClass(String key)
              get option value as typed value
     Date getOptionAsDate(String key)
              get option value as typed value
     double getOptionAsDouble(String key)
              get option value as typed value
     File getOptionAsFile(String key)
              get option value as typed value
     int getOptionAsInt(String key)
              get option value as typed value
     Time getOptionAsTime(String key)
              get option value as typed value
     Timestamp getOptionAsTimestamp(String key)
              get option value as typed value
     URL getOptionAsURL(String key)
              get option value as typed value
     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)
               
     List<String> getUnparsed()
              Return list of unparsed command line argument
    static String getUserHome()
               
     String getUsername()
               
     boolean hasListeners(String propertyName)
               
     boolean isUseOnlyAliases()
               
     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 removePropertyChangeListener(PropertyChangeListener listener)
               
     void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)
               
     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 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.
     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
    See Also:
    Constant Field Values

    useOnlyAliases

    protected boolean useOnlyAliases

    aliases

    protected Map<String,List<String>> aliases

    inParseOptionPhase

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


    defaults

    protected Properties defaults

    classpath

    protected Properties classpath

    etcfile

    protected Properties etcfile

    homefile

    protected Properties homefile

    curfile

    protected Properties curfile

    env

    protected Properties env

    jvm

    protected Properties jvm

    line

    protected Properties line

    options

    protected Properties options

    cacheOption

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

    cacheAction

    protected Map<Class<?>,Object> cacheAction

    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

    pcs

    protected PropertyChangeSupport pcs
    suport of config modification

    Constructor Detail

    ApplicationConfig

    public ApplicationConfig()
    Method Detail

    getUserHome

    public static String getUserHome()

    getUsername

    public String getUsername()

    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

    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
    Throws:
    IllegalAccessException
    IllegalArgumentException
    InvocationTargetException
    InstantiationException

    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()

    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

    Parameters:
    key - the option's key
    Returns:
    String representation value

    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 typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsURL

    public URL getOptionAsURL(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsClass

    public Class<?> getOptionAsClass(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsDate

    public Date getOptionAsDate(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsTime

    public Time getOptionAsTime(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsTimestamp

    public Timestamp getOptionAsTimestamp(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsInt

    public int getOptionAsInt(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsDouble

    public double getOptionAsDouble(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    getOptionAsBoolean

    public boolean getOptionAsBoolean(String key)
    get option value as typed value

    Parameters:
    key - the option's key
    Returns:
    typed value

    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.

    Parameters:
    options - Properties which contains all options to set

    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 -
    Returns:
    the created action
    Throws:
    ArgumentsParserException
    IllegalAccessException
    IllegalArgumentException
    InstantiationException
    InvocationTargetException

    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

    printConfig

    public void printConfig()
    For debugging


    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-2009 CodeLutin. All Rights Reserved.