Class ApplicationConfig

java.lang.Object
org.nuiton.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'ApplicationConfig qui contiendra par exemple une méthode :


   public static ApplicationConfig getConfig(
           Properties props, String configFilename, String ... args) {

       ApplicationConfig conf = new ApplicationConfig(
               MyAppConfigOption.class, MyAppConfigAction.class,
               props, configFilename);

       try {
           conf.parse(args);
       } catch (ArgumentsParserException eee) {
           if (log.isErrorEnabled()) {
               log.error("Can't load app configuration", eee);
           }
       }
       return conf;
   }

 
  • MyAppConfigOption doit étendre ConfigOptionDef et décrire les options de la configuration de l'application.
  • MyAppConfigAction doit étendre ConfigActionDef et décrire la liste des actions et de leur alias disponible pour l'application.

Lecture des fichiers de configuration

La lecture des fichiers de configuration se fait durant l'appel de la méthode parse(String...) en utilisant la valeur de qui doit être définit dans les options avec pour clef CONFIG_FILE_NAME pour trouver les fichiers (voir Les options de configuration pour l'ordre de chargement des fichiers)

La sauvegarde

La sauvegarde des options se fait via une des trois méthodes disponibles :

Lors de l'utilisation de la methode saveForSystem(String...) ou saveForUser(String...) seules les options lues dans un fichier ou modifiées par programmation (setOption(String, String) seront sauvegardées. Par exemple les options passees sur la ligne de commande ne seront pas sauvées.

Les options de configuration

Cette classe permet de lire les fichiers de configuration, utiliser les variable d'environnement et de parser la ligne de commande. L'ordre de prise en compte des informations trouvées est le suivant (le premier le plus important) :

  • options ajoutées par programmation: setOption(String, String)
  • ligne de commande
  • variable d'environnement de la JVM: java -Dkey=value
  • variable d'environnement; export key=value
  • fichier de configuration du repertoire courant: $user.dir/filename
  • fichier de configuration du repertoire home de l'utilisateur: $user.home/.filename
  • fichier de configuration du repertoire /etc: /etc/filename
  • fichier de configuration trouve dans le classpath: $CLASSPATH/filename
  • options ajoutées par programmation: setDefaultOption(String, String)

Les options sur la ligne de commande sont de la forme:

 --option key value
 --monOption key value1 value2
 
  • --option key value: est la syntaxe par defaut
  • --monOption key value1 value2: est la syntaxe si vous avez ajouter une méthode setMonOption(key, value1, value2) sur votre classe de configuration qui hérite de ApplicationConfig. Dans ce cas vous pouvez mettre les arguments que vous souhaitez du moment qu'ils soient convertibles de la representation String vers le type que vous avez mis.

Les actions

Les actions ne peuvent etre que sur la ligne de commande. Elles sont de la forme:

 --le.package.LaClass#laMethode arg1 arg2 arg3 ... argN
 

Une action est donc défini par le chemin complet vers la méthode qui traitera l'action. Cette méthode peut-être une méthode static ou non. Si la méthode n'est pas static lors de l'instanciation de l'objet on essaie de passer en paramètre du constructeur la classe de configuration utilisée pour permettre a l'action d'avoir a sa disposition les options de configuration. Si aucun constructeur avec comme seul paramètre une classe héritant de ApplicationConfig n'existe alors le constructeur par défaut est utilise (il doit être accessible). Toutes methodes d'actions faisant parties d'un meme objet utiliseront la meme instance de cette objet lors de leur execution.

Si la méthode utilise les arguments variants alors tous les arguments jusqu'au prochain -- ou la fin de la ligne de commande sont utilises. Sinon Le nombre exact d'argument nécessaire a la méthode sont utilises.

Les arguments sont automatiquement converti dans le bon type réclamé par la methode.

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

Les actions ne sont pas execute mais seulement parsées. Pour les exécuter il faut utiliser la méthode doAction(int) qui prend en argument un numéro de 'step' ou doAllAction() qui fait les actions dans l'ordre de leur step. Par défaut toutes les actions sont de niveau 0 et sont exécutées dans l'ordre d'apparition sur la ligne de commande. Si l'on souhaite distinguer les actions il est possible d'utiliser l'annotation ApplicationConfig.Action.Step sur la methode qui fera l'action en precisant une autre valeur que 0.

 doAction(0);
 ... do something ...
 doAction(1);
 

dans cette exemple on fait un traitement entre l'execution des actions de niveau 0 et les actions de niveau 1.

Les arguments non parsées

Tout ce qui n'est pas option ou action est considèré comme non parse et peut etre recupere par la methode getUnparsed(). Si l'on souhaite forcer la fin du parsing de la ligne de commande il est possible de mettre --. Par exemple:

 monProg "mon arg" --option k1 v1 -- --option k2 v2 -- autre
 

Dans cet exemple seule la premiere option sera considère comme une option. On retrouvera dans unparsed: "mon arg", "--option", "k2", "v2", "--", "autre"

Les alias

On voit qu'aussi bien pour les actions que pour les options, le nom de la méthode doit être utilise. Pour éviter ceci il est possible de définir des alias ce qui permet de creer des options courtes par exemple. Pour cela, on utilise la méthode addAlias(String, String...).

 addAlias("-v", "--option", "verbose", "true");
 addAlias("-o", "--option", "outputfile");
 addAlias("-i", "--mon.package.MaClass#MaMethode", "import");
 
En faite avant le parsing de la ligne de commande tous les alias trouves sont automatiquement remplacer par leur correspondance. Il est donc possible d'utiliser ce mécanisme pour autre chose par exemple:
 addAlias("cl", "Code Lutin");
 addAlias("bp", "Benjamin POUSSIN);
 

Dans le premier exemple on simplifie une option de flags l'option -v n'attend donc plus d'argument. Dans le second exemple on simplifie une option qui attend encore un argument de type File. Enfin dans le troisième exemple on simplifie la syntaxe d'une action et on force le premier argument de l'action a être "import".

Conversion de type

Pour la conversion de type nous utilisons common-beans. Les types supportes sont:

  • les primitif (byte, short, int, long, float, double, char, boolean)
  • String
  • File
  • URL
  • Class
  • SqlDate
  • SqlTime
  • SqlTimestamp
  • les tableaux d'un type primitif ou String. Chaque element doit etre separe par une virgule.

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

Les substitutions de variable

ApplicationConfig supporte les substituions de variables de la forme ${xxx}xxx est une autre variable de la configuration.

Exemple (dans un fichier de configuration):

 firstname = John
 lastname = Doe
 fullname = ${firstname} ${lastname}
 
getOption("fullname") retournera "John Doe".
Since:
0.30
Author:
Benjamin Poussin - poussin@codelutin.com, Tony Chemit - dev@tchemit.fr
  • Field Details

    • LIST_SEPARATOR

      public static final String LIST_SEPARATOR
      See Also:
    • CONFIG_FILE_NAME

      public static final String CONFIG_FILE_NAME
      Configuration file key option.
      See Also:
    • CONFIG_ENCODING

      public static final String CONFIG_ENCODING
      Configuration encoding key option.
      See Also:
    • APP_NAME

      public static final String APP_NAME
      Permet d'associer un nom de contexte pour prefixer les options CONFIG_PATH et CONFIG_FILE_NAME.
      See Also:
    • ADJUSTING_PROPERTY

      public static final String ADJUSTING_PROPERTY
      Property name of adjusting internal state.
      Since:
      1.3
      See Also:
    • 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:
    • 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
    • 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

      TODO
    • pcs

      Deprecated.
      since 3.1, we should no more use property change support on ApplicationConfig
      support of config modification.
    • context

      protected Map<String,Object> context
      permet de conserver des objets associe avec ce ApplicationConfig
    • applicationIOHelper

      protected ApplicationConfigIOHelper applicationIOHelper
      Pour gérer la lecture/écriture des properties.
      Since:
      3.1
  • Constructor Details

    • ApplicationConfig

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

      Also init converters.

      See Also:
      • ConverterUtil.initConverters()
    • ApplicationConfig

      public ApplicationConfig(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 defaults

      Also 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 null
      configFilename - 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
    • ApplicationConfig

      @Deprecated public ApplicationConfig(Class<O> optionClass, Class<A> actionClass, Properties defaults, String configFilename)
      Deprecated.
      All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line
      Type Parameters:
      O - option type
      A - action type
      Parameters:
      optionClass - class that describe option, can be null
      actionClass - class that describe action, can be null
      defaults - properties that override default value of optionClass, can be null
      configFilename - override default config filename, can be null
  • Method Details

    • 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
    • init

      @Deprecated protected void init(Properties defaults, String configFilename)
      Deprecated.
      since 3.0, no more used, use now init(ApplicationConfigInit)
      On separt l'init du corps du constructeur, car les sous classes ne doivent pas l'executer.
      Parameters:
      defaults - properties that override default value of optionClass, can be null
      configFilename - override default config filename, can be null
      Since:
      2.4.9
    • 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
    • getOsName

      public String getOsName()
      Get os name (system property os.name).
      Returns:
      os name
      Since:
      2.6.6
    • getOsArch

      public String getOsArch()
      Get os arch (system property os.arch).
      Returns:
      os arch
      Since:
      2.6.6
    • loadDefaultOptions

      @Deprecated public <O extends ConfigOptionDef> void loadDefaultOptions(Class<O> optionClass)
      Deprecated.
      since 2.4.8, prefer use now loadDefaultOptions(ConfigOptionDef[])
      Load default options of enum pass in param (enum must extend ConfigOptionDef)
      Type Parameters:
      O - type of enum extend ConfigOptionDef
      Parameters:
      optionClass - to load
    • loadDefaultOptions

      public <O extends ConfigOptionDef> void loadDefaultOptions(O[] options)
      Load default given options.
      Type Parameters:
      O - type of enum extend ConfigOptionDef
      Parameters:
      options - options to load
      Since:
      2.4.8
    • loadActions

      @Deprecated public <A extends ConfigActionDef> void loadActions(Class<A> actionClass)
      Deprecated.
      since 2.4.8, prefer use now loadActions(ConfigActionDef[])
      Load actions of enum pass in param (enum must extend ConfigActionDef)
      Type Parameters:
      A - type of enum extend ConfigActionDef
      Parameters:
      actionClass - to load
    • loadActions

      public <A extends ConfigActionDef> void loadActions(A[] actions)
      Load given actions.
      Type Parameters:
      A - type of enum extend ConfigActionDef
      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 key
      value - 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 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) throws ApplicationConfigSaveException
      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
      Throws:
      ApplicationConfigSaveException
    • saveForUser

      public void saveForUser(String... excludeKeys) throws ApplicationConfigSaveException
      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
      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 given excludeKeys will 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
    • 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

      Do all action in specified order step (first 0).
      Throws:
      IllegalAccessException - if action invocation failed
      IllegalArgumentException - if action invocation failed
      InvocationTargetException - if action invocation failed
      InstantiationException - if action invocation failed
      Since:
      2.4
      See Also:
    • doAction

      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:
    • setUseOnlyAliases

      public void setUseOnlyAliases(boolean useOnlyAliases)
    • isUseOnlyAliases

      public boolean isUseOnlyAliases()
    • 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 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()
    • 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.file option becomes pollen.config.file and config.path becomes pollen.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:

      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:
      true si l'option existe, false sinon.
    • hasOption

      public boolean hasOption(ConfigOptionDef key)
      Teste si un option existe ou non
      Parameters:
      key - la clef de l'option à tester
      Returns:
      true si 'loption existe, false sinon.
    • 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'option
      o - 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

      public Object getOptionAsObject(String key)
      retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key'. Retourne null si la cle n'est pas retrouve.
      Parameters:
      key - le nom de l'option à récupérer
      Returns:
      l'objet requis
      Since:
      2.4.2
    • getOptionAsObject

      public <E> E getOptionAsObject(Class<E> clazz, String key)
      retourne une nouvelle instance d'un objet dont on recupere la la class dans la configuration via la cle 'key' et le cast en E. Retourne null si la cle n'est pas retrouve

      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
      key - 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 retrouve

      La classe peut avoir un constructeur prenant un ApplicationConfig

      Type Parameters:
      E - le type de l'option à récupérer
      Parameters:
      clazz - le type de l'option à récupérer
      key - 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 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

      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 type
      key - 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 true

      example:

      • 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 expected
      key - option key
      value - value to convert
      asList - 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 as File.
      Parameters:
      key - the option's key
      Returns:
      value as file
    • getOptionAsColor

      public Color getOptionAsColor(String key)
      Get option value as Color.
      Parameters:
      key - the option's key
      Returns:
      value as color
    • getOptionAsProperties

      public Properties getOptionAsProperties(String key) throws IOException
      Get option value as Properties, 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 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
    • getOptionAsLong

      public long getOptionAsLong(String key)
      Get option value as long.
      Parameters:
      key - the option's key
      Returns:
      value as long
    • getOptionAsFloat

      public float getOptionAsFloat(String key)
      Get option value as float.
      Parameters:
      key - the option's key
      Returns:
      value as float
      Since:
      2.2
    • 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.
    • getOptionAsLocale

      public Locale getOptionAsLocale(String key)
      Get option value as Locale.
      Parameters:
      key - the option's key
      Returns:
      value as Locale.
      Since:
      2.0
    • getOptionAsVersion

      public org.nuiton.version.Version getOptionAsVersion(String key)
      Get option value as Version.
      Parameters:
      key - the option's key
      Returns:
      value as Version.
      Since:
      2.0
    • getOptionAsKeyStroke

      public KeyStroke getOptionAsKeyStroke(String key)
      Get option value as KeyStroke.
      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 by setConfigFileName(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

      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 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
    • 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
    • loadResource

      protected void loadResource(URI uri, Properties properties) throws IOException
      Load a resources given by his uri to the given properties argument.
      Parameters:
      uri - the uri to load
      properties - the properties file to load
      Throws:
      IOException - if something occurs bad while loading resource
      Since:
      2.3
      See Also:
    • saveResource

      protected void saveResource(File file, Properties properties, String comment) throws IOException
      Save the given properties into the given file with the given comment.
      Parameters:
      file - the location where to store the properties
      properties - the properties file to save
      comment - the comment to add in the saved file
      Throws:
      IOException - if something occurs bad while saving resource
      Since:
      2.3
      See Also:
    • 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)
    • firePropertyChange

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

      @Deprecated public void addPropertyChangeListener(PropertyChangeListener listener)
      Deprecated.
    • addPropertyChangeListener

      @Deprecated public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)
      Deprecated.
    • removePropertyChangeListener

      @Deprecated public void removePropertyChangeListener(PropertyChangeListener listener)
      Deprecated.
    • removePropertyChangeListener

      @Deprecated public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)
      Deprecated.
    • hasListeners

      @Deprecated public boolean hasListeners(String propertyName)
      Deprecated.
    • getPropertyChangeListeners

      @Deprecated public PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
      Deprecated.
    • getPropertyChangeListeners

      @Deprecated public PropertyChangeListener[] getPropertyChangeListeners()
      Deprecated.