r2851 - in trunk/lima-swing: . src/main/java/org/chorem/lima src/main/java/org/chorem/lima/actions src/main/java/org/chorem/lima/util
Author: echatellier Date: 2010-04-09 18:21:50 +0200 (Fri, 09 Apr 2010) New Revision: 2851 Log: Misc refactoring an updates (splash, actions, useless code) Added: trunk/lima-swing/src/main/java/org/chorem/lima/LimaMain.java trunk/lima-swing/src/main/java/org/chorem/lima/actions/ trunk/lima-swing/src/main/java/org/chorem/lima/actions/MiscAction.java trunk/lima-swing/src/main/java/org/chorem/lima/util/ErrorHelper.java Removed: trunk/lima-swing/src/main/java/org/chorem/lima/DataManager.java trunk/lima-swing/src/main/java/org/chorem/lima/LimaAction.java trunk/lima-swing/src/main/java/org/chorem/lima/Main.java trunk/lima-swing/src/main/java/org/chorem/lima/util/ServiceHelper.java Modified: trunk/lima-swing/pom.xml trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java trunk/lima-swing/src/main/java/org/chorem/lima/LimaContext.java trunk/lima-swing/src/main/java/org/chorem/lima/LimaSplash.java Modified: trunk/lima-swing/pom.xml =================================================================== --- trunk/lima-swing/pom.xml 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/pom.xml 2010-04-09 16:21:50 UTC (rev 2851) @@ -59,6 +59,21 @@ <artifactId>jdom</artifactId> </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-email</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.openejb</groupId> + <artifactId>openejb-core</artifactId> + </dependency> + + <!-- for remote mode only --> + <dependency> + <groupId>org.apache.openejb</groupId> + <artifactId>openejb-client</artifactId> + </dependency> </dependencies> <!-- ************************************************************* --> @@ -72,11 +87,6 @@ <!-- *** Build Settings ****************************************** --> <!-- ************************************************************* --> <properties> - - <!-- jaxx configuration - <jaxx.addProjectClassPath>true</jaxx.addProjectClassPath> - <jaxx.addSourcesToClassPath>true</jaxx.addSourcesToClassPath>--> - <!--Main class in JAR --> <maven.jar.main.class>org.chorem.lima.Main</maven.jar.main.class> @@ -109,6 +119,10 @@ <plugin> <groupId>org.nuiton.jaxx</groupId> <artifactId>maven-jaxx-plugin</artifactId> + <configuration> + <addCompileClassPath>true</addCompileClassPath> + <addProjectClassPath>true</addProjectClassPath> + </configuration> <executions> <execution> <goals> @@ -123,7 +137,6 @@ <artifactId>maven-i18n-plugin</artifactId> <executions> <execution> - <id>java</id> <configuration> <entries> <entry> @@ -133,7 +146,7 @@ </configuration> <goals> <goal>parserJava</goal> - <goal>bundle</goal> + <goal>gen</goal> </goals> </execution> </executions> Deleted: trunk/lima-swing/src/main/java/org/chorem/lima/DataManager.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/DataManager.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/DataManager.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,243 +0,0 @@ -/** - * *##% Lima Main - * Copyright (C) 2008 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima; - -import java.util.List; - -import org.chorem.lima.dto.AccountDTO; -import org.chorem.lima.dto.JournalDTO; -import org.chorem.lima.dto.PeriodDTO; -import org.chorem.lima.dto.StatusDTO; -import org.chorem.lima.dto.TransactionDTO; -import org.chorem.lima.service.PeriodService; -import org.chorem.lima.service.ServiceFactory; -import org.chorem.lima.service.util.ProgressListener; -import org.chorem.lima.service.util.ServiceHelper; -import org.chorem.lima.table.model.ClosureTableModel; -import org.chorem.lima.table.model.JournalTableModel; -import org.chorem.lima.table.model.TransactionDataTableModel; -import org.chorem.lima.tree.model.AccountTreeTableModel; - -/** - * Cette classe permet de gérer les données de Lima. Chaque type de données - * peut être récupéré. Certaines données peuvent être retourner sous forme - * de model (essentiellement pour les données en tableau). - * Exemple : pour récupérer les transactions, il suffit d'appeler la méthode - * getTransactionModel, qui ensuite possède une méthode pour récuper les données - * sous forme de liste. - * - * @author ore - * @author Rémi Chapelet - */ -public class DataManager { - - protected ClosureTableModel closureModel; - protected JournalTableModel journalModel; - protected AccountTreeTableModel accountModel; - protected TransactionDataTableModel transactionModel; - protected List<PeriodDTO> periodes; - protected List<StatusDTO> status; - protected JournalDTO currentJournal; - protected PeriodDTO currentPeriod; - - /** - * Constructor - */ - public DataManager() { - } - - /** - * @return - */ - public JournalTableModel getJournalModel() { - if (journalModel == null) { - /** Services */ - List<JournalDTO> journals = LimaContext.getContext().getNeogiaFactory().getJournalService().getAllJournal(); - journalModel = new JournalTableModel(journals); - } - return journalModel; - } - - /** - * @return - */ - public ClosureTableModel getClosureModel() { - if (closureModel == null) { - /** Services */ - // Création de la liste des périodes - List<PeriodDTO> listPeriodDTO = LimaContext.getContext().getNeogiaFactory().getPeriodService().getAllPeriod(getStatus()); - // Parcourt toutes les périodes (2007 / 2008 / etc) - for (PeriodDTO period : getPeriodes()) - { - // Parcourt toutes les périodes mensuelles pour chaque exercice - for (PeriodDTO periodChild : period.getChildren()) - { - listPeriodDTO.add(periodChild); - } - } - closureModel = new ClosureTableModel(listPeriodDTO); - } - return closureModel; - } - - /** - * @return - */ - public AccountTreeTableModel getAccountModel() { - if (accountModel == null) { - /** Services */ - AccountDTO account = LimaContext.getContext().getNeogiaFactory().getAccountService().getAllAccount(); - accountModel = new AccountTreeTableModel(account); - } - return accountModel; - } - - public AccountTreeTableModel resetAccountModel() { - /** Services */ - AccountDTO account = LimaContext.getContext().getNeogiaFactory().getAccountService().getAllAccount(); - accountModel = new AccountTreeTableModel(account); - return accountModel; - } - - public AccountTreeTableModel resetAccountModel(AccountDTO account) { - /** Services */ - accountModel = new AccountTreeTableModel(account); - return accountModel; - } - - /** - * @return - */ - public TransactionDataTableModel getTransactionModel() { - - - if (transactionModel == null) { - /** Services */ - List<TransactionDTO> data = LimaContext.getContext().getNeogiaFactory().getTransactionService().getAllTransaction( - ServiceHelper.getAllFlatPeriod( - getPeriodes()), - getJournalModel().getData(), - ServiceHelper.getAllFlatAccount(getAccountModel().getData()), - getStatus(), null); - transactionModel = new TransactionDataTableModel(data); - } - return transactionModel; - } - - public TransactionDataTableModel getTransactionModel(ProgressListener progressListener) { - - - if (transactionModel == null) { - /** Services */ - List<TransactionDTO> data = LimaContext.getContext().getNeogiaFactory().getTransactionService().getAllTransaction( - ServiceHelper.getAllFlatPeriod( - getPeriodes()), - getJournalModel().getData(), - ServiceHelper.getAllFlatAccount(getAccountModel().getData()), - getStatus(), progressListener); - transactionModel = new TransactionDataTableModel(data); - } - return transactionModel; - } - - - /** - * Permet de relancer le model des transactions. Il a besoin en entrée de - * la liste des transactions à charger dans Lima. Cette méthode peut être - * utilisée dans le cas d'un import de données par exemple. - * @param listTransactions - * @return - */ - public TransactionDataTableModel resetTransactionModel (List<TransactionDTO> listTransactions) { - transactionModel = new TransactionDataTableModel(listTransactions); - return transactionModel; - } - - /** - * @return - */ - public List<PeriodDTO> getPeriodes() { - if (periodes == null) { - /** Services */ - LimaContext context = LimaContext.getContext(); - ServiceFactory factory = context.getNeogiaFactory(); - PeriodService periodService =factory.getPeriodService(); - status = getStatus(); - periodes= periodService.getAllPeriod(status); -// periodes = LimaContext.getContext().getNeogiaFactory().getPeriodService().getAllPeriod( -// getStatus()); - } - return periodes; - } - - public List<PeriodDTO> resetPeriodes() { - periodes.clear(); - periodes = LimaContext.getContext().getNeogiaFactory().getPeriodService().getAllPeriod( - getStatus()); - return periodes; - } - - public List<PeriodDTO> resetPeriodes(List<PeriodDTO> listPeriodes) { - periodes.clear(); - periodes = listPeriodes; - return periodes; - } - - /** - * @return - */ - public List<StatusDTO> getStatus() { - if (status == null) { - /** Services */ - status = LimaContext.getContext().getNeogiaFactory().getStatusService().getAllStatus(); - } - return status; - } - - /** - * - */ - public void reset() { - journalModel = null; - accountModel = null; - transactionModel = null; - periodes = null; - } - - public JournalDTO getCurrentJournal() { - return currentJournal == null ? getJournalModel().getData().get(0) : currentJournal; - } - - public void setCurrentJournal(JournalDTO currentJournal) { - this.currentJournal = currentJournal; - } - - public PeriodDTO getCurrentPeriod() { - return (currentPeriod == null && !getPeriodes().isEmpty()) ? getPeriodes().get(0) : currentPeriod; - } - - public void setCurrentPeriod(PeriodDTO currentPeriod) { - this.currentPeriod = currentPeriod; - } - - public boolean isPeriodSelected() { - return currentPeriod != null; - } -} Deleted: trunk/lima-swing/src/main/java/org/chorem/lima/LimaAction.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaAction.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaAction.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,59 +0,0 @@ -package org.chorem.lima; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Les actions appellables via {@link Main}. - * - * @author tony - */ -public class LimaAction { - - /** - * to use log facility, just put in your code: log.info(\"...\"); - */ - static private Log log = LogFactory.getLog(LimaAction.class); - /** - * La configuration de l'application. - */ - protected LimaConfig config; - - public LimaAction() { - } - - public LimaAction(LimaConfig config) { - this.config = config; - } - - public void help() { - System.out.println("observe.message.help.usage"); - System.out.println("Options (set with --option <key> <value>:"); - for (LimaConfig.Option o : LimaConfig.Option.values()) { - System.out.println("\t" + o.key + "(" + o.defaultValue + "):" + o.description); - } - - System.out.println("Actions:"); - for (LimaConfig.Action a : LimaConfig.Action.values()) { - System.out.println("\t" + java.util.Arrays.toString(a.aliases) + "(" + a.action + "):" + a.description); - } - } - - /** - * Désactiver la possiblite de lancer l'ui principale. - */ - public void disableMainUI() { - if (log.isDebugEnabled()) { - log.debug(this); - } - getConfig().setDisplayMainUI(false); - } - - protected LimaConfig getConfig() { - if (config == null) { - LimaContext context = LimaContext.getContext(); - config = context.getConfig(); - } - return config; - } -} Modified: trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaConfig.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,155 +1,177 @@ +/* *##% Lima Swing + * Copyright (C) 2008 - 2010 CodeLutin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * ##%*/ + package org.chorem.lima; +import static org.nuiton.i18n.I18n._; + import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.InputStream; +import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import static org.nuiton.i18n.I18n._; -import org.nuiton.util.FileUtil; +import org.chorem.lima.actions.MiscAction; +import org.nuiton.util.ApplicationConfig; +import org.nuiton.util.ArgumentsParserException; +import org.nuiton.util.ConverterUtil; import org.nuiton.util.Version; - -import java.io.File; -import java.util.Locale; -import java.util.Properties; - -import org.nuiton.util.ConverterUtil; import org.nuiton.util.VersionUtil; /** * La configuration de l'application. - * <p/> - * TODO ajouter d'autres propriete pour controler quel storage est utilise - * et quel est son type (local ou pas). * * @author chemit + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ */ -public class LimaConfig extends org.nuiton.util.ApplicationConfig { +public class LimaConfig extends ApplicationConfig { /** * to use log facility, just put in your code: log.info(\"...\"); */ static private Log log = LogFactory.getLog(LimaConfig.class); + /** - * La version du logiciel constitue de l.d.r - * <li>l: le numero de version du logiciel - * <li>d: le numero de version du schema de la base de donnees - * <li>r: le numero de version de de l'interface graphique ou autre modif mineur - * <p/> - * lors de l'increment de l, d et r sont remis a 0 - * lors de l'increment de d et r sont remis a 0 - * lors de l'increment de r est remis a 0 - * <p/> - * Un changement d'UI ne modifie jamais le numero de version de database - * Un changement de schema de base pour lequel on ne peut pas faire de - * migration de donnees demande automatiquement un changement de version - * d'application. + * La version du logiciel. */ - protected final Version version; - public static final String APPLICATION_PROPERTIES = "/lima.properties"; - public static final String USER_DIRECTORY_FILENAME = ".lima"; + protected Version version; + /** - * le repertoire utilisateur principale + * Get copyrighy text (include version). + * + * @return copyright text */ - protected static File observeUserDirectory; - public String getCopyrightText() { return "Version " + getVersion() + " Codelutin @ 2008-2010"; } /** + * Version as string. + * * @return le nombre global ex: 3.2.0.0 */ public String getVersion() { return version.toString(); } - public static File getLimaUserDirectory() { - if (observeUserDirectory == null) { - observeUserDirectory = new File(new File(LimaConfig.getUserHome()), USER_DIRECTORY_FILENAME); - } - return observeUserDirectory; - } - /** - * un drepeau pour savoir s'il faut lancer l'interface graphique. - * Cette valeur peut être programmées lors des actions. + * Lima config constructor. + * + * Define all default options and action alias. */ - private boolean displayMainUI = true; - /** - * drapeau pour savoir si on peut utiliser des ui dans l'environnement. - * <p/> - * Par defaut, on suppose qu'on peut utiliser l'environnement graphique - * et si on désactive explicitement si pas d'environnement graphique trouvé. - */ - private boolean canUseUI = true; - public LimaConfig() { - setConfigFileName(Option.CONFIG_FILE.defaultValue); - - // chargement de la configuration interne - - InputStream stream = getClass().getResourceAsStream(APPLICATION_PROPERTIES); - - Properties p = new Properties(); - try { - p.load(stream); - for (Object k : p.keySet()) { - String key = k + ""; - Object value = p.get(k); - if (log.isDebugEnabled()) { - log.debug("install properties " + k + " : " + value); - } - setDefaultOption(key, "" + value); - } - } catch (IOException ex) { - throw new RuntimeException(ex); - } - + // set defaut option (included configuration file name : important) for (Option o : Option.values()) { setDefaultOption(o.key, o.defaultValue); } - // on supprime tout ce qui est apres - (-SNAPSHOT, -rc-1 ,...) - //TODO Il faut que VersionNumber gère les versions plus évoluée (alpha-x beta-x rc-x,...) - String sVersion = VersionUtil.removeSnapshot(getOption("application.version")); - version = VersionUtil.valueOf(sVersion); - - // initialisation des répertoires - FileUtil.setCurrentDirectory(getLimaUserDirectory()); - - getLimaUserDirectory().mkdirs(); - + // set action alias for (Action a : Action.values()) { for (String alias : a.aliases) { addActionAlias(alias, a.action); } } - log.info(_("lima.message.config.loaded", version)); + // ajout des alias (can be set in option enum ?) + addAlias("--disableui", "--launchui false"); + + // initialisation des répertoires + // TODO what is it for ? + //FileUtil.setCurrentDirectory(getLimaUserDirectory()); + //getLimaUserDirectory().mkdirs(); } - public boolean isFullScreen() { - Boolean result = getOptionAsBoolean(Option.FULL_SCREEN.key); - return result != null && result; + /* + * @see org.nuiton.util.ApplicationConfig#parse(java.lang.String[]) + */ + @Override + public void parse(String[] args) throws ArgumentsParserException { + + // super parse, read config file etc... + super.parse(args); + + // on ne peut pas connaitre la version avant la lecture du fichier + // on supprime tout ce qui est apres - (-SNAPSHOT, -rc-1 ,...) + String sVersion = VersionUtil.removeSnapshot(getOption("application.version")); + version = VersionUtil.valueOf(sVersion); + } + /** + * Get application locale. + * + * @return configuration application locale + */ public Locale getLocale() { String local = getOption(Option.LOCALE.key); Locale result = ConverterUtil.convert(Locale.class, local); return result; } - public boolean isDisplayMainUI() { - return displayMainUI; + /** + * Locale setter for command line parameters. + * + * @param locale new locale + */ + public void setLocale(String locale) { + setOption(Option.LOCALE.key, locale); } - public boolean isCanUseUI() { - return canUseUI; + /** + * Change locale (not command line version). + * Save user file. + * + * @param newLocale new locale + */ + public void setLocale(Locale newLocale) { + setOption(Option.LOCALE.key, newLocale.toString()); + saveForUser(); + firePropertyChange("locale", null, newLocale); } + /** + * Launch ui configuration value. + * + * @return {@code true} if ui must be displayed + */ + public boolean isLaunchui() { + boolean launchUI = getOptionAsBoolean(Option.LAUNCH_UI.key); + return launchUI; + } + + /** + * Launch ui setter for command line parameters. + * + * @param launchui new lauch ui value + */ + public void setLaunchui(String launchui) { + setOption(Option.LAUNCH_UI.key, launchui); + } + + /** + * Change full screen mode. + * Save user file. + * + * @param fullscreen new fullscreen mode + */ public void setFullscreen(boolean fullscreen) { boolean oldValue = isFullScreen(); setOption(Option.FULL_SCREEN.key, fullscreen + ""); @@ -157,38 +179,40 @@ firePropertyChange("fullscreen", oldValue, fullscreen); } - public void setDisplayMainUI(boolean b) { - displayMainUI = b; + public boolean isFullScreen() { + Boolean result = getOptionAsBoolean(Option.FULL_SCREEN.key); + return result != null && result; } - public void setCanUseUI(boolean canUseUI) { - this.canUseUI = canUseUI; - if (!canUseUI) { - // on ne pourra pas lancer l'ui principale - setDisplayMainUI(false); - } + /** + * Get support email address. + * + * @return support email + */ + public String getSupportEmail() { + return getOption(Option.SUPPORT_EMAIL.key); } - public void setLocale(Locale newLocale) { - setOption(Option.LOCALE.key, newLocale.toString()); - saveForUser(); - firePropertyChange("locale", null, newLocale); + /** + * Return true if ejb mode is configured as remote. + * + * @return {@code true} if remote mode should be used + */ + public boolean isEJBRemoteMode() { + boolean result = getOptionAsBoolean(Option.OPENEJB_REMOTEMODE.key); + return result; } /** - * Save configuration, in user home directory using the - * {@link #getConfigFileName}. Default, env and commande line note saved + * Used in ???? */ - public void saveForUser() { - super.saveForUser(); - } + public static final String[] DEFAULT_JAXX_PCS = { "fullScreen", "locale" }; - public static final String[] DEFAULT_JAXX_PCS = { - "fullScreen", "locale" - }; - + /** + * Used in ???? + */ public void removeJaxxPropertyChangeListener() { - PropertyChangeListener[] toRemove = jaxx.runtime.Util.findJaxxPropertyChangeListener(DEFAULT_JAXX_PCS, getPropertyChangeListeners()); + PropertyChangeListener[] toRemove = jaxx.runtime.JAXXUtil.findJaxxPropertyChangeListener(DEFAULT_JAXX_PCS, getPropertyChangeListeners()); if (toRemove == null || toRemove.length == 0) { return; } @@ -205,17 +229,22 @@ } } - ////////////////////////////////////////////////// - // Toutes les options disponibles - ////////////////////////////////////////////////// + /** + * Lima option definition. + * + * Contains all lima configuration key, with defaut value and + * information for jaxx configuration frame ({@link #type}, + * {@link #_transient}, {@link #_final}...) + */ public static enum Option implements OptionDef { - CONFIG_FILE(CONFIG_FILE_NAME, _("lima.config.configFileName.description"), "lima-config", String.class, true, true), - // directories + CONFIG_FILE(CONFIG_FILE_NAME, _("lima.config.configFileName.description"), "lima-config.properties", String.class, true, true), + LOCALE("locale", _("lima.config.locale.description"), "fr_FR", Locale.class, false, false), + FULL_SCREEN("lima.ui.fullscreen", _("lima.config.ui.fullscreen.description"), "false", Boolean.class, false, false), + LAUNCH_UI("lima.ui.launchui", _("lima.config.ui.flaunchui.description"), "true", Boolean.class, true, true), + SUPPORT_EMAIL("lima.misc.supportemail", _("lima.misc.supportemail.description"), "", String.class, false, false), + OPENEJB_REMOTEMODE("lima.openejb.remotemode", _("lima.openejb.remotemode.description"), "false", String.class, false, false); - LOCALE("locale", _("lima.config.locale.description"), "fr_FR", Locale.class, false, false), - // ui config - FULL_SCREEN("ui.fullscreen", _("lima.config.ui.fullscreen"), "false", Boolean.class, false, false); public final String key; public final String description; public final String defaultValue; @@ -223,7 +252,8 @@ public final boolean _transient; public final boolean _final; - private Option(String key, String description, String defaultValue, Class<?> type, boolean _transient, boolean _final) { + private Option(String key, String description, String defaultValue, + Class<?> type, boolean _transient, boolean _final) { this.key = key; this.description = description; this.defaultValue = defaultValue; @@ -262,14 +292,19 @@ return type; } } - - public static final int AFTER_INIT_STEP = 0; - public static final int BEFORE_EXIT_STEP = 1; + /** + * Lima action definition. + */ public static enum Action { - HELP(_("lima.action.commandline.help"), LimaAction.class.getName() + "#help", "-h", "--help"), - NO_MAIN_UI(_("lima.action.commandline.disable.main.ui"), LimaAction.class.getName() + "#disableMainUI", "-n", "--no-main"); + HELP(_("lima.action.commandline.help"), MiscAction.class.getName() + "#help", "-h", "--help"); + + /** Before init action step. */ + public static final int BEFORE_EXIT_STEP = 0; + /** After init action step. */ + public static final int AFTER_INIT_STEP = 1; + public String description; public String action; public String[] aliases; Modified: trunk/lima-swing/src/main/java/org/chorem/lima/LimaContext.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaContext.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaContext.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,33 +1,29 @@ -/** - * *##% Lima Main - * Copyright (C) 2008 CodeLutin +/* *##% Lima Swing + * Copyright (C) 2008 - 2010 CodeLutin * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. + * GNU General Public License for more details. * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * ##%*/ package org.chorem.lima; -import jaxx.runtime.Util; +import jaxx.runtime.JAXXUtil; import jaxx.runtime.context.JAXXContextEntryDef; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.chorem.lima.dto.util.DTOHelper; -import org.chorem.lima.service.ServiceFactory; import org.chorem.lima.ui.MainView; import org.chorem.lima.ui.MainViewHandler; -import org.chorem.lima.ui.MainViewImpl; import org.nuiton.i18n.I18n; import java.util.Locale; @@ -41,13 +37,15 @@ * to use log facility, just put in your code: log.info(\"...\"); */ static private Log log = LogFactory.getLog(LimaContext.class); + /** * l'intance partagée accessible après un appel à la méthode * {@link #init()} */ protected static LimaContext instance; - public static JAXXContextEntryDef<MainView> MAIN_UI_ENTRY_DEF = Util.newContextEntryDef("mainUI", MainView.class); + public static JAXXContextEntryDef<MainView> MAIN_UI_ENTRY_DEF = JAXXUtil.newContextEntryDef("mainUI", MainView.class); + /** * @return <code>true</code> si le context a été initialisé via la méthode * {@link #init()}, <ocde>false</code> autrement. @@ -90,16 +88,6 @@ return instance; } - /** - * neogia factory - */ - protected ServiceFactory neogiaFactory; - - /** - * Data manager* - */ - protected DataManager dataManager; - public LimaConfig getConfig() { return getContextValue(LimaConfig.class); } @@ -108,29 +96,14 @@ Locale locale = getConfig().getLocale(); I18n.init(locale); - /** Default Locale for DatePicker **/ + // Default Locale for DatePicker Locale.setDefault(locale); - DTOHelper.setLocale(locale); } - public ServiceFactory getNeogiaFactory() { - if (neogiaFactory == null) { - neogiaFactory = ServiceFactory.getServiceFactory(); - } - return neogiaFactory; + public MainView getMainUI() { + return (MainView) MAIN_UI_ENTRY_DEF.getContextValue(this); } - public MainViewImpl getMainUI() { - return (MainViewImpl) MAIN_UI_ENTRY_DEF.getContextValue(this); - } - - public DataManager getDataManager() { - if (dataManager == null) { - dataManager = new DataManager(); - } - return dataManager; - } - /** * close the application's context. * Copied: trunk/lima-swing/src/main/java/org/chorem/lima/LimaMain.java (from rev 2802, trunk/lima-swing/src/main/java/org/chorem/lima/Main.java) =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaMain.java (rev 0) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaMain.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -0,0 +1,272 @@ +/* *##% Lima Swing + * Copyright (C) 2008 - 2010 CodeLutin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * ##%*/ + +package org.chorem.lima; + +import static org.nuiton.i18n.I18n._; + +import java.util.List; +import java.util.Locale; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; + +import jaxx.runtime.SwingUtil; + +import org.apache.commons.beanutils.ConvertUtils; +import org.apache.commons.beanutils.Converter; +import org.apache.commons.beanutils.converters.DateConverter; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.chorem.lima.business.AccountService; +import org.chorem.lima.entity.Account; +import org.chorem.lima.service.LimaServiceFactory; +import org.chorem.lima.ui.MainView; +import org.chorem.lima.ui.MainViewHandler; +import org.chorem.lima.util.ErrorHelper; +import org.nuiton.i18n.I18n; +import org.nuiton.util.ConverterUtil; +import org.nuiton.util.StringUtil; + +/** + * Lima main. + * + * @author ore + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class LimaMain { + + /** Log. */ + private static final Log log = LogFactory.getLog(LimaMain.class); + + /** Lima configuration. */ + public static LimaConfig config; + + /** + * Lima main method. + * + * @param args program args + */ + public static void main(String[] args) { + + if (log.isInfoEnabled()) { + log.info("Lima start at " + new java.util.Date()); + log.info("Args: " + java.util.Arrays.toString(args)); + } + + try { + // init root context + final LimaContext context = init(args); + + // do actions + config = context.getContextValue(LimaConfig.class); + config.doAction(LimaConfig.Action.AFTER_INIT_STEP); + + // display main ui + if (config.isLaunchui()) { + launch(context); + } + } catch (Exception ex) { + if (log.isErrorEnabled()) { + log.error(_("Global lima exception"), ex); + } + ErrorHelper.showErrorDialog(_("Global lima exception"), ex); + System.exit(1); + } + } + + /** + * initialisation de l'application : + * <p/> + * chargement du context + * + * @param args les arguments passes a l'application + * @return le context de l'application + * @throws Exception pour toute erreur pendant l'init + */ + public static synchronized LimaContext init(String... args) throws Exception { + + // to enable javassist on webstart, must remove any securityManager, + // see if this can be dangerous (should not be since jnlp is signed ?) + // moreover it speeds up the loading :) + System.setSecurityManager(null); + + // init i18n + long t0 = System.nanoTime(); + + // FIXME cause NPE + // I18n.setInitializer(new DefaultI18nInitializer("lima-swing-i18n")); + + I18n.init(Locale.FRANCE); + if (log.isDebugEnabled()) { + log.debug("i18n loading time : " + (StringUtil.convertTime(t0, System.nanoTime()))); + } + + Runtime.getRuntime().addShutdownHook(new ShutdownHook()); + + // init root context + LimaContext context = LimaContext.init(); + LimaConfig config = context.getContextValue(LimaConfig.class); + config.parse(args); + + context.initI18n(); + + // prepare ui look&feel and load ui properties + try { + SwingUtil.initNimbusLoookAndFeel(); + } catch (Exception e) { + // could not find nimbus look-and-feel + if (log.isWarnEnabled()) { + log.warn(_("lima.warning.nimbus.landf")); + } + } + + // init date converter + Converter converter = ConverterUtil.getConverter(java.util.Date.class); + if (converter != null) { + ConvertUtils.deregister(java.util.Date.class); + DateConverter dateConverter = new DateConverter(); + dateConverter.setUseLocaleFormat(true); + ConvertUtils.register(dateConverter, java.util.Date.class); + } + + if (log.isDebugEnabled()) { + log.debug("Context init done in " + (StringUtil.convertTime(t0, System.nanoTime()))); + } + return context; + } + + protected static void launch(LimaContext context) throws Exception { + + // update splash + LimaSplash splash = new LimaSplash(); + splash.initSplash(config.getVersion()); + + // do init ui + MainViewHandler uiHandler = context.getContextValue(MainViewHandler.class); + final MainView ui = uiHandler.initUI(context, context.getConfig().isFullScreen()); + ui.setLocationRelativeTo(null); + + // defaut display home view (not closeable, but might be !) + uiHandler.showHomeView(context); + + // put services into context (or not...) + //context.setContextValue(LimaServiceFactory.getInstance().getAccountService()); + //context.setContextValue(LimaServiceFactory.getInstance().getAccountService()); + + // TODO EC-20100409 load accounts and test if there is an account plan defined + // if not, call #loadDefaultAccount() + splash.updateProgression(0.5, _("Loading accounting...")); + AccountService accountService = LimaServiceFactory.getInstance().getAccountService(); + List<Account> account = accountService.getChildrenAccounts(null); + if (CollectionUtils.isEmpty(account)) { + if (log.isInfoEnabled()) { + log.info("TODO : Propose for defaut account loading"); + } + } + + /*try { + if (log.isInfoEnabled()) { + log.info("Loading lima data..."); + } + loadData(context); + } + catch (Exception eee) { + if (log.isErrorEnabled()) { + log.error("Error durring data loading", eee); + } + }*/ + + // show ui + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + ui.setVisible(true); + } + }); + } + + public static class ShutdownHook extends Thread { + + public ShutdownHook() { + super("Shutdown Lima"); + } + + @Override + public void run() { + try { + super.run(); + + LimaContext.get().close(); + LimaServiceFactory.getInstance().destroy(); + // force to kill main thread + + if (log.isInfoEnabled()) { + log.info(_("lima.init.closed", new java.util.Date())); + } + Runtime.getRuntime().halt(0); + } catch (Exception ex) { + if (log.isErrorEnabled()) { + log.error(_("lima.init.errorclosing"), ex); + } + Runtime.getRuntime().halt(1); + } + } + } + + /** + * This method ask for user to load a default account plan. + * + * @param accountRoot database accounts + */ + public static void loadDefaultAccount(Account accountRoot) { + if (log.isDebugEnabled()) { + log.debug("Account root : " + accountRoot); + } + if (accountRoot.getSubAccounts().isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("No existing accounts"); + } + + String[] response = {_("lima.response.yes"), _("lima.response.no")}; + int n = JOptionPane.showOptionDialog(null, + _("lima.question.load.accounts"), + _("lima.question"), + JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, //do not use a custom Icon + response, //the titles of buttons + response[1]); //default button title + if (n == JOptionPane.YES_OPTION) { + /*XMLImport imports = new XMLImport(); + URL urlFile = LimaMain.class.getResource("/import/default_pcg.xml"); + try { + imports.importAccount(urlFile.openStream()); + } catch (IOException eee) { + log.error("Erreur chargement du fichier 'default_pcg.xml'", eee); + }*/ + } else { + //LimaContext.getContext().getDataManager().resetAccountModel(); + } + } + } +} Modified: trunk/lima-swing/src/main/java/org/chorem/lima/LimaSplash.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/LimaSplash.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/LimaSplash.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,3 +1,21 @@ +/* *##% Lima Swing + * Copyright (C) 2008 - 2010 CodeLutin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * ##%*/ + package org.chorem.lima; import java.awt.AlphaComposite; @@ -7,7 +25,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.chorem.lima.service.util.ProgressListener; /** * Utility class used to manage information on slash screen. @@ -25,7 +42,7 @@ * Last update : $Date$ * By : $Author$ */ -public class LimaSplash implements ProgressListener { +public class LimaSplash { /** Log. */ static private Log log = LogFactory.getLog(LimaSplash.class); Deleted: trunk/lima-swing/src/main/java/org/chorem/lima/Main.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/Main.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/Main.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,286 +0,0 @@ -/** - * *##% Lima Main - * Copyright (C) 2008 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ -package org.chorem.lima; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.chorem.lima.ui.MainView; -import org.chorem.lima.ui.MainViewHandler; -import org.chorem.lima.dto.AccountDTO; -import org.chorem.lima.imports.XMLImport; -import org.chorem.lima.service.ServiceFactory; - -import static org.nuiton.i18n.I18n._; - -import java.io.IOException; -import java.net.URL; -import java.util.Locale; - -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; - -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.ErrorDialogUI; -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.beanutils.converters.DateConverter; -import org.chorem.lima.tree.model.AccountTreeTableModel; -import org.nuiton.i18n.I18n; -import org.nuiton.i18n.init.DefaultI18nInitializer; -import org.nuiton.util.ConverterUtil; -import org.nuiton.util.StringUtil; - -/** - * @author ore - */ -public class Main { - - private static final Log log = LogFactory.getLog(Main.class); - - /** - * @param args les arguments passes au programme - */ - public static void main(String[] args) { - - long startingTime = System.nanoTime(); - log.info("Lima start at " + new java.util.Date() + " args: " + java.util.Arrays.toString(args)); - - try { - - // init root context - final LimaContext context = init(args); - - log.info(_("lima.init.context.done", StringUtil.convertTime(startingTime, System.nanoTime()))); - - LimaConfig config = context.getContextValue(LimaConfig.class); - - config.doAction(LimaConfig.AFTER_INIT_STEP); - - if (config.isDisplayMainUI()) { - // on affiche l'ui principale - - launch(context); - } - } catch (Exception e) { - ErrorDialogUI.showError(e); - log.error(e.getMessage(), e); - System.exit(1); - } - } - - /** - * initialisation de l'application : - * <p/> - * chargement du context - * - * @param args les arguments passes a l'application - * @return le context de l'application - * @throws Exception pour toute erreur pendant l'init - */ - public static synchronized LimaContext init(String... args) throws Exception { - - // to enable javassist on webstart, must remove any securityManager, - // see if this can be dangerous (should not be since jnlp is signed ?) - // moreover it speeds up the loading :) - System.setSecurityManager(null); - - long t0 = System.nanoTime(); - - I18n.setInitializer(new DefaultI18nInitializer("lima-main-i18n")); - - I18n.init(Locale.FRANCE); - - if (log.isDebugEnabled()) { - log.debug("i18n loading time : " + (StringUtil.convertTime(t0, System.nanoTime()))); - } - - Runtime.getRuntime().addShutdownHook(new ShutdownHook()); - - // init root context - LimaContext context = LimaContext.init(); - - LimaConfig config = context.getContextValue(LimaConfig.class); - - config.parse(args); - - context.initI18n(); - - // prepare ui look&feel and load ui properties - try { - SwingUtil.initNimbusLoookAndFeel(); - } catch (Exception e) { - // could not find nimbus look-and-feel - log.warn(_("lima.warning.nimbus.landf")); - } catch (Throwable e) { - log.warn(_("lima.warning.no.ui")); - // pas d'environnement d'ui - config.setCanUseUI(false); - } - - // init date converter - Converter converter = ConverterUtil.getConverter(java.util.Date.class); - if (converter != null) { - ConvertUtils.deregister(java.util.Date.class); - - DateConverter dateConverter = new DateConverter(); - dateConverter.setUseLocaleFormat(true); - ConvertUtils.register(dateConverter, java.util.Date.class); - } - -// if (config.isCanUseUI()) { -// // chargement de la configuration des uis -// SwingUtil.loadUIConfig(LimaConfig.APPLICATION_PROPERTIES, null); -// } - - ServiceFactory.init(null); - - if (log.isDebugEnabled()) { - log.debug("init done in " + (StringUtil.convertTime(t0, System.nanoTime()))); - } - return context; - } - - public static void launch(LimaContext context) throws Exception { - - MainViewHandler uiHandler = context.getContextValue(MainViewHandler.class); - - // do init ui - final MainView ui = uiHandler.initUI(context, context.getConfig().isFullScreen()); - - if (log.isInfoEnabled()) { - log.info(_("lima.init.ui.done")); - } - - try { - if (log.isInfoEnabled()) { - log.info("Loading lima data..."); - } - loadData(context); - } - catch (Exception eee) { - if (log.isErrorEnabled()) { - log.error("Error durring data loading", eee); - } - } - - // show ui - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ui.setVisible(true); - } - }); - } - - /** - * Load datas and update progression into splash screen. - * - * @param context application context - */ - protected static void loadData(LimaContext context) { - LimaSplash splash = new LimaSplash(); - splash.initSplash(context.getConfig().getVersion()); - - // Chargement des journaux - splash.updateProgression(0.05, _("lima.progressBar.load.etape1")); - DataManager dataManager = context.getDataManager(); - dataManager.getJournalModel(); - - // Chargement des comptes - splash.updateProgression(0.30, _("lima.progressBar.load.etape2")); - AccountTreeTableModel accountModel = dataManager.getAccountModel(); - loadDefaultAccount(accountModel.getData()); - - // Chargement des status - splash.updateProgression(0.50, _("lima.progressBar.load.etape3")); - dataManager.getStatus(); - - // Chargement des periodes - splash.updateProgression(0.60, _("lima.progressBar.load.etape4")); - dataManager.getPeriodes(); - - // Chargement des transactions - splash.updateProgression(0.70, _("lima.progressBar.load.etape5")); - dataManager.getTransactionModel(splash); - - // TODO needed or closed by UI ? - // splash.closeSplash(); - } - - public static class ShutdownHook extends Thread { - - public ShutdownHook() { - super("shutdown lima"); - } - - @Override - public void run() { - try { - super.run(); - - LimaContext.get().close(); - // force to kill main thread - - log.info(_("lima.init.closed", new java.util.Date())); - Runtime.getRuntime().halt(0); - } catch (Exception ex) { - log.error("error while closing " + ex.getMessage(), ex); - Runtime.getRuntime().halt(1); - } - } - } - - /** - * This method ask for user to laod a default account plan. - * - * @param accountRoot database accounts - */ - public static void loadDefaultAccount(AccountDTO accountRoot) { - if (log.isDebugEnabled()) { - log.debug("Account root : " + accountRoot); - } - if (accountRoot.getChildren().isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("No existing accounts"); - } - - String[] response = {_("lima.response.yes"), _("lima.response.no")}; - int n = JOptionPane.showOptionDialog(null, - _("lima.question.load.accounts"), - _("lima.question"), - JOptionPane.YES_NO_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, //do not use a custom Icon - response, //the titles of buttons - response[1]); //default button title - if (n == JOptionPane.YES_OPTION) { - XMLImport imports = new XMLImport(); - URL urlFile = Main.class.getResource("/import/default_pcg.xml"); - try { - imports.importAccount(urlFile.openStream()); - } catch (IOException eee) { - log.error("Erreur chargement du fichier 'default_pcg.xml'", eee); - } - } else { - LimaContext.getContext().getDataManager().resetAccountModel(); - } - } - } -} Copied: trunk/lima-swing/src/main/java/org/chorem/lima/actions/MiscAction.java (from rev 2802, trunk/lima-swing/src/main/java/org/chorem/lima/LimaAction.java) =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/actions/MiscAction.java (rev 0) +++ trunk/lima-swing/src/main/java/org/chorem/lima/actions/MiscAction.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -0,0 +1,56 @@ +/* *##% Lima Main + * Copyright (C) 2008 - 2010 CodeLutin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * ##%*/ + +package org.chorem.lima.actions; + +import static org.nuiton.i18n.I18n._; + +import org.chorem.lima.LimaConfig; +import org.chorem.lima.LimaMain; + +/** + * Les actions appellables via {@link LimaMain}. + * + * @author tony + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class MiscAction { + + /** La configuration de l'application. */ + protected LimaConfig config; + + public MiscAction(LimaConfig config) { + this.config = config; + } + + public void help() { + System.out.println(_("lima.message.help.usage")); + System.out.println("Options (set with --option <key> <value>:"); + for (LimaConfig.Option o : LimaConfig.Option.values()) { + System.out.println("\t" + o.key + "(" + o.defaultValue + "):" + o.description); + } + + System.out.println("Actions:"); + for (LimaConfig.Action a : LimaConfig.Action.values()) { + System.out.println("\t" + java.util.Arrays.toString(a.aliases) + "(" + a.action + "):" + a.description); + } + } +} Added: trunk/lima-swing/src/main/java/org/chorem/lima/util/ErrorHelper.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/util/ErrorHelper.java (rev 0) +++ trunk/lima-swing/src/main/java/org/chorem/lima/util/ErrorHelper.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -0,0 +1,160 @@ +/* + * *##% Lima Main + * Copyright (C) 2010 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.chorem.lima.util; + +import static org.nuiton.i18n.I18n._; + +import java.awt.Component; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import javax.swing.JOptionPane; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.mail.EmailException; +import org.apache.commons.mail.MultiPartEmail; +import org.chorem.lima.LimaMain; +import org.jdesktop.swingx.JXErrorPane; +import org.jdesktop.swingx.error.ErrorInfo; +import org.jdesktop.swingx.error.ErrorReporter; + +/** + * Error helper. + * + * Used to easily switch real exception interface. Currently used : swingx. + * + * @author chatellier + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +public class ErrorHelper implements ErrorReporter { + + /** Log. */ + private static final Log log = LogFactory.getLog(ErrorHelper.class); + + /** + * Display a user friendly error frame. + * + * @param parent parent component + * @param message message for user + * @param cause exception cause + */ + public static void showErrorDialog(Component parent, String message, + Throwable cause) { + JXErrorPane pane = new JXErrorPane(); + ErrorInfo info = new ErrorInfo(_("lima.error.errorpane.title"), + _("lima.error.errorpane.htmlmessage", message), null, null, + cause, null, null); + pane.setErrorInfo(info); + pane.setErrorReporter(new ErrorHelper()); + JXErrorPane.showDialog(parent, pane); + } + + /** + * Display a user friendly error frame. + * + * @param message message for user + */ + public static void showErrorDialog(String message) { + showErrorDialog(message, null); + } + + /** + * Display a user friendly error frame. + * + * @param message message for user + * @param cause exception cause + */ + public static void showErrorDialog(String message, Throwable cause) { + showErrorDialog(null, message, cause); + } + + /* + * @see org.jdesktop.swingx.error.ErrorReporter#reportError(org.jdesktop.swingx.error.ErrorInfo) + */ + @Override + public void reportError(ErrorInfo errorInfo) throws NullPointerException { + + try { + String emailTo = LimaMain.config.getSupportEmail(); + + MultiPartEmail email = new MultiPartEmail(); + // smtp + email.setHostName("smtp"); + // to + email.addTo(emailTo, "Support"); + // from + email.setFrom("no-reply@nuiton.org", "Lima"); + // subject + email.setSubject("Project error notification : Lima"); + + // message description + String message = formatMessage("Project", "Lima " + LimaMain.config.getVersion()); + message += formatMessage("Date", new Date().toString()); + message += formatMessage("Title", errorInfo.getTitle()); + message += formatMessage("Description", errorInfo.getBasicErrorMessage().replaceAll("<[^>]+>", "")); + + // message configuration + message += formatMessage("Configuration", null); + List<String> propertiesNames = new ArrayList<String>(LimaMain.config.getOptions().stringPropertyNames()); + Collections.sort(propertiesNames); + for (String propertyName : propertiesNames) { + // security, don't send string containing password : + if (!propertyName.contains("pass")) { + message += "\t" + propertyName + " : " + LimaMain.config.getOptions().getProperty(propertyName) + "\n"; + } + } + + // message exception + StringWriter out = new StringWriter(); + PrintWriter writer = new PrintWriter(out); + errorInfo.getErrorException().printStackTrace(writer); + message += formatMessage("Exception", out.toString()); + + // TODO EC-20100409 i18n files are iso encoded ? + email.setContent(message, "text/plain; charset=ISO-8859-9"); + + // send mail + email.send(); + + JOptionPane.showMessageDialog(null, "A report message has been sent to " + emailTo); + } catch (EmailException ex) { + if (log.isErrorEnabled()) { + log.error("Can't send report email" ,ex); + } + } + } + + protected String formatMessage(String category, String content) { + String formatted = category + " :\n"; + if (StringUtils.isNotEmpty(content)) { + formatted += "\t" + content + "\n"; + } + return formatted; + } +} Property changes on: trunk/lima-swing/src/main/java/org/chorem/lima/util/ErrorHelper.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Deleted: trunk/lima-swing/src/main/java/org/chorem/lima/util/ServiceHelper.java =================================================================== --- trunk/lima-swing/src/main/java/org/chorem/lima/util/ServiceHelper.java 2010-04-09 16:19:40 UTC (rev 2850) +++ trunk/lima-swing/src/main/java/org/chorem/lima/util/ServiceHelper.java 2010-04-09 16:21:50 UTC (rev 2851) @@ -1,354 +0,0 @@ -/** - * *##% Lima service - * Copyright (C) 2008 CodeLutin - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* - */ - -package org.chorem.lima.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import static org.nuiton.i18n.I18n._; - -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -/** - * @author chemit - * @author Rémi Chapelet - */ -public class ServiceHelper { - - /** - * log - */ - private static final Log log = LogFactory.getLog(ServiceHelper.class); - /** - * Transaction status type - */ - public static final String TR_FINALIZED = "TR_FINALIZED"; - public static final String TR_BALANCED = "TR_BALANCED"; - public static final String TR_WIP = "TR_WIP"; - /** - * Period status type - */ - public static final String PE_OPEN = "PE_OPEN"; - public static final String PE_CLOSETMP = "PE_CLOSETMP"; - public static final String PE_CLOSE = "PE_CLOSE"; - /** - * Responses - */ - public static final String RESPOND_SUCCESS = "success"; - public static final String RESPOND_ERROR = "error"; - - /** - * Account Error - */ - public static final String ACCOUNT_DOUBLE = "account_double"; - public static final String ACCOUNT_NOT_MASTER = "account_not_master"; - public static final String ACCOUNT_NOT_EXIST = "account_not_exist"; - public static final String ACCOUNT_WITH_ENTRIES = "account_with_entries"; - - /** - * Entries Error - */ - public static final String ENTRY_NOT_EXIST = "entry_not_exist"; - - /** - * Journal - */ - public static final String JOURNAL_DOUBLE = "journal_double"; - public static final String JOURNAL_NOT_EXIST = "journal_not_exist"; - public static final String JOURNAL_WITH_TRANSACTIONS = "journal_with_transactions"; - - /** - * Period - */ - public static final String PERIOD_CREATE_TIMESPANS = "period_create_timespan"; - public static final String PERIOD_TIMESPAN_NOT_BLOCK = "period_timespan_not_block"; - public static final String PERIOD_TIMESPAN_BLOCK = "period_timespan_block"; - public static final String PERIOD_ALL_TIMESPAN = "period_all_timespan"; - public static final String PERIOD_NOT_EXIST = "period_not_exist"; - - public static final String PERIOD_PREC_NOT_BLOCK = "period_prec_not_block"; - public static final String PERIOD_NEXT_NOT_BLOCK = "period_next_not_block"; - - /** - * Transaction - */ - public static final String TRANSACTION_NOT_JOURNAL = "transaction_not_journal"; - public static final String TRANSACTION_NOT_TIMESPAN = "transaction_not_timespan"; - public static final String TRANSACTION_TIMESPAN_BLOCKED = "transaction_timespan_blocked"; - public static final String TRANSACTION_NOT_EXIST = "transaction_not_exist"; - public static final String TRANSACTION_NOT_BALANCED = "transaction_not_balanced"; - - protected ServiceHelper() { - // no instance - } - - /** - * TODO - * - * @param accounts TODO - * @return TODO - */ - public static List<Account> getAllFlatAccount(Account accounts) { - List<Account> flatList = new LinkedList<Account>(); - concatListAccount(flatList, accounts.getChildren()); - return flatList; - } - - /** - * TODO - * - * @param res TODO - * @param add TODO - */ - private static void concatListAccount(List<Account> res, List<Account> add) { - res.addAll(add); - for (Account acc : add) { - if (acc.getChildren() != null) { - concatListAccount(res, acc.getChildren()); - } - } - } - - /** - * TODO - * - * @param periods TODO - * @return TODO - */ - public static List<PeriodDTO> getAllFlatPeriod(List<PeriodDTO> periods) { - List<PeriodDTO> flatList = new LinkedList<PeriodDTO>(); - for (PeriodDTO period : periods) { - flatList.add(period); - flatList.addAll(period.getChildren()); - } - return flatList; - } - - /** - * @param date - * @return - */ - public static String dateToMonth(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - switch (cal.get(Calendar.MONTH)) { - case Calendar.JANUARY: - return _("lima.date.january"); - case Calendar.FEBRUARY: - return _("lima.date.february"); - case Calendar.MARCH: - return _("lima.date.march"); - case Calendar.APRIL: - return _("lima.date.april"); - case Calendar.MAY: - return _("lima.date.may"); - case Calendar.JUNE: - return _("lima.date.june"); - case Calendar.JULY: - return _("lima.date.july"); - case Calendar.AUGUST: - return _("lima.date.august"); - case Calendar.SEPTEMBER: - return _("lima.date.september"); - case Calendar.OCTOBER: - return _("lima.date.october"); - case Calendar.NOVEMBER: - return _("lima.date.november"); - case Calendar.DECEMBER: - return _("lima.date.december"); - } - return null; - } - /** - * @param date the date to inspect - * @return the year of the given date - */ - public static String dateToYear(Date date) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - return "" + cal.get(Calendar.YEAR); - } - - /** - * @param trans - * @return - */ - public static boolean isEditable(TransactionDTO trans) { - String finalizedKey = ServiceHelper.PE_CLOSE; - return !trans.getPeriod().getStatus().getIdType().equals(finalizedKey); - } - - /** - * @param entry - * @return - */ - public static boolean isEditable(EntryDTO entry) { - return isEditable(entry.getTransaction()); - } - - public static StatusDTO findStatusByType(List<StatusDTO> list, String id) { - if (id == null || list == null) { - return null; - } - for (StatusDTO status : list) { - if (id.equals(status.getIdType())) { - return status; - } - } - log.warn("Status " + id + " couldn't be found."); - return null; - } - - public static JournalDTO findJournalById(List<JournalDTO> list, String id) { - if (id == null || list == null) { - return null; - } - for (JournalDTO journal : list) { - if (id.equalsIgnoreCase(journal.getIdName()) || id.equalsIgnoreCase(journal.getPrefix()) || id.equals(journal.getIdSeq())) { - return journal; - } - } - log.warn("Journal " + id + " couldn't be found."); - return null; - } - - public static StatusDTO findStatusById(List<StatusDTO> list, String id) { - if (id == null || list == null) { - return null; - } - for (StatusDTO Status : list) { - if (id.equals(Status.getIdName())) { - return Status; - } - } - log.warn("Status " + id + " couldn't be found."); - return null; - } - - public static AccountDTO findAccountById(List<AccountDTO> list, String id) { - if (id == null || list == null) { - return null; - } - for (AccountDTO account : list) { - if (id.equals(account.getIdNumber())) { - return account; - } - } - log.warn("Account " + id + " couldn't be found."); - return null; - } - - public static PeriodDTO findPeriodById(List<PeriodDTO> list, String id) { - if (id == null || list == null) { - return null; - } - for (PeriodDTO period : list) { - if (id.equals(period.getIdSeq())) { - return period; - } - } - log.warn("Period " + id + " couldn't be found."); - return null; - } - - public static PeriodDTO findPeriodByDate(List<PeriodDTO> list, Date d) { - if (d == null || list == null) { - return null; - } - PeriodDTO periodSearch = null; - for (PeriodDTO period : list) { - if ( betweenDate(d,period.getBegin(),period.getEnd()) ) { - periodSearch = period; - } - } - if ( periodSearch == null) - { - log.warn("Period with this date " + d + " couldn't be found."); - } - return periodSearch; - } - - /** - * Permet de rechercher toutes les transactions appartenant à une période - * donnée. - * @param period - * @param listTransactions - * @return - */ - public static List<TransactionDTO> findTransactionByPeriod(PeriodDTO period,List<TransactionDTO> listTransactions) - { - if (period == null || listTransactions == null) { - return null; - } - List<TransactionDTO> ListTransactionSearch = new LinkedList<TransactionDTO>(); - // Si période annuelle - if ( period.getParent() == null ) - { - for (TransactionDTO transaction : listTransactions) - { - if ( transaction.getPeriod().getParent().equals(period) ) - { - ListTransactionSearch.add(transaction); - } - } - } else { - // Si période mensuelle - for (TransactionDTO transaction : listTransactions) - { - if ( transaction.getPeriod().equals(period) ) - { - ListTransactionSearch.add(transaction); - } - } - } - return ListTransactionSearch; - } - - /** - * Permet de renvoyer vrai si une date d donnée est entre deux dates. - * @param d date se trouvant ou non dans la période - * @param dateBegin date de début de période - * @param dateEnd date de fin de période - * @return - */ - public static boolean betweenDate (Date d, Date dateBegin, Date dateEnd) - { - boolean result = false; - if ( ( (compareDate(d,dateBegin) == 0) || (compareDate(d,dateBegin) == 1) ) - && ( (compareDate(d,dateEnd) == 0) || (compareDate(d,dateEnd) == -1) ) ) - { - result = true; - } - return result; - } - - /** - * Implémentation de compareTO. Si il y a besoin, il est possible de la modifier. - * @param d1 - * @param d2 - * @return - */ - public static int compareDate(Date d1, Date d2) - { - return d1.compareTo(d2); - } -}
participants (1)
-
echatellier@users.chorem.org