|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectorg.nuiton.util.ApplicationConfig
public class ApplicationConfig
Application configuration.
useOnlyAliases
getOptionAsList(String)
ApplicationConfig qui contiendra par exemple une méthode :
static public 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;
}
ApplicationConfig.OptionDef et décrir la configuration de l'application.
ApplicationConfig.ActionDef et décrir la liste des options
et de leur alias disponible pour l'application.
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)
save(File, boolean,String...) sauve les données dans le fichier demandé
saveForSystem(String...) sauvegarde les donnees dans /etc
saveForUser(String...) sauvegarde les donnees dans $HOME
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 sauvees.
setOption(String, String)defaults.put(key, value)--option key value --monOption key value1 value2
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.
--le.package.LaClass#laMethode arg1 arg2 arg3 ... argNUne 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.
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 -- autreDans cet exemple seule la premiere option sera considere comme une option. On retrouvera dans
unparsed: "mon arg", "--option", "k2", "v2", "--",
"autre"
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 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".
String
File
URL
Class
Date
Time
Timestamp
String. Chaque element doit
etre separe par une virgule.
ApplicationConfig supporte les substition de variables de la forme
${xxx} où xxx est une autre variable de la configuration.
Exemple (dans un fichier de configuration):
firstname = John
lastname = Doe
fullname = ${firstname} ${lastname}
getOption("fullname") retournera "John Doe".
| Nested Class Summary | |
|---|---|
static class |
ApplicationConfig.Action
Defines a runtime action to be launched via the ApplicationConfig.Action.doAction()
method. |
static interface |
ApplicationConfig.ActionDef
Le contrat de marquage des action, on utilise cette interface pour caracteriser une 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. |
static class |
ApplicationConfig.OptionList
|
| 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
Permet d'associer un nom de contexte pour prefixer les options CONFIG_PATH et CONFIG_FILE_NAME. |
protected Map<Class<?>,Object> |
cacheAction
TODO |
protected Map<String,ApplicationConfig.CacheItem<?>> |
cacheOption
TODO |
protected Properties |
classpath
TODO |
static String |
CONFIG_ENCODING
Configuration encoding key option. |
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 |
static String |
LIST_SEPARATOR
|
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. |
|
ApplicationConfig(Class<O> optionClass,
Class<A> actionClass,
Properties defaults,
String configFilename)
All in one, this constructor allow to pass all necessary argument to initialise ApplicationConfig and parse command line |
|
ApplicationConfig(Properties defaults)
Init ApplicationConfig with current simple class name as config file and use Properties parameter as defaults Also init converters. |
|
ApplicationConfig(String configFilename)
Create WikittyConfig and load particular configuration filename |
|
| 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
|
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) => [] |
|
protected ApplicationConfig.Action |
createAction(String name,
ListIterator<String> args)
Create action from string, string must be [package.][class][#][method] if package, class or method missing, default is used |
|
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. |
|
String |
getEncoding()
Get the encoding used to read/write resources. |
|
protected String |
getEncodingOption()
Obtains the key used to store the option encoding. |
|
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. |
|
|
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. |
|
float |
getOptionAsFloat(String key)
Get option value as float. |
|
int |
getOptionAsInt(String key)
Get option value as int. |
|
ApplicationConfig.OptionList |
getOptionAsList(String key)
Help to convert value to list of object. |
|
Locale |
getOptionAsLocale(String key)
Get option value as Locale. |
|
long |
getOptionAsLong(String key)
Get option value as long. |
|
Properties |
getOptionAsProperties(String key)
Get option value as Properties, this property must be a filepath
and file must be a properties. |
|
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. |
|
Version |
getOptionAsVersion(String key)
Get option value as Version. |
|
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. |
|
String |
getPrintableConfig(String includePattern,
int padding)
Return all configuration used with value, that respect includePattern |
|
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 |
|
String |
getUserConfigDirectory()
Get user configuration path. |
|
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). |
|
boolean |
hasListeners(String propertyName)
|
|
protected void |
installSaveUserAction(String... properties)
Install the saveUserAction on givne properties. |
|
boolean |
isAdjusting()
|
|
boolean |
isUseOnlyAliases()
|
|
|
loadActions(Class<A> actionClass)
Load actions of enum pass in param (enum must extend ApplicationConfig.ActionDef) |
|
|
loadDefaultOptions(Class<O> optionClass)
Load default options of enum pass in param (enum must extend ApplicationConfig.OptionDef) |
|
protected void |
loadResource(URI uri,
Properties properties)
Load a resources given by his uri to the given
properties argument. |
|
protected void |
migrateUserConfigurationFile(File oldHomeConfig,
File homeConfig)
Move old user configuration file oldHomeConfig to homeConfig. |
|
ApplicationConfig |
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(). |
|
protected void |
saveResource(File file,
Properties properties,
String comment)
Save the given properties into the given file with
the given comment. |
|
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). |
|
void |
setDefaultOption(String key,
String value)
Used to put default configuration option in config option. |
|
void |
setEncoding(String encoding)
Set the new encoding 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(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 |
|---|
public static final String LIST_SEPARATOR
public static final String CONFIG_FILE_NAME
public static final String CONFIG_ENCODING
public static final String APP_NAME
CONFIG_PATH et CONFIG_FILE_NAME.
public static final String ADJUSTING_PROPERTY
adjusting internal state.
public static final String CONFIG_PATH
protected String osName
protected boolean useOnlyAliases
@Deprecated protected String userPath
protected boolean inParseOptionPhase
protected Properties defaults
protected Properties classpath
protected Properties etcfile
protected Properties homefile
protected Properties curfile
protected Properties env
protected Properties jvm
protected Properties line
protected Properties options
protected Map<String,ApplicationConfig.CacheItem<?>> cacheOption
protected Map<Class<?>,Object> cacheAction
protected List<String> unparsed
protected Map<String,List<String>> aliases
protected Map<Integer,List<ApplicationConfig.Action>> actions
protected PropertyChangeSupport pcs
| Constructor Detail |
|---|
public ApplicationConfig()
ConverterUtil.initConverters()public ApplicationConfig(String configFilename)
configFilename - name of config to usepublic ApplicationConfig(Properties defaults)
defaults - propertiesConverterUtil.initConverters()
public ApplicationConfig(Class<O> optionClass,
Class<A> actionClass,
Properties defaults,
String configFilename)
optionClass - class that describe option, can be nullactionClass - class that describe action, can be nulldefaults - properties that override default value of optionClass, can be nullconfigFilename - override default config filename, can be null| Method Detail |
|---|
public static String getUserHome()
user.home).
public String getUsername()
user.name).
public <O extends ApplicationConfig.OptionDef> void loadDefaultOptions(Class<O> optionClass)
ApplicationConfig.OptionDef)
O - type of enum extend ApplicationConfig.OptionDefoptionClass - to loadpublic <A extends ApplicationConfig.ActionDef> void loadActions(Class<A> actionClass)
ApplicationConfig.ActionDef)
A - type of enum extend ApplicationConfig.ActionDefactionClass - to load
public void setDefaultOption(String key,
String value)
key - default property keyvalue - default property value
public void save(File file,
boolean forceAll,
String... excludeKeys)
throws IOException
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
IOException - if IO pbpublic void saveForSystem(String... excludeKeys)
getConfigFileName(). Default, env and commande line note saved.
excludeKeys - optional list of keys to exclude frompublic void saveForUser(String... excludeKeys)
getConfigFileName(). Default, env and commande line note saved
excludeKeys - optional list of keys to exclude frompublic File getSystemConfigFile()
public File getUserConfigFile()
public List<String> getUnparsed()
public void addAction(ApplicationConfig.Action action)
action - action to add, can be null.
public void doAction(int step)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
InstantiationException
step - do action only defined in this step
IllegalAccessException - if action invocation failed
IllegalArgumentException - if action invocation failed
InvocationTargetException - if action invocation failed
InstantiationException - if action invocation failedApplicationConfig.Action.Steppublic void setUseOnlyAliases(boolean useOnlyAliases)
public boolean isUseOnlyAliases()
public String getEncoding()
getEncodingOption() key.
public void setEncoding(String encoding)
encoding - the new value of the option encoding
public void addAlias(String alias,
String... target)
alias - alias string as '-v'target - substitution as '--option verbose true'
public void addActionAlias(String alias,
String actionMethod)
addAlias(String, String...).
alias - the alias to add for the given method actionactionMethod - must be fully qualified method path:
package.Class#methodpublic void setConfigFileName(String name)
setDefaultOption(String, String).
name - file namepublic String getConfigFileName()
public boolean isAdjusting()
public void setAdjusting(boolean adjusting)
protected String getConfigFileNameOption()
protected String getEncodingOption()
public void setAppName(String appName)
config.file option becomes
pollen.config.file and config.path becomes
pollen.config.path
appName - to use as application contextpublic String getConfigPath()
CONFIG_PATH option
File.separatorprotected String getSystemConfigurationPath()
public String getUserConfigDirectory()
public void setOption(String key,
String value)
key - property keyvalue - property valuepublic String getOption(String key)
key - the option's key
protected String replaceRecursiveOptions(String option)
option - option to replace into
public Properties getOptionStartsWith(String prefix)
prefix - debut de cle a recuperer
public Object getOption(ApplicationConfig.OptionDef key)
key - the definition of the option
public <T> T getOption(Class<T> clazz,
String key)
T - type of the object wanted as return typeclazz - type of object wanted as return typekey - the option's key
protected <T> Object convertOption(Class<T> clazz,
String key,
String value,
boolean asList)
clazz - result type expectedkey - option keyvalue - value to convertasList - value is string that represente a list
public ApplicationConfig.OptionList getOptionAsList(String key)
key - the key of searched option
public File getOptionAsFile(String key)
File.
key - the option's key
public Properties getOptionAsProperties(String key)
throws IOException
Properties, this property must be a filepath
and file must be a properties.
Returned Properties is RecursiveProperties.
key - the option's key
IOException - if exception occured on read filepublic URL getOptionAsURL(String key)
URL.
key - the option's key
public Class<?> getOptionAsClass(String key)
Class.
key - the option's key
public Date getOptionAsDate(String key)
Date.
key - the option's key
public Time getOptionAsTime(String key)
Time.
key - the option's key
public Timestamp getOptionAsTimestamp(String key)
Timestamp.
key - the option's key
public int getOptionAsInt(String key)
int.
key - the option's key
intpublic long getOptionAsLong(String key)
long.
key - the option's key
longpublic float getOptionAsFloat(String key)
float.
key - the option's key
floatpublic double getOptionAsDouble(String key)
double.
key - the option's key
doublepublic boolean getOptionAsBoolean(String key)
boolean.
key - the option's key
boolean.public Locale getOptionAsLocale(String key)
Locale.
key - the option's key
Locale.public Version getOptionAsVersion(String key)
Version.
key - the option's key
Version.public Properties getOptions()
public void setOptions(Properties options)
setConfigFileName(String).
options - Properties which contains all options to setpublic Properties getFlatOptions()
Properties object (replace inner options).
public Properties getFlatOptions(boolean replaceInner)
Properties object.
replaceInner - if true replace imbricated options by theirs values
protected void installSaveUserAction(String... properties)
saveUserAction on givne properties.
properties - properties on which insalls the saveUserActionprotected Map<String,Method> getMethods()
protected String[] getParams(Method m,
ListIterator<String> args)
m - the method to callargs - iterator with many argument (equals or more than necessary
protected ApplicationConfig.Action createAction(String name,
ListIterator<String> args)
throws ArgumentsParserException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
name - name of the actionargs - arguments for action invocation
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
public ApplicationConfig parse(String... args)
throws ArgumentsParserException
args - argument as main(String[] args)
ArgumentsParserException - if parsing failed
protected void migrateUserConfigurationFile(File oldHomeConfig,
File homeConfig)
throws IOException
oldHomeConfig to homeConfig.
oldHomeConfig - old configuration file pathhomeConfig - new configuration file path
IOException - if could not move configuration file
protected void loadResource(URI uri,
Properties properties)
throws IOException
uri to the given
properties argument.
uri - the uri to loadproperties - the properties file to load
IOException - if something occurs bad while loading resourceProperties.load(Reader)
protected void saveResource(File file,
Properties properties,
String comment)
throws IOException
properties into the given file with
the given comment.
file - the location where to store the propertiesproperties - the properties file to savecomment - the comment to add in the saved file
IOException - if something occurs bad while saving resourceProperties.store(Writer, String)public void printConfig()
public void printConfig(PrintStream output)
output - output to write config to
public String getPrintableConfig(String includePattern,
int padding)
includePattern - null for all value, or config key pattern (ex: "wikitty.*")padding - for better presentation, you can use padding to align '=' sign
protected void firePropertyChange(String propertyName,
Object oldValue,
Object newValue)
public void addPropertyChangeListener(PropertyChangeListener listener)
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener)
public void removePropertyChangeListener(PropertyChangeListener listener)
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener)
public boolean hasListeners(String propertyName)
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
public PropertyChangeListener[] getPropertyChangeListeners()
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||