r2633 - in isis-fish/trunk: . src/main/java/fr/ifremer/isisfish/simulator src/main/java/fr/ifremer/isisfish/simulator/launcher src/test/java/fr/ifremer/isisfish/simulator src/test/resources/fr/ifremer/isisfish src/test/resources/fr/ifremer/isisfish/simulator src/test/resources/test-database/regions src/test/resources/test-database/regions/BaseMotosICA src/test/resources/test-database/regions/BaseMotosICA/data
Author: chatellier Date: 2009-09-18 09:07:37 +0000 (Fri, 18 Sep 2009) New Revision: 2633 Added: isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/ isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/ isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/ isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.1.log.db isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.data.db isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.index.db Modified: isis-fish/trunk/changelog.txt isis-fish/trunk/pom.xml isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java Log: Modifie la mecanique des parametres de simulation, instanciation ?\195?\160 la demande (regles/ plan/ export/ sensitivity export/sensitivity calculcator) Modified: isis-fish/trunk/changelog.txt =================================================================== --- isis-fish/trunk/changelog.txt 2009-09-18 09:05:13 UTC (rev 2632) +++ isis-fish/trunk/changelog.txt 2009-09-18 09:07:37 UTC (rev 2633) @@ -1,5 +1,8 @@ isis-fish (3.2.0.7) stable; urgency=low + * Fix strategies/population selection on old simulation reloading + * Always use logger for force writing in debug.txt file + * Instantiate simulation parameters objects only when needed (to work on caparmor) * Add log in equation content * Fix export names selection problem for current simulation * Fix result names selection problem for current simulation Modified: isis-fish/trunk/pom.xml =================================================================== --- isis-fish/trunk/pom.xml 2009-09-18 09:05:13 UTC (rev 2632) +++ isis-fish/trunk/pom.xml 2009-09-18 09:07:37 UTC (rev 2633) @@ -450,7 +450,7 @@ <goal>generate</goal> </goals> <configuration> - <extraImportList>jaxx.runtime.SwingUtil,static jaxx.runtime.Util.getStringValue</extraImportList> + <extraImportList>jaxx.runtime.SwingUtil</extraImportList> <addSourcesToClassPath>true</addSourcesToClassPath> <addProjectClassPath>true</addProjectClassPath> </configuration> Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java 2009-09-18 09:05:13 UTC (rev 2632) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/SimulationParameter.java 2009-09-18 09:07:37 UTC (rev 2633) @@ -27,8 +27,8 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; @@ -43,6 +43,7 @@ import org.codelutin.topia.TopiaContext; import org.codelutin.topia.TopiaException; import org.codelutin.topia.persistence.TopiaEntity; +import org.codelutin.util.SortedProperties; import org.codelutin.util.StringUtil; import fr.ifremer.isisfish.IsisConfig; @@ -67,10 +68,20 @@ /** * Contains all parameters for one simulation. * + * {@link SimulationParameter} must now be loaded from a {@link Properties} + * object. + * {@link #toProperties()} method, now return a new {@link Properties} object + * filled with : + * <ul> + * <li>non modified original properties + * <li>new properties if some objects has been instantiated by getters(). + * </ul> + * * Created: 10 janv. 2006 17:03:37 * * @author poussin - * + * @author chatellier + * * @version $Revision$ * * Last update: $Date$ @@ -82,83 +93,80 @@ private static Log log = LogFactory.getLog(SimulationParameter.class); /** Remember last read properties. */ - protected Properties lastReadParameters; + protected Properties propertiesParameters; /** - * @deprecated remove this hack + * Isis-fish version that permit to do the simulation. + * Must be set just before simulation by simulator. */ - public static String NUMBER_OF_SENSITIVITY_SIMULATION = "numberOfSensitivitySimulation"; + protected String isisFishVersion; - /** - * Isis-fish version that permit to do the simulation, must be set just - * before simulation by simulator. - */ - protected String isisFishVersion = IsisConfig.getVersion(); + /** Description de la simulation. */ + protected String description; - /** description de la simulation */ - protected String description = ""; + /** Nom de la region sur lequel on simule. */ + protected String regionName; - /** nom de la region sur lequel on simule */ - protected String regionName = ""; + /** Nombre d'année sur lequel on souhaite simuler. */ + protected Integer numberOfYear; - /** nombre d'année sur lequel on souhaite simuler */ - protected int numberOfYear = 1; + /** Le nom de l'objet script a utiliser pour faire la simulation. */ + protected String simulatorName; - /** le nom de l'objet script a utiliser pour faire la simulation */ - protected String simulatorName = "DefaultSimulator.java"; + /** Utilisation ou non des optimisations. */ + protected Boolean useOptimization; - /** utilisation ou non des optimisations */ - protected boolean useOptimization = true; + /** Utilisation ou non des statistiques. */ + protected Boolean useStatistic; - /** utilisation ou non des statistiques */ - protected boolean useStatistic = false; + /** La liste des strategies a utiliser pour la simulation. */ + protected List<Strategy> strategies; - /** la liste des strategies a utiliser pour la simulation */ - protected List<Strategy> strategies = new ArrayList<Strategy>(); + /** La liste des populations a utiliser pour la simulation. */ + protected List<Population> populations; - /** la liste des populations a utiliser pour la simulation */ - protected List<Population> populations = new ArrayList<Population>(); + /** Les effectifs initiaux des différentes population. */ + protected Map<Population, MatrixND> numbers; - /** les effectifs initiaux des différentes population */ - protected Map<Population, MatrixND> numbers = new HashMap<Population, MatrixND>(); + /** La liste des regles de gestions a utiliser pour la simulation. */ + protected List<Rule> rules; - /** la liste des regles de gestions a utiliser pour la simulation */ - protected List<Rule> rules = new ArrayList<Rule>(); + /** La liste des regles potentiellement ajoutée par les plans d'analyse. */ + protected List<String> extraRules; - /** la liste des regles potentiellement ajoutée par les plans d'analyse */ - protected List<String> extraRules = new ArrayList<String>(); + /** La liste des plans a utiliser pour la simulation. */ + protected List<AnalysePlan> analysePlans; - /** la liste des plans a utiliser pour la simulation */ - protected List<AnalysePlan> plans = new ArrayList<AnalysePlan>(); + /** Ma liste des exports automatique a faire en fin de simulation. */ + protected List<String> exportNames; - /** la liste des exports automatique a faire en fin de simulation */ - protected List<String> exportNames = new ArrayList<String>(); + /** Repertoire d'enregistrement des exports. */ + protected String exportDirectory; - protected String exportDirectory = "/tmp"; + /** Utilisation du script de pre simulation. */ + protected Boolean usePreScript; - /** utilisation du script de pre simulation */ - protected boolean usePreScript = false; + /** Le script de pre simulation a utiliser. */ + protected String preScript; - /** le script de pre simulation a utiliser */ - protected String preScript = ""; + /** Utilisation du plan d'analyse. */ + protected Boolean useAnalysePlan; - /** utilisation du plan d'analyse */ - protected boolean useAnalysePlan = false; - /** * Le script de plan d'analyse. * @deprecated since 3.2.0.7 unused */ - protected String analysePlan = ""; + protected String analysePlan; - /** le numero de sequence de la liste des plans d'analyse, le premier + /** + * Le numero de sequence de la liste des plans d'analyse. Le premier * élement du plan doit etre 0. Si la simulation ne fait pas partie d'un - * plan la valeur est -1 */ - protected int analysePlanNumber = -1; + * plan la valeur est -1. */ + protected Integer analysePlanNumber; /** Export utilisés pour les analyses de sensibilités. */ - protected List<SensitivityExport> sensitivityExports = new ArrayList<SensitivityExport>(); - + protected List<SensitivityExport> sensitivityExports; + /** * Nombre de simulation constituant l'analyse de sensibilité. * @@ -167,32 +175,35 @@ * Cela permet de savoir combien de simulation il y a au total * pour savoir quand elle sont terminées. */ - protected int numberOfSensitivitySimulation = -1; - + protected Integer numberOfSensitivitySimulation; + /** Export utilisés pour les analyses de sensibilités. */ - protected SensitivityCalculator sensitivityCalculator = null; - - /** la liste des resultats qui nous interesse */ - protected Collection<String> resultEnabled = new HashSet<String>(); + protected SensitivityCalculator sensitivityCalculator; - /** autre parametre defini par l'utilisateur */ - protected Map<String, String> tagValue = new LinkedHashMap<String, String>(); + /** La liste des resultats qui nous interesse. */ + protected Collection<String> resultEnabled; + /** Autre parametre defini par l'utilisateur. */ + protected Map<String, String> tagValue; + /** - * si vrai seul les exports automatiques ne sont souhaiter, la simulation - * pourrait etre supprimée a la fin + * Si vrai seul les exports automatiques ne sont souhaiter, la simulation + * pourrait etre supprimée a la fin. */ - protected boolean onlyExport = false; + protected Boolean onlyExport; - protected transient RegionStorage region = null; - - /** le niveau de log du simulateur à utiliser pendant la simulation , par default info */ + /** Le niveau de log du simulateur à utiliser pendant la simulation. Par defaut info. */ protected String simulLogLevel = "info"; - /** le niveau de log des scripts à utiliser pendant la simulation , par default info */ - protected String scriptLogLevel = "info"; - /** le niveau de log des librairies à utiliser pendant la simulation , par default error */ + /** Le niveau de log des scripts à utiliser pendant la simulation. Par defaut info. */ + protected String scriptLogLevel = "info"; + /** Le niveau de log des librairies à utiliser pendant la simulation. Par defaut error. */ protected String libLogLevel = "error"; - + + /** La region corespondant au parametre {@link #regionName}. */ + protected transient RegionStorage region; + /** [HACK] Directory form where region have to be loaded. */ + protected transient File directory; + /** * Permet de verifier que tous les parametres sont bon. Si ce n'est pas le * cas la liste retournée contient la liste des messages d'erreur. @@ -208,13 +219,28 @@ } /** - * @return Returns the isisFishVersion. + * Get isis fish version for the simulation. + * + * Defaut value to : {@link IsisConfig#getVersion()}. + * + * @return the isisFishVersion. */ public String getIsisFishVersion() { - return this.isisFishVersion; + // if not already set + if (isisFishVersion == null) { + if (propertiesParameters != null) { + isisFishVersion = propertiesParameters.getProperty("isisFishVersion", ""); + } else { + // default value + isisFishVersion = IsisConfig.getVersion(); + } + } + return isisFishVersion; } /** + * Set isis fish Version. + * * @param isisFishVersion The isisFishVersion to set. */ public void setIsisFishVersion(String isisFishVersion) { @@ -224,394 +250,52 @@ /** * Get description property. * + * Default value to : "". + * * @return Description property. */ public String getDescription() { + + if (description == null) { + if (propertiesParameters != null) { + description = propertiesParameters.getProperty("description", ""); + } else { + // default value + description = ""; + } + } return this.description; } /** - * @param description The description to set. + * Set simulation description. + * + * @param description the description to set. */ public void setDescription(String description) { this.description = description; } /** - * Permet de convertir l'objet SimulationParameter en un objet Properties - * Cela permet de le stocker facilement sur le disque. - * - * @return L'objet Properties representant les parametres - * @see #fromProperties(File, Properties) - */ - public Properties toProperties() { - Properties result = new Properties(); - - result.setProperty("isisFishVersion", isisFishVersion); - result.setProperty("description", description); - result.setProperty("regionName", regionName); - result.setProperty("numberOfYear", String.valueOf(numberOfYear)); - result.setProperty("simulatorName", simulatorName); - result.setProperty("useOptimization", String.valueOf(useOptimization)); - result.setProperty("useStatistic", String.valueOf(useStatistic)); - - String strategyList = ""; - for (Strategy str : getStrategies()) { - strategyList += str.getName() + ","; - } - result.setProperty("strategies", StringUtil.substring(strategyList, 0, - -1)); - - String populationList = ""; - for (Population pop : getPopulations()) { - populationList += pop.getName() + ","; - MatrixND number = getNumberOf(pop); - String numberAsString = String.valueOf(number.toList()); - result.setProperty("population." + pop.getName() + ".number", - numberAsString); - } - result.setProperty("populations", StringUtil.substring(populationList, - 0, -1)); - - String ruleList = ""; - int ruleIndex = 0; - for (Rule rule : getRules()) { - ruleList += RuleStorage.getName(rule) + ","; - Properties ruleProp = ruleParametertoProperties(ruleIndex++, rule); - result.putAll(ruleProp); - } - result.setProperty("rules", ruleList); - - String planList = ""; - int planIndex = 0; - for (AnalysePlan plan : getAnalysePlans()) { - planList += AnalysePlanStorage.getName(plan) + ","; - Properties planProp = planParametertoProperties(planIndex++, plan); - result.putAll(planProp); - } - result.setProperty("plans", planList); - - String exportList = ""; - for (String export : getExportNames()) { - exportList += export + ","; - - } - result.setProperty("exports", exportList); - - // number of sensitivity simulation - result.setProperty(NUMBER_OF_SENSITIVITY_SIMULATION, String.valueOf(numberOfSensitivitySimulation)); - - // calculator name - if (getSensitivityCalculator() != null) { - String calculatorName = SensitivityStorage.getName(getSensitivityCalculator()); - result.setProperty("sensitivitycalculator", calculatorName); - - // calculator parameter - Properties calculatorParams = sensitivityCalculatorParametertoProperties(0, getSensitivityCalculator()); - result.putAll(calculatorParams); - } - - // number of sensitivity simulation - String sensitivityExportList = ""; - int sensitivityExportIndex = 0; - // WARN only SENSITIVITY are parametrable for now - for (SensitivityExport sensitivityExport : getSensitivityExport()) { - sensitivityExportList += SensitivityExportStorage.getName(sensitivityExport) + ","; - Properties exportProp = sensitivityExportParametertoProperties(sensitivityExportIndex++, sensitivityExport); - result.putAll(exportProp); - } - result.setProperty("sensitivityexports", sensitivityExportList); - - - - result.setProperty("usePreScript", String.valueOf(usePreScript)); - result.setProperty("preScript", preScript); - result.setProperty("useAnalysePlan", String.valueOf(useAnalysePlan)); - result.setProperty("analysePlan", analysePlan); - result.setProperty("analysePlanNumber", String.valueOf(analysePlanNumber)); - - String resultList = ""; - for (String r : getResultEnabled()) { - resultList += r + ","; - } - result.setProperty("resultNames", resultList); - - for (Map.Entry<String, String> e : getTagValue().entrySet()) { - result.setProperty("tagValue." + e.getKey(), e.getValue()); - } - - result.setProperty("onlyExport", String.valueOf(onlyExport)); - result.setProperty("exportDirectory", String.valueOf(exportDirectory)); - - result.setProperty("simulLogLevel", simulLogLevel); - result.setProperty("scriptLogLevel", scriptLogLevel); - result.setProperty("libLogLevel", libLogLevel); - return result; - } - - /** - * Load properties from file. + * Load region conresponding to {@link #regionName}. * - * @param directory if not null, region will be forced to this directory - * @param props property to read - */ - public void fromProperties(File directory, Properties props) { - - // save properties (use full to read again parameter) - // for exports, or rules.... - lastReadParameters = props; - - // when reading new properties files, clean some information - // to force re instantion on next call - sensitivityExports = null; - rules = null; - - isisFishVersion = props.getProperty("isisFishVersion", ""); - description = props.getProperty("description", ""); - regionName = props.getProperty("regionName", ""); - numberOfYear = Integer.parseInt(props.getProperty("numberOfYear", "1")); - simulatorName = props.getProperty("simulatorName", "DefaultSimulator"); - useOptimization = Boolean.parseBoolean(props.getProperty( - "useOptimization", "true")); - useStatistic = Boolean.parseBoolean(props.getProperty( - "useStatistic", "true")); - - // FIXME not good place and code - if (directory != null && (this.region == null || !region.getName().equals(regionName))) { - // ATTENTION: directory pointe sur le repertoire de la simulation et non de la region - this.region = new RegionStorage(directory, regionName); // RegionStorage.getRegion(directory, regionName); - } - - try { - // On verifie tout d'abord que l'on ai pas dans une simulation - // si on y es, on utilise le context static non null du thread local - // Resoud les lazy exceptions des parametres des regles - boolean mustClose = false; - TopiaContext tx = SimulationContext.get().getDB(); - - if (tx == null) { - // not in simulation, create transaction - tx = getRegion().getStorage().beginTransaction(); - mustClose = true; - } - - // strategies - try { - StrategyDAO strategyDAO = IsisFishDAOHelper.getStrategyDAO(tx); - String[] strategyList = props.getProperty("strategies", "") - .split(","); - for (String name : strategyList) { - if (name != null && !"".equals(name)) { - try { - Strategy str = strategyDAO.findByName(name); - getStrategies().add(str); - } catch (TopiaException eee) { - if (log.isWarnEnabled()) { - log.warn("Can't find strategy: " + name, eee); - } - } - } - } - } catch (TopiaException eee1) { - if (log.isWarnEnabled()) { - log.warn("Can't get StrategyDAO", eee1); - } - } - - // populations - try { - PopulationDAO populationDAO = IsisFishDAOHelper - .getPopulationDAO(tx); - String[] populationList = props.getProperty("populations", "") - .split(","); - for (String name : populationList) { - if (name != null && !"".equals(name)) { - try { - Population population = populationDAO - .findByName(name); - getPopulations().add(population); - - String numberAsString = props - .getProperty("population." + name - + ".number"); - List number = MatrixHelper - .convertStringToList(numberAsString); - MatrixND mat = getNumberOf(population); - mat.fromList(number); - } catch (TopiaException eee) { - if (log.isWarnEnabled()) { - log.warn("Can't find population: " + name, eee); - } - } - } - } - } catch (TopiaException eee1) { - if (log.isWarnEnabled()) { - log.warn("Can't get PopulationDAO", eee1); - } - } - - tx.commitTransaction(); - - // si la transaction a été ouverte (pas dans une simulation) - // on la referme - if (mustClose) { - tx.closeContext(); - } - } catch (TopiaException eee1) { - if (log.isWarnEnabled()) { - log.warn("Can't get TopiaContext", eee1); - } - } - - // analyse plan - String[] planList = props.getProperty("plans", "").split(","); - int planIndex = 0; - for (String name : planList) { - if (name != null && !"".equals(name)) { - try { - AnalysePlan plan = AnalysePlanStorage.getAnalysePlan(name).getNewAnalysePlanInstance(); - populateAnalysePlan(planIndex++, plan, props); - getAnalysePlans().add(plan); - } catch (IsisFishException eee) { - if (log.isWarnEnabled()) { - log.warn("Can't find plan: " + name, eee); - } - } - } - } - - // exports - String[] exportList = props.getProperty("exports", "").split(","); - for (String name : exportList) { - if (name != null && !"".equals(name)) { - getExportNames().add(name); - } - } - - // number of sensitivity simulation - numberOfSensitivitySimulation = Integer.parseInt(props.getProperty(NUMBER_OF_SENSITIVITY_SIMULATION, "-1")); - // calculator name - String sensitivityCalculator = props.getProperty("sensitivitycalculator", null); - if (!StringUtils.isEmpty(sensitivityCalculator)) { - try { - SensitivityCalculator calculator = SensitivityStorage.getSensitivity(sensitivityCalculator).getNewSensitivityInstance(); - // 0 = only single sensitivity - populateSensitivityCalculator(0, calculator, props); - setSensitivityCalculator(calculator); - } catch (IsisFishException eee) { - if (log.isWarnEnabled()) { - log.warn("Can't find sensitivity: " + sensitivityCalculator, eee); - } - } - } - - usePreScript = Boolean.parseBoolean(props.getProperty("usePreScript", - "false")); - preScript = props.getProperty("preScript"); - useAnalysePlan = Boolean.parseBoolean(props.getProperty( - "useAnalysePlan", "false")); - analysePlan = props.getProperty("analysePlan"); - analysePlanNumber = Integer.parseInt(props.getProperty("analysePlanNumber", "-1")); - - String[] resultList = props.getProperty("resultNames", "").split(","); - for (String name : resultList) { - if (name != null && !"".equals(name)) { - getResultEnabled().add(name); - } - } - - for (Object k : props.keySet()) { - if (k.toString().startsWith("tagValue.")) { - String key = k.toString().substring("tagValue.".length()); - String value = props.getProperty(k.toString()); - getTagValue().put(key, value); - } - } - - onlyExport = Boolean.parseBoolean(props.getProperty("onlyExport", - "false")); - - exportDirectory = props.getProperty("exportDirectory"); - - simulLogLevel = props.getProperty("simulLogLevel","info"); - scriptLogLevel = props.getProperty("scriptLogLevel","info"); - libLogLevel = props.getProperty("libLogLevel","info"); - } - - /** - * Reload parameters du to context change. + * Contains a hack to load region from a specific directory + * instead of regions direcory ({@link #directory}). * - * ie : in simulators when rollbacking transaction - * - * Actually : reload rules - * - * @throws TopiaException + * @return the region */ - public void reloadContextParameters() throws TopiaException { + public RegionStorage getRegion() { - // On verifie tout d'abord que l'on ai pas dans une simulation - // si on y es, on utilise le context static non null du thread local - // Resoud les lazy exceptions des parametres des regles - boolean mustClose = false; - TopiaContext tx = SimulationContext.get().getDB(); - - if (tx == null) { - // not in simulation, create transaction - tx = getRegion().getStorage().beginTransaction(); - mustClose = true; - } - - // reload rules - if (log.isDebugEnabled()) { - log.debug("Reloading rules"); - } - for (Rule rule : getRules()) { - try { - for (Field field : rule.getClass().getFields()) { - // le champ ne doit pas être privé - if (Modifier.isPublic(field.getModifiers())) { - // si le type est topia entity (ou sous classe) - if (TopiaEntity.class.isAssignableFrom(field.getType())) { - TopiaEntity entity = (TopiaEntity)field.get(rule); - // il est possible que les parametres soient null - // dans ce cas, il ne faut pas essayer de les recharger - if (entity != null) { - // reloading - TopiaEntity newEntity = tx.findByTopiaId(entity.getTopiaId()); - field.set(rule, newEntity); - } - } - } - } - } catch (IllegalArgumentException e) { - if (log.isErrorEnabled()) { - log.error("Can't refresh rule field", e); - } - } catch (IllegalAccessException e) { - if (log.isErrorEnabled()) { - log.error("Can't access rule field", e); - } + if (region == null || !region.getName().equals(getRegionName())) { + // hack + if (directory != null) { + // ATTENTION: directory pointe sur le repertoire de la simulation et non de la region + this.region = new RegionStorage(directory, regionName); + } else { + region = RegionStorage.getRegion(getRegionName()); } - } - - // si la transaction a été ouverte (pas dans une simulation) - // on la referme - if (mustClose) { - tx.commitTransaction(); - tx.closeContext(); - } - } - - /** - * @return Returns the region. - */ - public RegionStorage getRegion() { - if (region == null || !region.getName().equals(getRegionName())) { - region = RegionStorage.getRegion(getRegionName()); - } - else { - if(log.isDebugEnabled()) { + } else { + if (log.isDebugEnabled()) { log.debug(_("Region %s already inited", getRegionName())); } } @@ -619,6 +303,9 @@ } public MatrixND getNumberOf(Population pop) { + if (numbers == null) { + numbers = new LinkedHashMap<Population, MatrixND>(); + } MatrixND result = numbers.get(pop); if (result == null) { List groups = pop.getPopulationGroup(); @@ -650,46 +337,47 @@ */ protected Properties ruleParametertoProperties(int ruleIndex, Rule rule) { Properties result = new Properties(); - ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); + ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion() + .getStorage()); for (String paramName : RuleStorage.getParameterNames(rule).keySet()) { String paramValueString; try { Object value = RuleStorage.getParameterValue(rule, paramName); paramValueString = beanUtils.convert(value); if (paramValueString != null) { - result.setProperty("rule." + ruleIndex + ".parameter." - + paramName, paramValueString); + result.setProperty("rule." + ruleIndex + ".parameter." + paramName, paramValueString); } } catch (IsisFishException eee) { if (log.isWarnEnabled()) { - log.warn("Can't convert parameter value to String: " - + paramName, eee); + log.warn("Can't convert parameter value to String: " + paramName, eee); } } } return result; } - + /** * Permet de mettre les parametres de l'export sous une forme String pour * pouvoir les relire ensuite. * * @param sensitivityExportIndex l'index de l'export - * @param sensitivityExport L'export dont on souhaite mettre les parametres dans l'objet - * Properties retourne + * @param sensitivityExport l'export dont on souhaite mettre les parametres dans l'objet + * Properties retourné * @return L'objet Properties contenant les valeurs des parametres de l'export */ - protected Properties sensitivityExportParametertoProperties(int sensitivityExportIndex, SensitivityExport sensitivityExport) { + protected Properties sensitivityExportParametertoProperties( + int sensitivityExportIndex, SensitivityExport sensitivityExport) { Properties result = new Properties(); ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); for (String paramName : SensitivityExportStorage.getParameterNames(sensitivityExport).keySet()) { - String paramValueString; try { - Object value = SensitivityExportStorage.getParameterValue(sensitivityExport, paramName); - paramValueString = beanUtils.convert(value); + Object value = SensitivityExportStorage.getParameterValue( + sensitivityExport, paramName); + String paramValueString = beanUtils.convert(value); if (paramValueString != null) { - result.setProperty("sensitivityexport." + sensitivityExportIndex + ".parameter." + result.setProperty("sensitivityexport." + + sensitivityExportIndex + ".parameter." + paramName, paramValueString); } } catch (IsisFishException eee) { @@ -702,7 +390,7 @@ return result; } - + /** * Permet de mettre les parametres du calculateur sous une forme String pour * pouvoir les relire ensuite. @@ -712,17 +400,17 @@ * Properties retourne * @return L'objet Properties contenant les valeurs des parametres du calculateur de sensibilité */ - protected Properties sensitivityCalculatorParametertoProperties(int sensitivityIndex, SensitivityCalculator calculator) { + protected Properties sensitivityCalculatorParametertoProperties( + int sensitivityIndex, SensitivityCalculator calculator) { Properties result = new Properties(); ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); for (String paramName : SensitivityStorage.getParameterNames(calculator).keySet()) { - String paramValueString; try { - Object value = SensitivityStorage.getParameterValue(calculator, paramName); - paramValueString = beanUtils.convert(value); + Object value = SensitivityStorage.getParameterValue(calculator, + paramName); + String paramValueString = beanUtils.convert(value); if (paramValueString != null) { - result.setProperty("sensitivity." + sensitivityIndex + ".parameter." - + paramName, paramValueString); + result.setProperty("sensitivity." + sensitivityIndex + ".parameter." + paramName, paramValueString); } } catch (IsisFishException eee) { if (log.isWarnEnabled()) { @@ -744,14 +432,14 @@ * Properties retourne * @return L'objet Properties contenant les valeurs des parametres du plan */ - protected Properties planParametertoProperties(int planIndex, AnalysePlan plan) { + protected Properties planParametertoProperties(int planIndex, + AnalysePlan plan) { Properties result = new Properties(); ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); for (String paramName : AnalysePlanStorage.getParameterNames(plan).keySet()) { - String paramValueString; try { - Object value = AnalysePlanStorage.getParameterValue(plan, paramName); - paramValueString = beanUtils.convert(value); + Object value = AnalysePlanStorage.getParameterValue(plan,paramName); + String paramValueString = beanUtils.convert(value); if (paramValueString != null) { result.setProperty("plan." + planIndex + ".parameter." + paramName, paramValueString); @@ -776,8 +464,10 @@ * proprietes * @param props les proprietes contenant les parametre du plan */ - protected void populateAnalysePlan(int planIndex, AnalysePlan plan, Properties props) { - ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); + protected void populateAnalysePlan(int planIndex, AnalysePlan plan, + Properties props) { + ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion() + .getStorage()); String planName = AnalysePlanStorage.getName(plan); String paramTag = "plan." + planIndex + ".parameter."; @@ -793,23 +483,25 @@ AnalysePlanStorage.setParameterValue(plan, propName, value); } catch (IsisFishException eee) { if (log.isWarnEnabled()) { - log.warn("Can't reload field " + propName + " for plan " + planName , eee); + log.warn("Can't reload field " + propName + " for plan " + + planName, eee); } } } } - + /** - * Recupere dans prop les valeurs des champs specifique au calculateur de sensibilité et met a - * jour les champs du calculateur. + * Recupere dans prop les valeurs des champs specifique au calculateur de + * sensibilité et met a jour les champs du calculateur. * * @param calculatorIndex l'index du calculateur - * @param calculator le calculateur dont les parametres doivent etre lu depuis les - * proprietes + * @param calculator le calculateur dont les parametres doivent etre lu depuis lesproprietes * @param props les proprietes contenant les parametre du calculateur */ - protected void populateSensitivityCalculator(int calculatorIndex, SensitivityCalculator calculator, Properties props) { - ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion().getStorage()); + protected void populateSensitivityCalculator(int calculatorIndex, + SensitivityCalculator calculator, Properties props) { + ConvertUtilsBean beanUtils = ConverterUtil.getConverter(getRegion() + .getStorage()); String calculatorName = SensitivityStorage.getName(calculator); String paramTag = "sensitivity." + calculatorIndex + ".parameter."; @@ -825,34 +517,100 @@ SensitivityStorage.setParameterValue(calculator, propName, value); } catch (IsisFishException eee) { if (log.isWarnEnabled()) { - log.warn("Can't reload field " + propName + " for sensitivity calculator " + calculatorName , eee); + log.warn("Can't reload field " + propName + + " for sensitivity calculator " + calculatorName, + eee); } } } } /** + * Get extra rules list. + * * @return Returns the extraRules. */ public List<String> getExtraRules() { - return this.extraRules; + + if (extraRules == null) { + // no properties in config ? + extraRules = new ArrayList<String>(); + } + return extraRules; } /** - * @param extraRules The extraRules to set. + * Add extra rules. + * + * @param extraRules extra rules to add */ - public void addExtraRules(String ... extraRules) { - this.extraRules.addAll(Arrays.asList(extraRules)); + public void addExtraRules(String... extraRules) { + getExtraRules().addAll(Arrays.asList(extraRules)); } /** + * Get instantiated population list. + * * @return Returns the populations. */ public List<Population> getPopulations() { if (populations == null) { populations = new ArrayList<Population>(); + + if (propertiesParameters != null) { + + try { + // On verifie tout d'abord que l'on ai pas dans une simulation + // si on y es, on utilise le context static non null du thread local + // Resoud les lazy exceptions des parametres des regles + boolean mustClose = false; + TopiaContext tx = SimulationContext.get().getDB(); + + if (tx == null) { + // not in simulation, create transaction + tx = getRegion().getStorage().beginTransaction(); + mustClose = true; + } + + PopulationDAO populationDAO = IsisFishDAOHelper + .getPopulationDAO(tx); + String[] populationList = propertiesParameters.getProperty( + "populations", "").split(","); + for (String name : populationList) { + if (name != null && !"".equals(name)) { + try { + Population population = populationDAO.findByName(name); + populations.add(population); + + String numberAsString = propertiesParameters.getProperty("population." + name + ".number"); + List number = MatrixHelper.convertStringToList(numberAsString); + MatrixND mat = getNumberOf(population); + mat.fromList(number); + } catch (TopiaException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find population: " + name, eee); + } + } + } + } + + // si la transaction a été ouverte (pas dans une simulation) + // on la referme + if (mustClose) { + tx.closeContext(); + } + } catch (TopiaException eee1) { + if (log.isWarnEnabled()) { + log.warn("Can't get PopulationDAO", eee1); + } + } + } else { + if (log.isDebugEnabled()) { + log.debug("No last read properties, skip population reloading"); + } + } } - return this.populations; + return populations; } /** @@ -863,22 +621,176 @@ } /** + * Get instantiated strategies list. + * + * Defaut to : empty array list + * * @return Returns the strategies. */ public List<Strategy> getStrategies() { + if (strategies == null) { + strategies = new ArrayList<Strategy>(); + + if (propertiesParameters != null) { + strategies = new ArrayList<Strategy>(); + + try { + + // On verifie tout d'abord que l'on ai pas dans une simulation + // si on y es, on utilise le context static non null du thread local + // Resoud les lazy exceptions des parametres des regles + boolean mustClose = false; + TopiaContext tx = SimulationContext.get().getDB(); + + if (tx == null) { + // not in simulation, create transaction + tx = getRegion().getStorage().beginTransaction(); + mustClose = true; + } + + StrategyDAO strategyDAO = IsisFishDAOHelper.getStrategyDAO(tx); + String[] strategyList = propertiesParameters.getProperty("strategies", "").split(","); + for (String name : strategyList) { + if (name != null && !"".equals(name)) { + try { + Strategy str = strategyDAO.findByName(name); + strategies.add(str); + } catch (TopiaException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find strategy: " + name, eee); + } + } + } + } + + // si la transaction a été ouverte (pas dans une simulation) + // on la referme + if (mustClose) { + tx.closeContext(); + } + } catch (TopiaException eee1) { + if (log.isWarnEnabled()) { + log.warn("Can't get StrategyDAO", eee1); + } + } + } else { + if (log.isDebugEnabled()) { + log.debug("No last read properties, skip strategies reloading"); + } + } } - return this.strategies; + return strategies; } /** - * @param strategies The strategies to set. + * Set strategies list. + * + * @param strategies strategies list to set */ public void setStrategies(List<Strategy> strategies) { this.strategies = strategies; } + /** + * Add new analyse plan. + * + * @param plan analyse plan to add + */ + public void addAnalysePlan(AnalysePlan plan) { + getAnalysePlans().add(plan); + } + + /** + * Remove a plan. + * + * @param plan + * @return {@code true} if this list contained the specified element + */ + public boolean removeAnalysePlan(AnalysePlan plan) { + return getAnalysePlans().remove(plan); + } + + /** + * Get instantiated analyse plan list. + * + * Default to empty list. + * + * @return Returns the plans. + */ + public List<AnalysePlan> getAnalysePlans() { + if (analysePlans == null) { + + analysePlans = new ArrayList<AnalysePlan>(); + + if (propertiesParameters != null) { + // analyse plan + String[] planList = propertiesParameters.getProperty("plans", + "").split(","); + int planIndex = 0; + for (String name : planList) { + if (name != null && !"".equals(name)) { + try { + AnalysePlan plan = AnalysePlanStorage + .getAnalysePlan(name) + .getNewAnalysePlanInstance(); + populateAnalysePlan(planIndex++, plan, propertiesParameters); + analysePlans.add(plan); + } catch (IsisFishException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find plan: " + name, eee); + } + } + } + } + } else { + if (log.isDebugEnabled()) { + log.debug("No last read properties, skip plans reloading"); + } + } + } + return this.analysePlans; + } + + /** + * Set plans list. + * + * @param plans plans to set + */ + public void setAnalysePlans(List<AnalysePlan> plans) { + this.analysePlans = plans; + } + + /** + * Retrun {@code true} if simulation is composed of independant plan only. + * + * @return {@code true} if all {@link AnalysePlan} are {@link AnalysePlanIndependent} + */ + public boolean isIndependentPlan() { + boolean result = true; + for (AnalysePlan plan : getAnalysePlans()) { + if (!(plan instanceof AnalysePlanIndependent)) { + result = false; + break; + } + } + return result; + } + + /** + * Clear plan list. + */ + public void clearPlans() { + if (analysePlans != null) { + analysePlans.clear(); + } + } + + /** + * Add new rule to rules list. + * @param rule rule to add + */ public void addRule(Rule rule) { getRules().add(rule); } @@ -887,50 +799,43 @@ * Remove a rule. * * @param rule rule to remove - * @return <tt>true</tt> if this list contained the specified element + * @return {@code true} if this list contained the specified element */ public boolean removeRule(Rule rule) { return getRules().remove(rule); } - public void addAnalysePlan(AnalysePlan plan) { - getAnalysePlans().add(plan); - } - - public void removeAnalysePlan(AnalysePlan plan) { - getAnalysePlans().remove(plan); - } - /** - * Get parameters rule list. - * @return Returns the rules. + * Get parameters rules list. + * + * @return the rules */ public List<Rule> getRules() { - if (rules == null || rules.isEmpty()) { + if (rules == null) { rules = new ArrayList<Rule>(); - - if (lastReadParameters != null) { + + if (propertiesParameters != null) { try { // On verifie tout d'abord que l'on ai pas dans une simulation // si on y es, on utilise le context static non null du thread local // Resoud les lazy exceptions des parametres des regles boolean mustClose = false; TopiaContext tx = SimulationContext.get().getDB(); - + if (tx == null) { // not in simulation, create transaction tx = getRegion().getStorage().beginTransaction(); mustClose = true; } - + // rules - String[] ruleList = lastReadParameters.getProperty("rules", "").split(","); + String[] ruleList = propertiesParameters.getProperty("rules", "").split(","); int ruleIndex = 0; for (String name : ruleList) { if (name != null && !"".equals(name)) { try { Rule rule = RuleStorage.getRule(name).getNewRuleInstance(); - RuleHelper.populateRule(ruleIndex++, tx, rule, lastReadParameters); + RuleHelper.populateRule(ruleIndex++, tx, rule, propertiesParameters); rules.add(rule); } catch (IsisFishException eee) { if (log.isWarnEnabled()) { @@ -939,7 +844,7 @@ } } } - + // si la transaction a été ouverte (pas dans une simulation) // on la referme if (mustClose) { @@ -950,8 +855,7 @@ log.warn("Can't get TopiaContext", eee1); } } - } - else { + } else { if (log.isDebugEnabled()) { log.debug("No last read properties, skip rule reloading"); } @@ -961,111 +865,179 @@ } /** - * @param rules The rules to set. + * Set simulation rules. + * + * @param rules rules to set */ public void setRules(List<Rule> rules) { this.rules = rules; } /** - * @return Returns the plans. + * Clear rule list. */ - public List<AnalysePlan> getAnalysePlans() { - if (plans == null) { - plans = new ArrayList<AnalysePlan>(); + public void clearRules() { + if (rules != null) { + rules.clear(); } - return this.plans; } /** - * @param plans The plans to set. + * Return if optimization sould be used. + * + * Default to : true. + * + * @return use optimization */ - public void setAnalysePlans(List<AnalysePlan> plans) { - this.plans = plans; - } + public boolean getUseOptimization() { - /** - * @return Returns the useOptimization. - */ - public boolean getUseOptimization() { - return this.useOptimization; + if (useOptimization == null) { + if (propertiesParameters != null) { + useOptimization = Boolean.valueOf(propertiesParameters.getProperty("useOptimization", "true")); + } else { + useOptimization = Boolean.TRUE; + } + } + return useOptimization.booleanValue(); } /** - * @param useOptimization The useOptimization to set. + * Change use optimization parameter. + * + * @param useOptimization use optimization to set */ public void setUseOptimization(boolean useOptimization) { this.useOptimization = useOptimization; } /** - * @return Returns the useStatistic. + * Return if statistic sould be used. + * + * Default to false; + * + * @return use statistic */ public boolean getUseStatistic() { - return this.useStatistic; - } - - public boolean isIndependentPlan() { - boolean result = true; - for (AnalysePlan plan : getAnalysePlans()) { - if (!(plan instanceof AnalysePlanIndependent)) { - result = false; - break; + + if (useStatistic == null) { + if (propertiesParameters != null) { + useStatistic = Boolean.valueOf(propertiesParameters.getProperty("useStatistic", "false")); + } else { + useStatistic = Boolean.FALSE; } } - return result; + return this.useStatistic; } /** - * @param useStatistic The useStatistic to set. + * Change use statistic property. + * + * @param useStatistic use statistic to set */ public void setUseStatistic(boolean useStatistic) { this.useStatistic = useStatistic; } /** - * @return Returns the exportNames. + * Get export names list. + * + * @return export names list */ public List<String> getExportNames() { if (exportNames == null) { exportNames = new ArrayList<String>(); + + if (propertiesParameters != null) { + // exports + String[] exportList = propertiesParameters.getProperty("exports", "").split(","); + for (String name : exportList) { + if (name != null && !"".equals(name)) { + exportNames.add(name); + } + } + } } return this.exportNames; } /** - * @param exportNames The exportNames to set. + * Set export names list. + * + * @param exportNames export names list to set */ public void setExportNames(List<String> exportNames) { this.exportNames = exportNames; } - /** + * Get number of sensitivity simulation. + * + * Default value to : -1 + * * @return the numberOfSensitivitySimulation */ public int getNumberOfSensitivitySimulation() { - return numberOfSensitivitySimulation; + + if (numberOfSensitivitySimulation == null) { + + if (propertiesParameters != null) { + numberOfSensitivitySimulation = Integer.valueOf(propertiesParameters.getProperty( + "numberOfSensitivitySimulation", "-1")); + } else { + numberOfSensitivitySimulation = Integer.valueOf(-1); + } + } + + return numberOfSensitivitySimulation.intValue(); } /** - * @param numberOfSensitivitySimulation the numberOfSensitivitySimulation to set + * Set number of sensitivity simulation. + * + * @param numberOfSensitivitySimulation number of sensitivity simulation to set */ - public void setNumberOfSensitivitySimulation(int numberOfSensitivitySimulation) { + public void setNumberOfSensitivitySimulation( + int numberOfSensitivitySimulation) { this.numberOfSensitivitySimulation = numberOfSensitivitySimulation; } /** + * Get instanciated sensitivity calculator. + * + * Default to : null. + * * @return the sensitivityCalculator */ public SensitivityCalculator getSensitivityCalculator() { + + if (sensitivityCalculator == null) { + if (propertiesParameters != null) { + String calculatorName = propertiesParameters + .getProperty("sensitivitycalculator"); + if (!StringUtils.isEmpty(calculatorName)) { + try { + SensitivityStorage sensitivityStorage = SensitivityStorage.getSensitivity(calculatorName); + sensitivityCalculator = sensitivityStorage.getNewSensitivityInstance(); + // 0 = only single sensitivity + populateSensitivityCalculator(0, sensitivityCalculator, propertiesParameters); + } catch (IsisFishException eee) { + sensitivityCalculator = null; + if (log.isWarnEnabled()) { + log.warn("Can't find sensitivity: " + sensitivityCalculator, eee); + } + } + } + } + } + return sensitivityCalculator; } /** * @param sensitivityCalculator the sensitivityCalculator to set */ - public void setSensitivityCalculator(SensitivityCalculator sensitivityCalculator) { + public void setSensitivityCalculator( + SensitivityCalculator sensitivityCalculator) { this.sensitivityCalculator = sensitivityCalculator; } @@ -1077,31 +1049,37 @@ * @return the sensitivityExportNames */ public List<SensitivityExport> getSensitivityExport() { - if (sensitivityExports == null || sensitivityExports.isEmpty()) { + if (sensitivityExports == null) { sensitivityExports = new ArrayList<SensitivityExport>(); - if (lastReadParameters != null) { + if (propertiesParameters != null) { try { // On verifie tout d'abord que l'on ai pas dans une simulation // si on y es, on utilise le context static non null du thread local // Resoud les lazy exceptions des parametres des regles boolean mustClose = false; TopiaContext tx = SimulationContext.get().getDB(); - + if (tx == null) { // not in simulation, create transaction tx = getRegion().getStorage().beginTransaction(); mustClose = true; } - + // sensitivity export - String[] sensitivityExportList = lastReadParameters.getProperty("sensitivityexports", "").split(","); + String[] sensitivityExportList = propertiesParameters + .getProperty("sensitivityexports", "").split(","); int sensitivityExportIndex = 0; for (String name : sensitivityExportList) { try { if (!StringUtils.isEmpty(name)) { - SensitivityExport sensitivityExport = SensitivityExportStorage.getSensitivityExport(name).getNewSensitivityExportInstance(); - ExportHelper.populateSensitivityExport(sensitivityExportIndex++, tx, sensitivityExport, lastReadParameters); + SensitivityExport sensitivityExport = SensitivityExportStorage + .getSensitivityExport(name) + .getNewSensitivityExportInstance(); + ExportHelper.populateSensitivityExport( + sensitivityExportIndex++, tx, + sensitivityExport, + propertiesParameters); sensitivityExports.add(sensitivityExport); } } catch (IsisFishException eee) { @@ -1110,7 +1088,7 @@ } } } - + // si la transaction a été ouverte (pas dans une simulation) // on la referme if (mustClose) { @@ -1121,8 +1099,7 @@ log.warn("Can't get TopiaContext", eee1); } } - } - else { + } else { if (log.isDebugEnabled()) { log.debug("No last read properties, skip sensitivity exports reloading"); } @@ -1139,29 +1116,58 @@ } /** - * @return Returns the useAnalysePlan. + * Get use analyse plans property. + * + * @return use analyse plan. */ public boolean getUseAnalysePlan() { + + if (useAnalysePlan == null) { + + if (propertiesParameters != null) { + useAnalysePlan = Boolean.valueOf(propertiesParameters.getProperty("useAnalysePlan", "false")); + } else { + useAnalysePlan = Boolean.FALSE; + } + } return this.useAnalysePlan; } /** - * @param useAnalysePlan The useAnalysePlan to set. + * Set use analyse plans property. + * + * @param useAnalysePlan use analyse plan to set */ public void setUseAnalysePlan(boolean useAnalysePlan) { this.useAnalysePlan = useAnalysePlan; } /** + * Return analyse plan content. + * + * Default to "". + * * @return Returns the analysePlan. * * @deprecated since 3.2.0.7 unused */ public String getAnalysePlan() { + + if (analysePlan == null) { + + if (propertiesParameters != null) { + analysePlan = propertiesParameters.getProperty("analysePlan", ""); + } else { + analysePlan = ""; + } + } + return this.analysePlan; } /** + * Set analyse plan content. + * * @param analysePlan The analysePlan to set. * @deprecated since 3.2.0.7 unused */ @@ -1170,243 +1176,559 @@ } /** - * @return Returns the analysePlanNumber. + * Get simulation number in analyse plan. + * + * @return simulation number in analyse plan */ public int getAnalysePlanNumber() { - return this.analysePlanNumber; + + if (analysePlanNumber == null) { + + if (propertiesParameters != null) { + analysePlanNumber = Integer.valueOf(propertiesParameters.getProperty("analysePlanNumber", "-1")); + } else { + analysePlanNumber = Integer.valueOf(-1); + } + } + + return this.analysePlanNumber.intValue(); } /** - * @param analysePlanNumber The analysePlanNumber to set. + * Set simulation number in analyse plan. + * + * @param analysePlanNumber analyse plan number to set */ public void setAnalysePlanNumber(int analysePlanNumber) { this.analysePlanNumber = analysePlanNumber; } /** - * @return Returns the numberOfYear. + * Get number of year to run to simulate. + * + * @return number of year */ public int getNumberOfYear() { - return this.numberOfYear; + + if (numberOfYear == null) { + + if (propertiesParameters != null) { + numberOfYear = Integer.valueOf(propertiesParameters.getProperty("numberOfYear", "1")); + } else { + numberOfYear = Integer.valueOf(1); + } + } + return numberOfYear.intValue(); } /** - * @param numberOfYear The numberOfYear to set. + * Set number of year to run to simulate. + * + * @param numberOfYear number of year to set */ public void setNumberOfYear(int numberOfYear) { this.numberOfYear = numberOfYear; } /** + * Get use prescript. + * + * Default to false. + * * @return Returns the usePreScript. */ public boolean getUsePreScript() { - return this.usePreScript; + + if (usePreScript == null) { + + if (propertiesParameters != null) { + usePreScript = Boolean.valueOf(propertiesParameters.getProperty("usePreScript", "false")); + } else { + usePreScript = Boolean.FALSE; + } + } + + return usePreScript.booleanValue(); } /** - * @param usePreScript The usePreScript to set. + * Set use prescript property + * + * @param usePreScript use preScript to set */ public void setUsePreScript(boolean usePreScript) { this.usePreScript = usePreScript; } /** - * @return Returns the preScript. + * Get prescript content. + * + * @return preScript content */ public String getPreScript() { - return this.preScript; + + if (preScript == null) { + + if (propertiesParameters != null) { + preScript = propertiesParameters.getProperty("preScript", ""); + } else { + preScript = ""; + } + } + + return preScript; } /** - * @param preScript The preScript to set. + * Set pre script content. + * + * @param preScript prescript content */ public void setPreScript(String preScript) { this.preScript = preScript; } /** - * @return Returns the regionName. + * Get region name. + * + * @return region name */ public String getRegionName() { - return this.regionName; + + if (regionName == null) { + if (propertiesParameters != null) { + regionName = propertiesParameters.getProperty("regionName", ""); + } else { + // defaut value + regionName = ""; + } + } + + return regionName; } /** - * @param regionName The regionName to set. + * Set region name. + * + * @param regionName region name to set */ public void setRegionName(String regionName) { this.regionName = regionName; } /** - * @return Returns the simulatorName. + * Set simulator name. + * + * @return simulator name. */ public String getSimulatorName() { - return this.simulatorName; + + if (simulatorName == null) { + if (propertiesParameters != null) { + simulatorName = propertiesParameters.getProperty( + "simulatorName", "DefaultSimulator.java"); + } else { + simulatorName = "DefaultSimulator.java"; + } + } + return simulatorName; } /** - * @param simulatorName The simulatorName to set. + * Set simulator name. + * + * @param simulatorName simulator name to set */ public void setSimulatorName(String simulatorName) { this.simulatorName = simulatorName; } /** - * @return Returns the resultNotEnabled. + * Get enabled result names list. + * + * @return enabled result names list */ public Collection<String> getResultEnabled() { - return this.resultEnabled; + + if (resultEnabled == null) { + + resultEnabled = new LinkedList<String>(); + + if (propertiesParameters != null) { + String[] resultList = propertiesParameters.getProperty("resultNames", "").split(","); + for (String name : resultList) { + if (name != null && !"".equals(name)) { + resultEnabled.add(name); + } + } + } + } + return resultEnabled; } /** - * @param resultEnabled The resultNotEnabled to set. + * Set enabled result names list. + * + * @param resultEnabled enabled result names list */ public void setResultEnabled(Collection<String> resultEnabled) { this.resultEnabled = resultEnabled; } /** + * Get tag values. + * + * Default to empty map + * * @return Returns the tagValue. */ public Map<String, String> getTagValue() { - return this.tagValue; + + if (tagValue == null) { + tagValue = new LinkedHashMap<String, String>(); + + if (propertiesParameters != null) { + for (Object k : propertiesParameters.keySet()) { + if (k.toString().startsWith("tagValue.")) { + String key = k.toString().substring("tagValue.".length()); + String value = propertiesParameters.getProperty(k.toString()); + getTagValue().put(key, value); + } + } + } + } + + return tagValue; } /** - * @param tagValue The tagValue to set. + * Set tag values. + * + * @param tagValue tagValues to set. */ public void setTagValue(Map<String, String> tagValue) { this.tagValue = tagValue; } /** - * @return Returns the onlyExport. + * Get only export properties. + * + * Default to false. + * + * @return only export. */ public boolean getOnlyExport() { + + if (onlyExport == null) { + if (propertiesParameters != null) { + onlyExport = Boolean.valueOf(propertiesParameters.getProperty("onlyExport", "false")); + } else { + onlyExport = Boolean.FALSE; + } + } + return onlyExport; } /** - * @param onlyExport The onlyExport to set. + * Set only export property. + * + * @param onlyExport only export to set */ public void setOnlyExport(boolean onlyExport) { this.onlyExport = onlyExport; } /** - * @return Returns the exportDirectory. + * Get export directory path. + * + * Default to /tmp. + * + * @return export directory path */ public String getExportDirectory() { + + if (exportDirectory == null) { + + if (propertiesParameters != null) { + exportDirectory = propertiesParameters.getProperty("exportDirectory", "/tmp"); + } else { + exportDirectory = "/tmp"; + } + } return this.exportDirectory; } - + /** - * @param exportDirectory The exportDirectory to set. + * Set export directory path. + * + * @param exportDirectory export directory path. */ public void setExportDirectory(String exportDirectory) { this.exportDirectory = exportDirectory; } + /** + * Get simulator log level. + * + * Default to "info". + * + * @return simualtor log level + */ public String getSimulLogLevel() { + + if (simulLogLevel == null) { + + if (propertiesParameters != null) { + simulLogLevel = propertiesParameters.getProperty("simulLogLevel", "info"); + } else { + simulLogLevel = "info"; + } + } + return simulLogLevel; } + /** + * Set simulator log level. + * + * @param logLevel simulator log level + */ public void setSimulLogLevel(String logLevel) { - log.info(_("isisfish.params.changeLogLev",simulLogLevel ,logLevel)); + if (log.isDebugEnabled()) { + log.debug(_("isisfish.params.changeLogLev", simulLogLevel, + logLevel)); + } this.simulLogLevel = logLevel; } + /** + * Get script log level. + * + * Default to "info". + * + * @return script log level + */ public String getScriptLogLevel() { + + if (scriptLogLevel == null) { + if (propertiesParameters != null) { + scriptLogLevel = propertiesParameters.getProperty( + "scriptLogLevel", "info"); + } else { + scriptLogLevel = "info"; + } + } + return scriptLogLevel; } + /** + * Set script log level. + * + * @param logLevel script log level + */ public void setScriptLogLevel(String logLevel) { - log.info(_("isisfish.params.changeLogLev",scriptLogLevel,logLevel)); + if (log.isDebugEnabled()) { + log.debug(_("isisfish.params.changeLogLev", scriptLogLevel, + logLevel)); + } this.scriptLogLevel = logLevel; } + /** + * Get librairies log level. + * + * Default to "error". + * + * @return librairies log level + */ public String getLibLogLevel() { + if (libLogLevel == null) { + if (propertiesParameters != null) { + libLogLevel = propertiesParameters.getProperty("libLogLevel", + "error"); + } else { + libLogLevel = "info"; + } + } + return libLogLevel; } + /** + * Set lib log level. + * + * @param logLevel + */ public void setLibLogLevel(String logLevel) { - log.info(_("isisfish.params.changeLogLev",libLogLevel,logLevel)); + if (log.isDebugEnabled()) { + log.debug(_("isisfish.params.changeLogLev", libLogLevel, logLevel)); + } this.libLogLevel = logLevel; } + public boolean isSimulErrorLevel() { + return "error".equals(simulLogLevel); + } + + public boolean isSimulWarnLevel() { + return "warn".equals(simulLogLevel); + } + + public boolean isSimulInfoLevel() { + return "info".equals(simulLogLevel); + } + + public boolean isSimulDebugLevel() { + return "debug".equals(simulLogLevel); + } + + public boolean isScriptErrorLevel() { + return "error".equals(scriptLogLevel); + } + + public boolean isScriptWarnLevel() { + return "warn".equals(scriptLogLevel); + } + + public boolean isScriptInfoLevel() { + return "info".equals(scriptLogLevel); + } + + public boolean isScriptDebugLevel() { + return "debug".equals(scriptLogLevel); + } + + public boolean isLibErrorLevel() { + return "error".equals(libLogLevel); + } + + public boolean isLibWarnLevel() { + return "warn".equals(libLogLevel); + } + + public boolean isLibInfoLevel() { + return "info".equals(libLogLevel); + } + + public boolean isLibDebugLevel() { + return "debug".equals(libLogLevel); + } + /** + * A copy instance of SimulationParameter. + * * @return a copy of this instance */ public SimulationParameter copy() { SimulationParameter result = new SimulationParameter(); - result.isisFishVersion = isisFishVersion; - result.description = description; - result.regionName = regionName; - result.numberOfYear = numberOfYear; - result.simulatorName = simulatorName; - result.useOptimization = useOptimization; - result.useStatistic = useStatistic; - result.usePreScript = usePreScript; - result.preScript = preScript; - result.useAnalysePlan = useAnalysePlan; - result.analysePlan = analysePlan; - result.analysePlanNumber = analysePlanNumber; - result.onlyExport = onlyExport; - result.exportNames.addAll(exportNames); - result.exportDirectory = exportDirectory; - result.strategies.addAll(strategies) ; - result.populations.addAll(populations) ; - result.rules.addAll(getRules()) ; - result.plans.addAll(plans) ; - result.resultEnabled.addAll(resultEnabled); - result.numbers.putAll(numbers) ; - result.tagValue.putAll(tagValue) ; - result.simulLogLevel = simulLogLevel; - result.scriptLogLevel = scriptLogLevel; - result.libLogLevel = libLogLevel; - result.numberOfSensitivitySimulation = numberOfSensitivitySimulation; - result.sensitivityExports.addAll(getSensitivityExport()); + // just need to copy directory and properties now + result.directory = directory; + + if (propertiesParameters != null) { + result.propertiesParameters = new SortedProperties(); + // I think that iteration work better than parameters in contructor + result.propertiesParameters.putAll(propertiesParameters); + } + + // still needed to be copied, if there is no propertiesParameters + result.isisFishVersion = getIsisFishVersion(); + result.description = getDescription(); + result.regionName = getRegionName(); + result.numberOfYear = getNumberOfYear(); + result.simulatorName = getSimulatorName(); + result.useOptimization = getUseOptimization(); + result.useStatistic = getUseStatistic(); + result.usePreScript = getUsePreScript(); + result.preScript = getPreScript(); + result.useAnalysePlan = getUseAnalysePlan(); + result.analysePlan = getAnalysePlan(); + result.analysePlanNumber = getAnalysePlanNumber(); + result.onlyExport = getOnlyExport(); + if (exportNames != null) { + result.exportNames = new LinkedList<String>(exportNames); + } + result.exportDirectory = getExportDirectory(); + if (strategies != null) { + result.strategies = new LinkedList<Strategy>(strategies); + } + if (populations != null) { + result.populations = new LinkedList<Population>(populations); + } + if (rules != null) { + result.rules = new LinkedList<Rule>(rules); + } + if (analysePlans != null) { + result.analysePlans = new LinkedList<AnalysePlan>(analysePlans); + } + if (resultEnabled != null) { + result.resultEnabled = new LinkedList<String>(resultEnabled); + } + if (numbers != null) { + result.numbers = new HashMap<Population, MatrixND>(numbers); + } + if (tagValue != null) { + result.tagValue = new HashMap<String, String>(tagValue); + } + result.simulLogLevel = getSimulLogLevel(); + result.scriptLogLevel = getScriptLogLevel(); + result.libLogLevel = getLibLogLevel(); + result.numberOfSensitivitySimulation = getNumberOfSensitivitySimulation(); + if (sensitivityExports != null) { + result.sensitivityExports = new LinkedList<SensitivityExport>(sensitivityExports); + } result.sensitivityCalculator = sensitivityCalculator; return result; } - /* (non-Javadoc) - * @see java.lang.Object#toString() + /** + * The toString() methode call getters. + * + * So make instances of rules/export/plans... */ @Override public String toString() { StringBuffer result = new StringBuffer(); - result.append(_("isisfish.params.toString.simulation.done", getIsisFishVersion())).append('\n'); + result.append( + _("isisfish.params.toString.simulation.done", + getIsisFishVersion())).append('\n'); result.append("--------------------\n"); result.append(getDescription()).append('\n'); result.append("--------------------\n"); if (getUseAnalysePlan()) { - result.append(_("isisfish.params.toString.plan.number", getAnalysePlanNumber())); + result.append(_("isisfish.params.toString.plan.number", + getAnalysePlanNumber())); } RegionStorage region = getRegion(); result.append(_("isisfish.params.toString.fishery", region.getName())); - result.append(_("isisfish.params.toString.number.years", getNumberOfYear())); - List strs = getStrategies(); + result.append(_("isisfish.params.toString.number.years", + getNumberOfYear())); + + // startegies + List<Strategy> strs = getStrategies(); result.append(_("isisfish.params.toString.strategies")); String sep = ""; - for (Object str : strs) { - result.append(sep).append(str); + for (Strategy str : strs) { + result.append(sep).append(str.getName()); sep = ","; } result.append("\n\n"); + + // populations result.append(_("isisfish.params.toString.populations")); sep = ""; - for(Population pop : getPopulations()){ + for (Population pop : getPopulations()) { result.append(sep).append(pop.getName()); - sep =","; + sep = ","; } result.append("\n\n"); + + // rules for (Rule rule : getRules()) { String name = RuleStorage.getName(rule); String param = ""; @@ -1414,7 +1736,8 @@ param = RuleStorage.getParamAsString(rule); } catch (IsisFishException eee) { if (log.isWarnEnabled()) { - log.warn("Can't convert rule parameter to string for " + name, eee); + log.warn("Can't convert rule parameter to string for " + + name, eee); } } result.append(_("isisfish.params.toString.rule", name)); @@ -1424,6 +1747,8 @@ } result.append("\n\n"); + + // analyse plans for (AnalysePlan plan : getAnalysePlans()) { String name = RuleStorage.getName(plan); String param = ""; @@ -1431,7 +1756,8 @@ param = AnalysePlanStorage.getParamAsString(plan); } catch (IsisFishException eee) { if (log.isWarnEnabled()) { - log.warn("Can't convert plan parameter to string for " + name, eee); + log.warn("Can't convert plan parameter to string for " + + name, eee); } } result.append(_("isisfish.params.toString.plan", name)); @@ -1441,66 +1767,480 @@ } result.append('\n'); - result.append(_("isisfish.params.toString.script.presimulation")).append(":\n"); + result.append(_("isisfish.params.toString.script.presimulation")) + .append(":\n"); result.append(getPreScript()); result.append('\n'); - result.append(_("isisfish.params.toString.simul.logger.level", simulLogLevel)); + result.append(_("isisfish.params.toString.simul.logger.level", + simulLogLevel)); result.append('\n'); - result.append(_("isisfish.params.toString.script.logger.level", scriptLogLevel)); + result.append(_("isisfish.params.toString.script.logger.level", + scriptLogLevel)); result.append('\n'); - result.append(_("isisfish.params.toString.lib.logger.level", libLogLevel)); + result.append(_("isisfish.params.toString.lib.logger.level", + libLogLevel)); result.append('\n'); return result.toString(); } - public boolean isSimulErrorLevel() { - return "error".equals(simulLogLevel); - } - public boolean isSimulWarnLevel() { - return "warn".equals(simulLogLevel); - } - public boolean isSimulInfoLevel() { - return "info".equals(simulLogLevel); - } - public boolean isSimulDebugLevel() { - return "debug".equals(simulLogLevel); - } + /** + * Permet de convertir l'objet SimulationParameter en un objet Properties + * Cela permet de le stocker facilement sur le disque. + * + * Recopie certaines proprietes si elle n'ont pas été instancié : + * <ul> + * <li>strategies</li> + * <li>rules</li> + * <li>analyseplans</li> + * <li>sensitivityexports</li> + * <li>calculator</li> + * </ul> + * + * @return L'objet Properties representant les parametres + * @see #fromProperties(File, Properties) + */ + public Properties toProperties() { + Properties result = new SortedProperties(); - public boolean isScriptErrorLevel() { - return "error".equals(scriptLogLevel); - } - public boolean isScriptWarnLevel() { - return "warn".equals(scriptLogLevel); - } - public boolean isScriptInfoLevel() { - return "info".equals(scriptLogLevel); - } - public boolean isScriptDebugLevel() { - return "debug".equals(scriptLogLevel); - } + result.setProperty("isisFishVersion", getIsisFishVersion()); + result.setProperty("description", getDescription()); + result.setProperty("regionName", getRegionName()); + result.setProperty("numberOfYear", String.valueOf(getNumberOfYear())); + result.setProperty("simulatorName", getSimulatorName()); + result.setProperty("useOptimization", String.valueOf(getUseOptimization())); + result.setProperty("useStatistic", String.valueOf(getUseStatistic())); - public boolean isLibErrorLevel() { - return "error".equals(libLogLevel); - } - public boolean isLibWarnLevel() { - return "warn".equals(libLogLevel); - } - public boolean isLibInfoLevel() { - return "info".equals(libLogLevel); - } - public boolean isLibDebugLevel() { - return "debug".equals(libLogLevel); - } + // strategies + if (strategies != null) { + String strategyList = ""; + for (Strategy str : getStrategies()) { + strategyList += str.getName() + ","; + } + result.setProperty("strategies", StringUtil.substring(strategyList, 0, -1)); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("strategies")) { + result.setProperty("strategies", propertiesParameters.getProperty("strategies")); + } + } + // populations + if (populations != null) { + String populationList = ""; + for (Population pop : getPopulations()) { + populationList += pop.getName() + ","; + MatrixND number = getNumberOf(pop); + String numberAsString = String.valueOf(number.toList()); + result.setProperty("population." + pop.getName() + ".number", numberAsString); + } + result.setProperty("populations", StringUtil.substring( + populationList, 0, -1)); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("populations")) { + result.setProperty("populations", propertiesParameters.getProperty("populations")); + for (String key : propertiesParameters.stringPropertyNames()) { + if (key.startsWith("population.")) { + result.setProperty(key, propertiesParameters.getProperty(key)); + } + } + } + } - public void clearRules() { + // rules if (rules != null) { - rules.clear(); + String ruleList = ""; + int ruleIndex = 0; + for (Rule rule : getRules()) { + ruleList += RuleStorage.getName(rule) + ","; + Properties ruleProp = ruleParametertoProperties(ruleIndex++, rule); + result.putAll(ruleProp); + } + result.setProperty("rules", ruleList); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("rules")) { + result.setProperty("rules", propertiesParameters + .getProperty("rules")); + for (String key : propertiesParameters.stringPropertyNames()) { + if (key.startsWith("rule.")) { + result.setProperty(key, propertiesParameters + .getProperty(key)); + } + } + } } + + // anaylyse plans + if (analysePlans != null) { + String planList = ""; + int planIndex = 0; + for (AnalysePlan plan : getAnalysePlans()) { + planList += AnalysePlanStorage.getName(plan) + ","; + Properties planProp = planParametertoProperties(planIndex++, plan); + result.putAll(planProp); + } + result.setProperty("plans", planList); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("plans")) { + result.setProperty("plans", propertiesParameters + .getProperty("plans")); + for (String key : propertiesParameters.stringPropertyNames()) { + if (key.startsWith("plan.")) { + result.setProperty(key, propertiesParameters.getProperty(key)); + } + } + } + } + + // export names + String exportList = ""; + for (String export : getExportNames()) { + exportList += export + ","; + + } + result.setProperty("exports", exportList); + + // number of sensitivity simulation + result.setProperty("numberOfSensitivitySimulation", String + .valueOf(getNumberOfSensitivitySimulation())); + + // calculator name + if (sensitivityCalculator != null) { + String calculatorName = SensitivityStorage + .getName(getSensitivityCalculator()); + result.setProperty("sensitivitycalculator", calculatorName); + + // calculator parameter + Properties calculatorParams = sensitivityCalculatorParametertoProperties( + 0, getSensitivityCalculator()); + result.putAll(calculatorParams); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("sensitivitycalculator")) { + result.setProperty("sensitivitycalculator", + propertiesParameters.getProperty("sensitivitycalculator")); + for (String key : propertiesParameters.stringPropertyNames()) { + if (key.startsWith("sensitivity.")) { + result.setProperty(key, propertiesParameters.getProperty(key)); + } + } + } + } + + // sensitivity exports + if (sensitivityExports != null) { + String sensitivityExportList = ""; + int sensitivityExportIndex = 0; + for (SensitivityExport sensitivityExport : getSensitivityExport()) { + sensitivityExportList += SensitivityExportStorage + .getName(sensitivityExport) + ","; + Properties exportProp = sensitivityExportParametertoProperties( + sensitivityExportIndex++, sensitivityExport); + result.putAll(exportProp); + } + result.setProperty("sensitivityexports", sensitivityExportList); + } else { + if (propertiesParameters != null + && propertiesParameters.containsKey("sensitivityexports")) { + result.setProperty("sensitivityexports", propertiesParameters + .getProperty("sensitivityexports")); + for (String key : propertiesParameters.stringPropertyNames()) { + if (key.startsWith("sensitivityexport.")) { + result.setProperty(key, propertiesParameters.getProperty(key)); + } + } + } + } + + result.setProperty("usePreScript", String.valueOf(getUsePreScript())); + result.setProperty("preScript", getPreScript()); + result.setProperty("useAnalysePlan", String.valueOf(getUseAnalysePlan())); + result.setProperty("analysePlan", getAnalysePlan()); + result.setProperty("analysePlanNumber", String.valueOf(getAnalysePlanNumber())); + + String resultList = ""; + for (String r : getResultEnabled()) { + resultList += r + ","; + } + result.setProperty("resultNames", resultList); + + for (Map.Entry<String, String> e : getTagValue().entrySet()) { + result.setProperty("tagValue." + e.getKey(), e.getValue()); + } + + result.setProperty("onlyExport", String.valueOf(getOnlyExport())); + result.setProperty("exportDirectory", String.valueOf(getExportDirectory())); + + result.setProperty("simulLogLevel", getSimulLogLevel()); + result.setProperty("scriptLogLevel", getScriptLogLevel()); + result.setProperty("libLogLevel", getLibLogLevel()); + return result; } - public void clearPlans() { - if (plans!= null) { - plans.clear(); + + /** + * Load properties from file. + * + * @param directory if not null, region will be forced to this directory + * @param props property to read + */ + public void fromProperties(File directory, Properties props) { + + // save properties (use full to read again parameter) + // for exports, or rules.... + this.propertiesParameters = props; + this.directory = directory; + + // when reading new properties files, clean some information + // to force re instantion on next call + //sensitivityExports = null; + //rules = null; + + //isisFishVersion = props.getProperty("isisFishVersion", ""); + //description = props.getProperty("description", ""); + //regionName = props.getProperty("regionName", ""); + //numberOfYear = Integer.parseInt(props.getProperty("numberOfYear", "1")); + //simulatorName = props.getProperty("simulatorName", "DefaultSimulator.java"); + //useOptimization = Boolean.parseBoolean(props.getProperty( + // "useOptimization", "true")); + //useStatistic = Boolean.parseBoolean(props.getProperty("useStatistic", + // "true")); + + // FIXME not good place and code + // FIXME regionName is null + /*if (directory != null && (this.region == null || !region.getName().equals(regionName))) { + // ATTENTION: directory pointe sur le repertoire de la simulation et non de la region + this.region = new RegionStorage(directory, regionName); // RegionStorage.getRegion(directory, regionName); + }*/ + + /*try { + // On verifie tout d'abord que l'on ai pas dans une simulation + // si on y es, on utilise le context static non null du thread local + // Resoud les lazy exceptions des parametres des regles + boolean mustClose = false; + TopiaContext tx = SimulationContext.get().getDB(); + + if (tx == null) { + // not in simulation, create transaction + tx = getRegion().getStorage().beginTransaction(); + mustClose = true; + } + + // strategies + try { + StrategyDAO strategyDAO = IsisFishDAOHelper.getStrategyDAO(tx); + String[] strategyList = props.getProperty("strategies", "") + .split(","); + for (String name : strategyList) { + if (name != null && !"".equals(name)) { + try { + Strategy str = strategyDAO.findByName(name); + getStrategies().add(str); + } catch (TopiaException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find strategy: " + name, eee); + } + } + } + } + } catch (TopiaException eee1) { + if (log.isWarnEnabled()) { + log.warn("Can't get StrategyDAO", eee1); + } + } + + // populations + try { + PopulationDAO populationDAO = IsisFishDAOHelper + .getPopulationDAO(tx); + String[] populationList = props.getProperty("populations", "") + .split(","); + for (String name : populationList) { + if (name != null && !"".equals(name)) { + try { + Population population = populationDAO + .findByName(name); + getPopulations().add(population); + + String numberAsString = props + .getProperty("population." + name + + ".number"); + List number = MatrixHelper + .convertStringToList(numberAsString); + MatrixND mat = getNumberOf(population); + mat.fromList(number); + } catch (TopiaException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find population: " + name, eee); + } + } + } + } + } catch (TopiaException eee1) { + if (log.isWarnEnabled()) { + log.warn("Can't get PopulationDAO", eee1); + } + } + + tx.commitTransaction(); + + // si la transaction a été ouverte (pas dans une simulation) + // on la referme + if (mustClose) { + tx.closeContext(); + } + } catch (TopiaException eee1) { + if (log.isWarnEnabled()) { + log.warn("Can't get TopiaContext", eee1); + } + }*/ + + // analyse plan + /*String[] planList = props.getProperty("plans", "").split(","); + int planIndex = 0; + for (String name : planList) { + if (name != null && !"".equals(name)) { + try { + AnalysePlan plan = AnalysePlanStorage.getAnalysePlan(name) + .getNewAnalysePlanInstance(); + populateAnalysePlan(planIndex++, plan, props); + getAnalysePlans().add(plan); + } catch (IsisFishException eee) { + if (log.isWarnEnabled()) { + log.warn("Can't find plan: " + name, eee); + } + } + } + }*/ + + // exports + /*String[] exportList = props.getProperty("exports", "").split(","); + for (String name : exportList) { + if (name != null && !"".equals(name)) { + getExportNames().add(name); + } + }*/ + + // number of sensitivity simulation + //numberOfSensitivitySimulation = Integer.parseInt(props.getProperty( + // "numberOfSensitivitySimulation", "-1")); + // calculator name + /*String sensitivityCalculator = props.getProperty( + "sensitivitycalculator", null); + if (!StringUtils.isEmpty(sensitivityCalculator)) { + try { + SensitivityCalculator calculator = SensitivityStorage + .getSensitivity(sensitivityCalculator) + .getNewSensitivityInstance(); + // 0 = only single sensitivity + populateSensitivityCalculator(0, calculator, props); + setSensitivityCalculator(calculator); + } catch (IsisFishException eee) { + if (log.isWarnEnabled()) { + log.warn( + "Can't find sensitivity: " + sensitivityCalculator, + eee); + } + } + }*/ + + //usePreScript = Boolean.parseBoolean(props.getProperty("usePreScript", + // "false")); + //preScript = props.getProperty("preScript"); + //useAnalysePlan = Boolean.parseBoolean(props.getProperty( + // "useAnalysePlan", "false")); + //analysePlan = props.getProperty("analysePlan"); + //analysePlanNumber = Integer.parseInt(props.getProperty( + // "analysePlanNumber", "-1")); + + /*String[] resultList = props.getProperty("resultNames", "").split(","); + for (String name : resultList) { + if (name != null && !"".equals(name)) { + getResultEnabled().add(name); + } + }*/ + + /*for (Object k : props.keySet()) { + if (k.toString().startsWith("tagValue.")) { + String key = k.toString().substring("tagValue.".length()); + String value = props.getProperty(k.toString()); + getTagValue().put(key, value); + } + }*/ + + //onlyExport = Boolean.parseBoolean(props.getProperty("onlyExport", + // "false")); + + //exportDirectory = props.getProperty("exportDirectory"); + + /*simulLogLevel = props.getProperty("simulLogLevel", "info"); + scriptLogLevel = props.getProperty("scriptLogLevel", "info"); + libLogLevel = props.getProperty("libLogLevel", "info");*/ + } + + /** + * Reload parameters du to context change. + * + * ie : in simulators when rollbacking transaction + * + * Actually : reload rules parameters + * + * @throws TopiaException + */ + public void reloadContextParameters() throws TopiaException { + + // On verifie tout d'abord que l'on ai pas dans une simulation + // si on y es, on utilise le context static non null du thread local + // Resoud les lazy exceptions des parametres des regles + boolean mustClose = false; + TopiaContext tx = SimulationContext.get().getDB(); + + if (tx == null) { + // not in simulation, create transaction + tx = getRegion().getStorage().beginTransaction(); + mustClose = true; } + + // reload rules + if (log.isDebugEnabled()) { + log.debug("Reloading rules"); + } + for (Rule rule : getRules()) { + try { + for (Field field : rule.getClass().getFields()) { + // le champ ne doit pas être privé + if (Modifier.isPublic(field.getModifiers())) { + // si le type est topia entity (ou sous classe) + if (TopiaEntity.class.isAssignableFrom(field.getType())) { + TopiaEntity entity = (TopiaEntity) field.get(rule); + // il est possible que les parametres soient null + // dans ce cas, il ne faut pas essayer de les recharger + if (entity != null) { + // reloading + TopiaEntity newEntity = tx.findByTopiaId(entity + .getTopiaId()); + field.set(rule, newEntity); + } + } + } + } + } catch (IllegalArgumentException e) { + if (log.isErrorEnabled()) { + log.error("Can't refresh rule field", e); + } + } catch (IllegalAccessException e) { + if (log.isErrorEnabled()) { + log.error("Can't access rule field", e); + } + } + } + + // si la transaction a été ouverte (pas dans une simulation) + // on la referme + if (mustClose) { + tx.commitTransaction(); + tx.closeContext(); + } } } Modified: isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java =================================================================== --- isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java 2009-09-18 09:05:13 UTC (rev 2632) +++ isis-fish/trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationMonitor.java 2009-09-18 09:07:37 UTC (rev 2633) @@ -700,9 +700,9 @@ protected void analyzeSensitivityResult(SimulationJob job, SimulationStorage simulation) { - Properties props = simulation.getPropertiesParameter(); + SimulationParameter params = simulation.getParameter(); - int numberOfSimulation = Integer.parseInt(props.getProperty(SimulationParameter.NUMBER_OF_SENSITIVITY_SIMULATION)); //getNumberOfSensitivitySimulation(); + int numberOfSimulation = params.getNumberOfSensitivitySimulation(); if (numberOfSimulation > 0) { // this is a sensitivity simulation @@ -715,9 +715,6 @@ // et on l'envoie au script d'analyse de sensibilite if (numberFinished == numberOfSimulation) { - // FIXME buggy because of hack in getParameter() - // getRegion() from simulation can be locked - SimulationParameter params = simulation.getParameter(); SensitivityCalculator sensitivityCalculator = params.getSensitivityCalculator(); if (sensitivityCalculator != null) { if (log.isDebugEnabled()) { Modified: isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java =================================================================== --- isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java 2009-09-18 09:05:13 UTC (rev 2632) +++ isis-fish/trunk/src/test/java/fr/ifremer/isisfish/simulator/SimulationParameterTest.java 2009-09-18 09:07:37 UTC (rev 2633) @@ -18,13 +18,19 @@ package fr.ifremer.isisfish.simulator; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; import java.util.Properties; -import junit.framework.Assert; - +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codelutin.util.SortedProperties; +import org.junit.Assert; import org.junit.Test; import fr.ifremer.isisfish.AbstractIsisFishTest; +import fr.ifremer.isisfish.IsisConfig; /** * Simulation parameter test class. @@ -37,18 +43,60 @@ */ public class SimulationParameterTest extends AbstractIsisFishTest { + /** Logger for this class. */ + private static Log log = LogFactory.getLog(SimulationParameterTest.class); + /** + * Test les valeurs par defaut des parametres de simulations. + */ + @Test + public void testDefaultProperties() { + SimulationParameter params = new SimulationParameter(); + + Assert.assertEquals(IsisConfig.getVersion(), params.getIsisFishVersion()); + Assert.assertEquals("", params.getDescription()); + Assert.assertEquals("", params.getRegionName()); + Assert.assertEquals(1, params.getNumberOfYear()); + Assert.assertEquals("DefaultSimulator.java", params.getSimulatorName()); + Assert.assertTrue(params.getUseOptimization()); + Assert.assertFalse(params.getUseStatistic()); + Assert.assertTrue(params.getStrategies().isEmpty()); + Assert.assertTrue(params.getPopulations().isEmpty()); + // Not easy to test it + //Assert.assertNotNull(params.getNumberOf(new PopulationImpl())); + Assert.assertTrue(params.getRules().isEmpty()); + Assert.assertTrue(params.getExtraRules().isEmpty()); + Assert.assertTrue(params.getAnalysePlans().isEmpty()); + Assert.assertTrue(params.getExportNames().isEmpty()); + Assert.assertEquals("/tmp", params.getExportDirectory()); + Assert.assertFalse(params.getUsePreScript()); + Assert.assertEquals("", params.getPreScript()); + Assert.assertFalse(params.getUseAnalysePlan()); + Assert.assertEquals(-1, params.getAnalysePlanNumber()); + Assert.assertTrue(params.getSensitivityExport().isEmpty()); + Assert.assertEquals(-1, params.getNumberOfSensitivitySimulation()); + Assert.assertNull(params.getSensitivityCalculator()); + Assert.assertTrue(params.getResultEnabled().isEmpty()); + Assert.assertTrue(params.getTagValue().isEmpty()); + Assert.assertFalse(params.getOnlyExport()); + Assert.assertEquals("info", params.getSimulLogLevel()); + Assert.assertEquals("info", params.getScriptLogLevel()); + Assert.assertEquals("error", params.getLibLogLevel()); + } + + /** * Test to build one simulation parameters. * * Write it on disk, read it from disk. * And test it.s */ @Test - public void testToPropertiesFromPropertties() { + public void testToPropertiesFromProperties() { SimulationParameter params = new SimulationParameter(); params.setIsisFishVersion("3.2.0.4"); params.setDescription("desc"); + params.setResultEnabled(Collections.singleton("bakh")); // make transform Properties props = params.toProperties(); @@ -57,6 +105,168 @@ Assert.assertEquals("3.2.0.4", params2.getIsisFishVersion()); Assert.assertEquals("desc", params2.getDescription()); + Assert.assertEquals(1, params2.getResultEnabled().size()); } + /** + * Test de lecture d'un fichier existant. + * + * Test que les valeurs string sont correcte. + * Et que les instances regles/export... sont correctes. + * + * Cas 1 : file basic + * @throws IOException + */ + @Test + public void testBasicFilePropertiesLoading() throws IOException { + + InputStream basicFileStream = SimulationParameterTest.class.getResourceAsStream("parameters_basic.properties"); + + Properties props = new SortedProperties(); + props.load(basicFileStream); + SimulationParameter param = new SimulationParameter(); + param.fromProperties(null, props); + + Assert.assertEquals("3.2.0.6", param.getIsisFishVersion()); + + // test des regles + Assert.assertNull(param.rules); + Assert.assertEquals(2, param.getRules().size()); + Assert.assertNotNull(param.rules); + + // test des exports + Assert.assertNull(param.exportNames); + + // test des export de sensibilité + Assert.assertNull(param.sensitivityExports); + Assert.assertEquals(0, param.getSensitivityExport().size()); + Assert.assertNotNull(param.sensitivityExports); + } + + /** + * Test une copies de simulation parameters sans instancier + * les regles, export, plans... pour verifier qu'il ne perde pas + * les informations des paramètres sur lesquels getxxx() n'a pas été + * appelé. + * @throws IOException + */ + @Test + public void testBasicFilePropertiesCopyWithoutInstancation() throws IOException { + InputStream basicFileStream = SimulationParameterTest.class.getResourceAsStream("parameters_basic.properties"); + + Properties props = new SortedProperties(); + props.load(basicFileStream); + SimulationParameter param = new SimulationParameter(); + param.fromProperties(null, props); + + Properties props2 = param.toProperties(); + SimulationParameter param2 = new SimulationParameter(); + param2.fromProperties(null, props2); + + // test rules + Assert.assertNull(param.rules); + Assert.assertEquals(2, param2.getRules().size()); + + // test analyse plans + Assert.assertNull(param.analysePlans); + Assert.assertEquals(0, param2.getAnalysePlans().size()); + + // test sur les populations + Assert.assertNull(param.populations); + Assert.assertEquals(1, param2.getPopulations().size()); + } + + /** + * Test de copie, avec une classe manquante dans le config. + * L'intanciation de la classe ne doit pas etre appelée. + * Et la configuration de la classe doit être copiée. + * + * @throws IOException + */ + @Test + public void testPlanFileWithMissingClasses() throws IOException { + InputStream basicFileStream = SimulationParameterTest.class.getResourceAsStream("parameters_plan.properties"); + + Properties props = new SortedProperties(); + props.load(basicFileStream); + SimulationParameter param = new SimulationParameter(); + param.fromProperties(null, props); + + Properties props2 = param.toProperties(); + SimulationParameter param2 = new SimulationParameter(); + param2.fromProperties(null, props2); + + // test analyse plans + Assert.assertNull(param.analysePlans); + Assert.assertTrue(param2.propertiesParameters.containsKey("plans")); + // ca rend zero parce que l'instanciation doit echouer + Assert.assertEquals(0, param2.getAnalysePlans().size()); + } + + /** + * Test toString() method. + * + * @throws IOException + */ + @Test + public void testSimulationParametersCopy() throws IOException { + InputStream basicFileStream = SimulationParameterTest.class.getResourceAsStream("parameters_basic.properties"); + + Properties props = new SortedProperties(); + props.load(basicFileStream); + SimulationParameter param = new SimulationParameter(); + param.fromProperties(null, props); + + // force some properties instantiation + param.getAnalysePlans(); + param.getStrategies(); + // not populations + + SimulationParameter param2 = param.copy(); + + Assert.assertEquals("3.2.0.6", param2.getIsisFishVersion()); + Assert.assertEquals("Done for unit testing", param2.getDescription()); + // test some collections + Assert.assertEquals(0, param2.getAnalysePlans().size()); + Assert.assertEquals(1, param2.getPopulations().size()); + Assert.assertEquals(3, param2.getStrategies().size()); + } + + /** + * Test toString() method. + * + * @throws IOException + */ + @Test + public void testSimulationParametersToString() throws IOException { + InputStream basicFileStream = SimulationParameterTest.class.getResourceAsStream("parameters_basic.properties"); + + Properties props = new SortedProperties(); + props.load(basicFileStream); + + SimulationParameter param = new SimulationParameter(); + param.fromProperties(null, props); + + String toString = param.toString(); + if (log.isInfoEnabled()) { + log.info("toString() result is : " + toString); + } + } + + /** + * Test copy method without setting internals paroperties. + */ + @Test + public void testCopyWithoutPropertiesLoad() { + SimulationParameter params = new SimulationParameter(); + params.setIsisFishVersion("3.2.0.4"); + params.setDescription("desc"); + params.setResultEnabled(Collections.singleton("bakh")); + + SimulationParameter params2 = params.copy(); + + Assert.assertEquals("3.2.0.4", params2.getIsisFishVersion()); + Assert.assertEquals("desc", params2.getDescription()); + Assert.assertEquals(1, params2.getResultEnabled().size()); + } } Added: isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties =================================================================== --- isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties (rev 0) +++ isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_basic.properties 2009-09-18 09:07:37 UTC (rev 2633) @@ -0,0 +1,34 @@ +#Parameters +#Wed Sep 16 12:01:08 CEST 2009 +libLogLevel=error +sensitivityexports= +numberOfSensitivitySimulation=-1 +preScript= +usePreScript=false +onlyExport=false +rule.1.parameter.gear=fr.ifremer.isisfish.entities.Gear\#1179302919571\#0.05429698852124787 +numberOfYear=4 +rule.1.parameter.zone=fr.ifremer.isisfish.entities.Zone\#1169028645759\#0.8226513521396226 +scriptLogLevel=info +simulLogLevel=info +rules=GraviteVPUE1,Cantonnement, +useOptimization=true +useStatistic=false +exportDirectory=/home/chatellier/isis-export +useAnalysePlan=false +isisFishVersion=3.2.0.6 +rule.1.parameter.endMonth=10 +rule.1.parameter.endDate=118 +regionName=BaseMotosICA +rule.1.parameter.beginDate=1 +populations=Anchois_long +description=Done for unit testing +analysePlan= +rule.1.parameter.beginMonth=1 +population.Anchois_long.number=[[10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 2000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0]] +plans= +simulatorName=DefaultSimulator.java +strategies=Espagnols,BolBretons,PelProfil1 +analysePlanNumber=-1 +exports=EffortsMetier.java, +resultNames=matrixGrossValueOfLandingsPerStrategyMet, Added: isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties =================================================================== --- isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties (rev 0) +++ isis-fish/trunk/src/test/resources/fr/ifremer/isisfish/simulator/parameters_plan.properties 2009-09-18 09:07:37 UTC (rev 2633) @@ -0,0 +1,34 @@ +#Parameters +#Wed Sep 16 12:01:08 CEST 2009 +libLogLevel=error +sensitivityexports= +numberOfSensitivitySimulation=-1 +preScript= +usePreScript=false +onlyExport=false +rule.1.parameter.gear=fr.ifremer.isisfish.entities.Gear\#1179302919571\#0.05429698852124787 +numberOfYear=4 +rule.1.parameter.zone=fr.ifremer.isisfish.entities.Zone\#1169028645759\#0.8226513521396226 +scriptLogLevel=info +simulLogLevel=info +rules=GraviteVPUE1,Cantonnement, +useOptimization=true +useStatistic=false +exportDirectory=/home/chatellier/isis-export +useAnalysePlan=true +isisFishVersion=3.2.0.6 +rule.1.parameter.endMonth=11 +rule.1.parameter.endDate=119 +regionName=BaseMotosICA +rule.1.parameter.beginDate=0 +populations=Anchois_long +description=Done for unit testing (plan) +analysePlan=TestCapturabiliteUnavailable +rule.1.parameter.beginMonth=0 +population.Anchois_long.number=[[10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 5000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 2000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0], [10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0, 10000.0]] +plans=TestCapturabiliteUnavailable +simulatorName=DefaultSimulator.java +strategies=Espagnols,BolBretons,PelProfil1 +analysePlanNumber=-1 +exports=EffortsMetier.java, +resultNames=matrixGrossValueOfLandingsPerStrategyMet, Added: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.1.log.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.1.log.db ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.data.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.data.db ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.index.db =================================================================== (Binary files differ) Property changes on: isis-fish/trunk/src/test/resources/test-database/regions/BaseMotosICA/data/data.index.db ___________________________________________________________________ Added: svn:mime-type + application/octet-stream
participants (1)
-
chatellier@users.labs.libre-entreprise.org